Issue updating modal with slack using views.update api - slack

When I am trying to update my modal in my slack app it is giving this error message: Error returned when the given view_id or external_id doesn't exist.
This is my code of updating the modal, help me what is going wrong here or if something is missing:
if (userAction.getType().equalsIgnoreCase("view_submission")) {
log.info("inside view_submission..");
List<LayoutBlock> message = new ArrayList();
ButtonElement buttonElement = ButtonElement.builder()
.actionId("submit")
.value("submit")
.text(PlainTextObject.builder().text("submit").build()).build();
message.add(SectionBlock.builder()
.accessory(buttonElement)
.text(MarkdownTextObject.builder().text("hey this is my updated modal").build()).build());
ViewTitle viewTitle = ViewTitle.builder()
.text("Header for 2nd modal")
.type("plain_text")
.emoji(true).build();
ViewSubmit viewSubmit = ViewSubmit.builder()
.text("Submit")
.type("plain_text").build();
View view = View.builder()
.type("modal")
.callbackId("second_view")
.title(viewTitle)
.submit(viewSubmit)
.blocks(message).build();
ViewsUpdateRequest viewsUpdateRequest = ViewsUpdateRequest.builder()
.viewId(userAction.getViewModel().getId())
.hash(userAction.getViewModel().getHash())
.view(view)
.token(botToken).build();
slackhelperService.sendViews(viewsUpdateRequest, botToken);
return;
}

Related

Client-Side error when uploading image on server ASP.NET Core

I am struggling with uploading an image from thew client-side to a folder on the server-side in .Net Core.I used Postman to check if the method on the server-side is working and it does without any problem,but when I try to upload an image from the client-side,I get an error on the server-side of type NullReferenceException:Object reference not set to an instance of an object.This is the Post method on the server-side:
[HttpPost]
public async Task Post(IFormFile file)
{
if (string.IsNullOrWhiteSpace(_environment.WebRootPath))
{
_environment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
//var fileName = file.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
if (!Directory.Exists(uploads)) Directory.CreateDirectory(uploads);
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
Apparently the method is thrown where I check if the length of the file is bigger than 0.On the client-side I get error "500 internal server error" and I tried to check using the debugger where exactly the error is thrown but i can't find anything that could resemble an error of some sort.This is the API method for the client-side:
public async Task UploadPictureAsync(MediaFile image)
{
User user = new User();
string pictureUrl = "http://10.0.2.2:5000/api/UploadPicture";
HttpContent fileStreamContent = new StreamContent(image.GetStream());
// user.Picture=GetImageStreamAsBytes(image.GetStream());
fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {FileName=Guid.NewGuid() + ".Png",Name="image"};
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient(clientHandler))
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent);
var response = await client.PostAsync(pictureUrl, formData);
if(response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
}
}
The image is declared in the Model as byte array:
public byte[] Picture { get; set; }
Does someone understand why my POST method has this behavior since the server-side works perfectly but fails when I try to upload an image from the client-side?What I find weird though is that when i read the error and I look at the Content-Type it is "text/plain" instead of "form-data" and I have tried to set it at the MutipartFormDataContent like this:
formData.Headers.ContentType.MediaType = "multipart/form-data";
I also tried to set the MediaTypeHeaderValue on the client like this:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
I still get the wrong content type.
I have also tried a different approach with Stream instead of MediaFile but without any luck as it did not even hit the break point in debugger mode for the response.Any help would be appreciated! :)
I have managed to find the answer finalllyyyyy!!!The problem was on the client-side as I suspected and guess what,it was all about the correct name.It turns out that since on the server side I have IFormFile file I had to change the client side to take the parameter name "file" instead of image as well so that it could work.Thank you #Jason for the suggestions as I didn't understand the error from the first place and did some debugging on the server-side to help me figure it out.

Xamarin and Auth0 - getting refresh tokens

I was following the guide provided by auth0 and have been authenticating just fine, but I am getting tired of having to log in everytime I open the app and wanted to start storing and taking advantage of refresh tokens. However I can't seem to get a refresh token, its always null.
In my LoginActivity I have the following
_client = new Auth0Client(new Auth0ClientOptions
{
Domain = Resources.GetString(Resource.String.auth0_domain),
ClientId = Resources.GetString(Resource.String.auth0_client_id),
//Scope = "offline_access",
Activity = this
});
and handling the log in like so
_authorizeState = await _client.PrepareLoginAsync(new { audience = "myaudience.blahblahblah"});
protected override async void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
var loginResult = await _client.ProcessResponseAsync(intent.DataString, _authorizeState);
var sb = new StringBuilder();
if (loginResult.IsError)
{
sb.AppendLine($"An error occurred during login: {loginResult.Error}");
}
else
{
var mainActivity = new Intent(this, typeof(MainActivity));
mainActivity.PutExtra("token", loginResult.AccessToken);
StartActivity(mainActivity);
Finish();
}
}
If I include the scope then I get an error back that the response doesn't contain an identity token. if I don't include I just don't get the refresh token.
For me, the trick were add Scope row as shown below.
The original code:
client = new Auth0Client(new Auth0ClientOptions
{
Domain = Resources.GetString(Resource.String.auth0_domain),
ClientId = Resources.GetString(Resource.String.auth0_client_id),
Activity = this
});
Changed and working one:
client = new Auth0Client(new Auth0ClientOptions
{
Domain = Resources.GetString(Resource.String.auth0_domain),
ClientId = Resources.GetString(Resource.String.auth0_client_id),
Activity = this,
Scope = "openid offline_access"
});
I tried only with this:
Scope = "offline_access"
But received an error, until the "openid" in the front of it.

