Team creation with C# for RC glip - ringcentral

We are trying to use C# code to create team in Glip.
I already referred to this article:
https://medium.com/ringcentral-developers/apis-for-ringcentral-team-messaging-tasks-a-brief-intro-4a2c38c8ce2d
Though it has Glip APIs references but not exactly what we are looking for. Still didn't find reference to start with the code.
Any reference for Team creation using C# code using Glip API. What other permission required for creating the app to access Glip API other than Glip?

Step by step guidance is given for team creation in C# here:
https://developers.ringcentral.com/guide/team-messaging/quick-start#c#
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using RingCentral;
using Newtonsoft.Json;
namespace Create_Team
{
class Program
{
const string RINGCENTRAL_CLIENTID = "<ENTER CLIENT ID>";
const string RINGCENTRAL_CLIENTSECRET = "<ENTER CLIENT SECRET>";
const bool RINGCENTRAL_PRODUCTION = false;
const string RINGCENTRAL_USERNAME = "<YOUR ACCOUNT PHONE NUMBER>";
const string RINGCENTRAL_PASSWORD = "<YOUR ACCOUNT PASSWORD>";
const string RINGCENTRAL_EXTENSION = "<YOUR EXTENSION, PROBABLY '101'>";
static RestClient restClient;
static void Main(string[] args)
{
restClient = new RestClient(RINGCENTRAL_CLIENTID, RINGCENTRAL_CLIENTSECRET, RINGCENTRAL_PRODUCTION);
restClient.Authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD).Wait();
create_team().Wait();
}
static private async Task create_team()
{
var parameters = new GlipPostTeamBody();
parameters.#public = true;
parameters.name = "Fun team";
parameters.description = "Let chit chat here";
var member1 = new CreateGlipMember();
member1.email = "member.1#gmail.com";
var member2 = new CreateGlipMember();
member2.email = "member.2#gmail.com";
parameters.members = new CreateGlipMember[] { member1, member2 };
var response = await restClient.Restapi().Glip().Teams().Post(parameters);
var jsonStr = JsonConvert.SerializeObject(response);
Console.WriteLine(jsonStr);
}
}
}
Hope this above example help

Related

How to running method webservice in background from android xamarin form

I want running this method UpdateStatus when he close app
It is my coding method UpdateStatus in android:
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
Could you help me ?
In the Android, When you close your applcation, based on my research, above code can not be run, because all of threads or services will be killed when applcation is killed.
If you want to run above code when application in the background, you can can use background service to achieve that, due to background execution limits in Android 8.0 or later, if you code need some time to execute, and you want code running stably, Foreground Services is a good choice.
In xamarin forms, you can use dependenceService in the OnSleep method of App.xaml.cs
OnSleep - called each time the application goes to the background.
You can create a interface.
IService.cs
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//==============================do you work=====================
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is similar thread:
How to create service doing work at period time in Xamarin.Forms?

Problems with AWS SDK .NET

I am trying to retrieve images from my bucket to send to my mobile apps, I currently have the devices accessing AWS directly, however I am adding a layer of security and having my apps (IOS and Android) now make requests to my server which will then respond with DynamoDB and S3 data.
I am trying to follow the documentation and code samples provided by AWS for .Net and they worked seamlessly for DynamoDB, I am running into problems with S3.
S3 .NET Documentation
My problem is that if I provide no credentials, I get the error:
Failed to retrieve credentials from EC2 Instance Metadata Service
This is expected as I have IAM roles set up and only want my apps and this server (in the future, only this server) to have access to the buckets.
But when I provide the credentials, the same way I provided credentials for DynamoDB, my server waits forever and doesn't receive any responses from AWS.
Here is my C#:
<%# WebHandler Language="C#" Class="CheckaraRequestHandler" %>
using System;
using System.Web;
using System.Collections.Generic;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System.IO;
using System.Threading.Tasks;
public class CheckaraRequestHandler : IHttpHandler
{
private const string bucketName = "MY_BUCKET_NAME";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USEast1;
public static IAmazonS3 client = new AmazonS3Client("MY_ACCESS_KEY", "MY_SECRET_KEY", RegionEndpoint.USEast1);
public void ProcessRequest(HttpContext context)
{
if (context.Request.HttpMethod.ToString() == "GET")
{
string userID = context.Request.QueryString["User"];
string Action = context.Request.QueryString["Action"];
if (userID == null)
{
context.Response.ContentType = "text/plain";
context.Response.Write("TRY AGAIN!");
return;
}
if (Action == "GetPhoto")
{
ReadObjectDataAsync(userID).Wait();
}
var client = new AmazonDynamoDBClient("MY_ACCESS_KEY", "MY_SECRET_KEY", RegionEndpoint.USEast1);
Console.WriteLine("Getting list of tables");
var table = Table.LoadTable(client, "TABLE_NAME");
var item = table.GetItem(userID);
if (item != null)
{
context.Response.ContentType = "application/json";
context.Response.Write(item.ToJson());
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("0");
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
static async Task ReadObjectDataAsync(string userID)
{
string responseBody = "";
try
{
string formattedKey = userID + "/" + userID + "_PROFILEPHOTO.jpeg";
//string formattedKey = userID + "_PROFILEPHOTO.jpeg";
//formattedKey = formattedKey.Replace(":", "%3A");
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = formattedKey
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
string title = response.Metadata["x-amz-meta-title"]; // Assume you have "title" as medata added to the object.
string contentType = response.Headers["Content-Type"];
Console.WriteLine("Object metadata, Title: {0}", title);
Console.WriteLine("Content type: {0}", contentType);
responseBody = reader.ReadToEnd(); // Now you process the response body.
}
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
}
}
When I debug, this line waits forever:
using (GetObjectResponse response = await client.GetObjectAsync(request))
This is the same line that throws the credentials error when I don't provide them. Is there something that I am missing here?
Any help would be greatly appreciated.
I suspect that the AWS .NET SDK has some isses with it specifically with the async call to S3.
The async call to dynamoDB works perfect, but the S3 one hangs forever.
What fixed my problem was simply removing the async functionality (even tho in the AWS docs, the async call is supposed to be used)
Before:
using (GetObjectResponse response = await client.GetObjectAsync(request))
After:
using (GetObjectResponse response = myClient.GetObject(request))
Hopefully this helps anyone else encountering this issue.

WinRT App consume NAV web services and got this message

I did the following and got the below error msg:
The error message :
An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code
Additional information: One or more errors occurred.
If there is a handler for this exception, the program may be safely continued.
Question :
a) What seems to be the problems in above code as I just wanted to retrieve a record.
b) Must use Async Methods in WinRT or Windows store app?
c) Will below code able to retrieve record from Navision?
-----1------- Windows store App to access Nav Web Services
1.1 Added the service reference in WinRT App
1.2 Added a class1.cs in WinRT App
private async void btnImportCustomer_Click(object sender, RoutedEventArgs e)
{
Task _asyncCustomer = Class1.Customer.Listing.GetAsyncRecords("Y007");
### encounterd error here: ####
string g_strmsg = _asyncCustomer.Result.No + " “ +_asyncCustomer.Result.Name;
}
-----2---------- Class1.cs use inside WinRT App Project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MobileNAVSalesSystem
{
class Class1
{
public static string _webserviceurlpage = "http ://{0}:{1}/{2}/WS/{3}/Page/{4}";
public static string _webserviceurlcodeunit = "http://{0}:{1}/{2}/WS/{3}/Codeunit/{4}";
public static Uri _webserviceuripage = null;
public static Uri _webserviceuricodeunit = null;
#region Customer
public class Customer
{
public class Card
{
//Do something for Card Type
}
public class Listing
{
public static wsCustomerList.Customer_List_PortClient GetService()
{
_webserviceuripage = new Uri(string.Format(_webserviceurlpage, "msxxx", "7047", "DynamicsNAV_xxx", Uri.EscapeDataString("Global xxx Pte. Ltd."), "Customer List"));
System.ServiceModel.BasicHttpBinding _wSBinding = new System.ServiceModel.BasicHttpBinding();
_wSBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
_wSBinding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
_wSBinding.MaxBufferSize = Int32.MaxValue;
_wSBinding.MaxReceivedMessageSize = Int32.MaxValue;
//_wSBinding.UseDefaultWebProxy = false;
wsCustomerList.Customer_List_PortClient _ws = new wsCustomerList.Customer_List_PortClient(_wSBinding, new System.ServiceModel.EndpointAddress(_webserviceuripage));
_ws.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
_ws.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("xxx","xxxx", "companyName");
return _ws;
}
//-------------------------- Using Async Methods
public static async Task GetAsyncRecords(string _No)
{
wsCustomerList.Customer_List_PortClient _ws = GetService();
wsCustomerList.Customer_List _List = (await _ws.ReadAsync(_No)).Customer_List;
if (_ws.State == System.ServiceModel.CommunicationState.Opened)
await _ws.CloseAsync();
return _List;
}
public static async Task GetAsyncRecords(wsCustomerList.Customer_List_Filter[] _filters)
{
wsCustomerList.Customer_List_PortClient _ws = GetService();
wsCustomerList.Customer_List[] _List;
List _filterArray = new List();
_filterArray.AddRange(_filters);
_List = (await _ws.ReadMultipleAsync(_filterArray.ToArray(), null, 0)).ReadMultiple_Result1;
if (_ws.State == System.ServiceModel.CommunicationState.Opened)
await _ws.CloseAsync();
return _List;
}
public static async Task GetAsyncRecords(wsCustomerList.Customer_List_Filter[] _filters, string _bookmarkkey)
{
wsCustomerList.Customer_List_PortClient _ws = GetService();
wsCustomerList.Customer_List[] _List;
List _filterArray = new List();
_filterArray.AddRange(_filters);
_List = (await _ws.ReadMultipleAsync(_filterArray.ToArray(), _bookmarkkey, 0)).ReadMultiple_Result1;
if (_ws.State == System.ServiceModel.CommunicationState.Opened)
await _ws.CloseAsync();
return _List;
}
public static async Task GetAsyncRecords(wsCustomerList.Customer_List_Filter[] _filters, string _bookmarkkey, int _setsize)
{
wsCustomerList.Customer_List_PortClient _ws = GetService();
wsCustomerList.Customer_List[] _List;
List _filterArray = new List();
_filterArray.AddRange(_filters);
_List = (await _ws.ReadMultipleAsync(_filterArray.ToArray(), _bookmarkkey, _setsize)).ReadMultiple_Result1;
if (_ws.State == System.ServiceModel.CommunicationState.Opened)
await _ws.CloseAsync();
return _List;
}
}
}
#endregion
}
//--- end namespace
}
i know it is some time ago this question was posted, but others might stumble across it, so here goes:
a) What seems to be the problems in above code as I just wanted to retrieve a record.
it seems like your return type is incorrect.
b) Must use Async Methods in WinRT or Windows store app?
Yes, when using windows mobile platforms(windows store apps and windows phone apps), you have to use asynchronous calls.
c) Will below code able to retrieve record from Navision?
Hard to tell, but to me it seems like your data you try to retrieve is in a incorrect format. Ill give you a simple example from one of my current projects where I retrieve a login:
private async void Button_Click(object sender, RoutedEventArgs e)
{
await call();
}
private async Task call()
{
BasicHttpBinding binding = new BasicHttpBinding();
NetworkCredential cred = new NetworkCredential("username", "password", "domain");
WS_PortClient ws = new WS_PortClient(binding, new EndpointAddress("Webservice-URL"));
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
ws.ClientCredentials.Windows.ClientCredential = cred;
CheckLogin_Result s = await ws.CheckLoginAsync("parameter");
string k = s.return_value.ToString();
MessageDialog d = new MessageDialog(k, "message");
await d.ShowAsync();
}
Hope it helps!