Proactive Bot Messaging - CreateDirectConversation - unauthorized exception

I am creating a bot to proactively start a conversation with an account I have never had a previous conversation with. I have created another controller that I am posting to and doing the following steps:
public class OutboundController : ApiController {
public HttpResponseMessage Post([FromUri] int id, [FromBody] OutboundData outboundData) {
MicrosoftAppCredentials.TrustServiceUrl(outboundData.ServiceUrl);
//create conversation
var connector = new ConnectorClient(new Uri(outboundData.ServiceUrl));
var botAccount = new ChannelAccount { Id = outboundData.FromAccountId, Name = outboundData.FromAccountName };
var toAccount = new ChannelAccount { Id = outboundData.ToAccountId, Name = outboundData.ToAccountName };
if(!MicrosoftAppCredentials.IsTrustedServiceUrl(outboundData.ServiceUrl)) {
throw new Exception("service URL is not trusted!");
}
var conversationResponse = connector.Conversations.CreateDirectConversation(botAccount, toAccount);
var client = new BuslogicClient();
var confirmData = client.GetOutboundData(id);
var greetingMessage = CreateGreetingMessage(confirmData);
var convoMessage = Activity.CreateMessageActivity();
convoMessage.Text = greetingMessage;
convoMessage.From = botAccount;
convoMessage.Recipient = toAccount;
convoMessage.Conversation = new ConversationAccount(id: conversationResponse.Id);
convoMessage.Locale = "en-Us";
connector.Conversations.SendToConversationAsync((Activity)convoMessage);
string message = string.Format("I received correlationid:{0} and started conversationId:{1}", id, conversationResponse.Id);
var response = Request.CreateResponse(HttpStatusCode.OK, message);
return response;
}
When I call connector.Conversations.CreateDirectConversation I am getting the following exception: Additional information: Authorization for Microsoft App ID [ID] failed with status code Unauthorized and reason phrase 'Unauthorized'. If I do this with appId and password blank everything works fine in the channel emulator. I've tried providing the MicrosoftAppCredentials to the constructor of the ConnectorClient, but that has no affect. I've read on other threads that the service URL must be trusted so I used MicrosoftAppCredentials.TrustServiceUrl.
versions I am using:
BotBuilder 3.5.3
Channel Emulator 3.0.0.59
The use-case for my bot is to post to the outbound controller with some user info to create a proactive message to be sent out (specifically SMS). If the user responds to my message it will be intercepted by the messages controller and passed to my dialogs for further processing and conversation responses on that same channel.
I've also taken a look at: https://github.com/Microsoft/BotBuilder/issues/2155 but don't quite understand solution described in the comments or if it even pertains to the issue I'm trying to solve.
Any suggestions or help would be appreciated!
You need to pass credentials explicitly to connector:
var credentials = new MicrosoftAppCredentials("YoursMicrosoftAppId", "YoursMicrosoftAppPassword");
var connector = new ConnectorClient(serviceUrl, credentials);

Loading a picture using AS3 issues

I am trying to upload a picture when a user clicks on a button using AS3. I have a button and a progress bar on the stage. This is the relevant code:
var myLoader:Loader = new Loader();
myPB.source = myLoader.contentLoaderInfo;
btn_one.addEventListener(MouseEvent.CLICK, btnImage);
function btnImage(event:MouseEvent):void{
myLoader.load(new URLRequest("MyPic.jpeg"));
addCild(myPB);
removeChild(myPB);
btn_one = null;
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, finishImage);
function finishImage(event:Event):void{
addChild(myLoader);
removeChild(myLoader);
btn_one = null;
When I execute the code this error appears Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found
Any ideas were I am going wrong?
var myLoader:Loader = new Loader();
//myPB.source = myLoader.contentLoaderInfo;
btn_one.addEventListener(MouseEvent.CLICK, btnImage);
function btnImage(event:MouseEvent):void{
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, finishImage);
myLoader.load(new URLRequest("MyPic.jpeg"));
//addCild(myPB);
//removeChild(myPB);
btn_one = null;
}
function finishImage(event:Event):void{
addChild(myLoader);
//removeChild(myLoader);
btn_one = null;
}
This should work. I don't know what you try to accomplish with adding a Child and removing the same child directly afterwards.
Hope this helps

Create Event C# SDK Failes - Getting (OAuthException) (#324) Missing or invalid image file

I am trying to create an event using the C# SDK. I am using the code from the following blog:
http://facebooksdk.blogspot.co.uk/2011/05/facebook-create-event.html
And I am using an image that I copied from an existing event on Facebook.
I am getting however the following error:
(OAuthException) (#324) Missing or invalid image file
Does anyone have an idea how to make it work?
Many thanks!
The code is as follows:
public string CreateEvent()
{
var fb = new FacebookWebClient();
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details for the event
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
//Add the event logo image
//You can add the event logo too
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\DevProjects\O2\o2PriorityFB\o2PriorityFB.Web\Images\logo.jpg"
};
logo.SetValue(System.IO.File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = fb.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
You need to include a valid access token in the request. Also, I would recommend upgrading to V6 of the Facebook C# SDK. For the version you are using though you need to pass the access token into the constructor of FacebookWebClient as follows:
var fb = new FacebookWebClient("valid_facebook_access_token");

Resources