Unit testing post controller .NET Web Api

I don't have much experience with .NET Web Api, but i've been working with it a while now, following John Papa's SPA application tutorial on Pluralsight. The application works fine, but the thing i'm struggling with now, is unit testing POST-controllers.
I have followed this incredible guide on how to unit test web api controllers. The only problem for me is when it comes to test the POST method.
My controller looks like this:
[ActionName("course")]
public HttpResponseMessage Post(Course course)
{
if (course == null)
throw new HttpResponseException(HttpStatusCode.NotAcceptable);
try
{
Uow.Courses.Add(course);
Uow.commit();
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var response = Request.CreateResponse(HttpStatusCode.Created, course);
string uri = Url.Link(routeName: "ControllerActionAndId",
routeValues: new { id = course.Id });
response.Headers.Location = new Uri(uri);
return response;
}
And my unit test looks like this:
[Test]
public void PostShouldReturnHttpResponse()
{
var populatedPostController = new CoursesController(new TestUOW());
SetupPostControllerForTest(populatedPostController);
var course = new Course
{
Id = 12,
Author = new UserProfile()
{
Firstname = "John",
Lastname = "Johnson",
},
Description = "Testcourse",
Title = "Test Title"
};
var responses = populatedPostController.Post(course);
ObjectContent content = responses.Content as ObjectContent;
Course result = (Course)content.Value;
Assert.AreSame(result, course);
}
With the help function:
public static void SetupPostControllerForTest(ApiController controller)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/courses/course");
var route = config.Routes.MapHttpRoute(
name: "ControllerActionAndId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null,
constraints: new { id = #"^\d+$" }
);
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "courses" }, { "action", "course" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
When i debug the unit test, it seems to fail at:
string uri = Url.Link(routeName: "ControllerActionAndId",
routeValues: new { id = course.Id });
response.Headers.Location = new Uri(uri); //Exception because uri = null
It seems like the Url.Link can't find the route.
I tried this guide aswell, but i really want the example i have above to work.
Am i missing something really basic here?
Yes, you are missing the one line in the configuration as Nemesv mentioned.
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData
As you can see, configuring a controller just for using the UrlHelper is extremely complex. I tend to avoid the use of UrlHelper in the controller classes for that reason. I usually introduce an external dependency to make testing easier like an IUrlHelper, which allows me to mock the behavior in an unit test.
public interface IUrlHelper
{
string Link(string routeName, object routeValues);
string Route(string routeName, object routeValues);
}
public class UrlHelperWrapper : IUrlHelper
{
UrlHelper helper;
public UrlHelperWrapper(UrlHelper helper)
{
this.helper = helper;
}
public string Link(string routeName, object routeValues)
{
return this.helper.Link(routeName, routeValues);
}
public string Route(string routeName, object routeValues)
{
return this.helper.Route(routeName, routeValues);
}
}
I inject this UrlHelperWraper in the real Web API, and a mock of the IUrlHelper interface in the tests. By doing that, you don't need all that complex configuration with the routes.
Regards,
Pablo.

Amazon web service. How to authenticate?

I am going to write a small program that query Amazon web service for book information.
Given some sample I found online, I wrote;
namespace TestWCF
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter keyword: ");
var line = Console.ReadLine();
if (line == null)
{
return;
}
using (var svc = new AmazonSearchPortClient())
{
var keywordReq = new KeywordRequest
{
locale = "us",
type = "lite",
sort = "reviewrank",
mode = "books",
keyword = line,
tag = "associate-id",
devtag = "????????????"
};
var productInfo = svc.KeywordSearchRequest(keywordReq);
foreach(var detail in productInfo.Details)
{
Console.WriteLine(detail.ProductName);
}
}
}
}
This does not work as it returns authenticate failure at the line;
var productInfo = svc.KeywordSearchRequest(keywordReq);
I am not sure what information I should put into the tag and devtag fields. Someone says I should put associate ID but what I shall put into the devtag?
Many thanks,
Regards.
}