Yahoo PlaceFinder API Connection Issues - asp.net-mvc-3

I'm trying to used Yahoo's PlaceFinder API to get longitude and latitude for a postcode. Everything works fine on my local machine but when I upload it to my production server I get a connection refused error from Yahoo. I've copied my code below:
Dictionary<string, decimal> GetYahooGeoCode(string postcode)
{
string url = "http://where.yahooapis.com/geocode?flags=J&appid=[My_App_ID]&location=";
decimal latitude = 0;
decimal longitude = 0;
try
{
dynamic yahooResults = new Uri(url + postcode).GetDynamicJsonObject();
foreach (var result in yahooResults.ResultSet.Results)
{
latitude = (decimal)result.latitude;
longitude = (decimal)result.longitude;
}
Dictionary<string, decimal> geoCode = new Dictionary<string, decimal>();
geoCode.Add("latitude", latitude);
geoCode.Add("longitude", longitude);
return geoCode;
}
catch (Exception ex)
{
Log4NetLogger logger = new Log4NetLogger();
logger.Error(ex);
return null;
}
}
The error I'm getting is: No connection could be made because the target machine actively refused it. Does anyone have any ideas on this? I have done a lot of searching and can't seem to find any information on this problem. I don't know if this makes any difference but my production server is a dedicated Cloud server. Any help would be appreciated.

I try to solve your problem here my solition:
Check your web.config:
<system.net>
<defaultProxy />
</system.net>
And my code (GetDynamicJsonObject() not parsed the response):
string postcode = "10003";
string url = String.Format("http://where.yahooapis.com/geocode?state={0}&postal={1}", "NY", postcode);
Dictionary<string, decimal> geoCode = new Dictionary<string, decimal>();
System.Xml.Linq.XDocument xDocument = XDocument.Load(url);
var latlon = (from r in xDocument.Descendants("Result")
select new { latitude = r.Element("latitude").Value, longitude = r.Element("longitude").Value }).FirstOrDefault();
if(null != latlon)
{
geoCode.Add("latitude", Convert.ToDecimal(latlon.latitude));
geoCode.Add("longitude", Convert.ToDecimal(latlon.longitude));
}
Check place finder yahoo api parameters here http://developer.yahoo.com/geo/placefinder/guide/requests.html#base-uri

Related

Cognitive face detection is not working when I try to upload the image with a face mask

Any suggestions on how to get info of the image with a mask in cognitive face recognition?
When I upload image with headwear or eyeglasses then cognitive service returns the image information but when picking an image with mask, Cognitive service doesn't return any information. That means my implementation of cognitive service is not able to recognize the image with the mask. If anybody has faced this issue and resolved it please suggest me a solution.
public string subscriptionKey = "88c**************************f7";
public string uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
//Method to pick an image from the gallery
async void btnPick_Clicked(object sender, System.EventArgs e)
{
try
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
return;
}
var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (file == null) return;
imgSelected.Source = ImageSource.FromStream(() => {
var stream = file.GetStream();
return stream;
});
MakeAnalysisRequest(file.Path);
}
catch (Exception ex)
{
string test = ex.Message;
}
}
> //convert Convert image to byte array
public byte[] GetImageAsByteArray(string imageFilePath)
{
using (FileStream fileStream =
new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
{
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
> //Method to get image information from the detection Url
public async void MakeAnalysisRequest(string imageFilePath)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
"&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
"emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
string uri = uriBase + "?" + requestParameters;
HttpResponseMessage response;
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
string contentString = await response.Content.ReadAsStringAsync();
//***************************************************
//Here it return null in case of mask else its working fine
//***************************************************
List<ResponseModel> faceDetails = JsonConvert.DeserializeObject<List<ResponseModel>>(contentString);
if (faceDetails.Count != 0)
{
lblTotalFace.Text = "Total Faces : " + faceDetails.Count;
lblGender.Text = "Gender : " + faceDetails[0].faceAttributes.gender;
lblAge.Text = "Total Age : " + faceDetails[0].faceAttributes.age;
Console.WriteLine(faceDetails[0].faceAttributes.accessories.FirstOrDefault(x => x.type == "mask").confidence);
}
}
}
There a 2 different things that you must have in mind:
Some faces might not be seen by the services, see doc:
Some faces might not be detected because of technical challenges.
Extreme face angles (head pose) or face occlusion (objects such as
sunglasses or hands that block part of the face) can affect detection.
Frontal and near-frontal faces give the best results.
There are currently 2 detection models in Face API: "detection_01" and "detection_02". This latest model (existing since May 2019 if I remember well) has better performances (especially for rotated or partially hidden faces) but is not providing all the information in output that model 1 is giving.
Difference in detection models
I made a quick demo using a the "Cognitive Workbench" demo portal (available here) with the following image:
With detection_01: no face found
With detection_02: the face is found, as you can see in this capture:
But if you need to use specific attributes from the face, this might not solve your problem. See API documentation extract:

Connecting to RETS Servers with UserAgent Requirement

I am hoping there is someone here who is familiar with a Real Estate data standard known as RETS. The National Association of Realtors provides a dll for interfacing with their services called libRETS, but it is not being supported like it once was and recent events have prompted us to create our own as a replacement. For logistics reasons, we can't do this in Core and are using the current C#.Net 4.7.2.
There are 2 or 3 different "security levels" for connecting to a RETS Server, with the method being a per case basis from one MLS to the next. We can successfully connect to those who only require a login and password, but are hitting a wall on those who also require what is called a UserAgent and UserAgentPassword, which must passed somehow using Md5 encryption. The server is returning:
The remote server returned an error: (401) Unauthorized.
private WebResponse GetLoginBasicResponse()//*** THIS ONE WORKS ***
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(new Uri(_cred.loginUri));
request.Method = "GET";
request.Headers.Add("RETS-Version", _retsVersion);
request.Credentials = new NetworkCredential(_login, _password);
return request.GetResponse();
}
catch (Exception ex)
{
string ignore = ex.Message;
return null;
}
}
private WebResponse GetLoginWithUserAgentResponse()//*** THIS ONE DOES NOT WORK ***
{
try
{
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(new Uri(_cred.loginUri));
request.Method = "GET";
request.Headers.Add("RETS-Version", _retsVersion);
if (!string.IsNullOrEmpty(_cred.userAgent))
{
request.UserAgent = Md5(_cred.userAgent + ":" + _cred.userAgentPassword);
//request.Headers.Add("RETS-UA-Authorization", "Digest " + Md5(_cred.userAgent + ":" + _cred.userAgentPassword));
}
request.Credentials = new NetworkCredential(_login, _password);
return request.GetResponse();
}
catch (Exception ex)
{
string ignore = ex.Message;
return null;
}
}
public string Md5(string input) //*** Borrowed this from from .NET Core Project and presume it works
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
Page 20 of this document describes how to build the UA header: https://www.ranww.org/documents/resources/rets_1_8.pdf
There’s a few other fields you need to include.
We were not able to solve the issue in .NET but found a .NET Core project in GitHub that we are using instead. https://github.com/CrestApps/RetsConnector
This case can be closed
Not seeing an option to "Mark as Answer". Have tried both MS Edge and Google Chrome

CRM SDK 2013 Activity doesn't exist just after creating it

I have a custom comment activity which I'm updating in code and this used to work but has started failing recently. It creates the activity but when I try to retrieve it or execute SetStateResponse on it, I get "tk_comment With Id = 9a1686d1-7d9d-e611-80e3-00155d001104 Does Not Exist" - which doesn't make sense as I've just created it! The activity record shows up against the account but I can't click on it there or do anything (Record is unavailable - The requested record was not found or you do not have sufficient permissions to view it.).
This is the code I'm using. I'd love you to tell me I've made some simple mistake :)
using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
{
_serviceProxy.EnableProxyTypes();
try
{
tk_comment comment = new tk_comment();
int maxLength = 190; //subject has a max length of 200 characters
if (subject.Length > maxLength)
{
comment.Subject = subject.Substring(0, maxLength);
comment.Description = subject.Substring(maxLength, subject.Length - maxLength);
}
else
{
comment.Subject = subject;
}
comment.RegardingObjectId = entity.ToEntityReference();
comment.ActualStart = CommentDate;
comment.ActualEnd = CommentDate;
comment.ScheduledStart = CommentDate;
comment.ScheduledEnd = CommentDate;
Guid commentID = _serviceProxy.Create(comment);
try
{
tk_comment aComment = (tk_comment)_serviceProxy.Retrieve(tk_comment.EntityLogicalName, commentID, new ColumnSet(allColumns: true));
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("Always an error here " + ex.Message);
}
Account test = (Account) _serviceProxy.Retrieve(Account.EntityLogicalName, entity.Id, new ColumnSet(allColumns: true));
// tk_comment newComment = (tk_comment)_serviceProxy.Retrieve(tk_comment.EntityLogicalName, commentID, new ColumnSet(allColumns: true));
SetStateRequest request = new SetStateRequest();
request.EntityMoniker = new EntityReference(tk_comment.EntityLogicalName, commentID);
request.State = new OptionSetValue((int) tk_commentState.Completed); //completed
request.Status = new OptionSetValue(2); //completed
SetStateResponse response = (SetStateResponse)_serviceProxy.Execute(request); //always an error here too
}
Appreciate any suggestions
Cheers, Mick
It seems like you don't have proper read permission of this custom activity entity.
OR You need to validate all the permissions of this custom entity.

Windows Azure Storage - Table not found

I'm trying to implement windows azure table storage...but I'm getting 'Table Not Found'
Here is my connection string(How post I xml here?)(sorry for links)
ServiceConfiguration.Cloud.cscfg:
http://pastebin.com/F9tuckfT
ServiceConfiguration.Local.cscfg:
http://pastebin.com/XZHEvv6g
and here there's a print screen from my windows azure portal
http://s20.postimage.org/nz1sxq7hp/print.png
The code(sorry for the longer code...but there's three pages...Login works, when I log in, go to main.aspx that call grid.aspx ...In grid.aspx I get the error "Table not found" All this code is important for the question.....) http://pastebin.com/RnuvvqsM
I have tried
private void popula()
{
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
account.CreateCloudTableClient().CreateTableIfNotExist("fiscal");
var context = new CRUDManifestacoesEntities(account.TableEndpoint.ToString(), account.Credentials);
Hashtable ht = (Hashtable)ViewState["filtro"];
if (ht == null)
GridView1.DataSource = context.SelectConc(ViewState["x"].ToString());
else
GridView1.DataSource = context.SelectConc(ht);
GridView1.DataBind();
}
but it doesn't work too
Other error similar is when I try to add a USER in table
public string addusr(string nome, string cidade, string cpf, string email, string telefone)
{
try
{
if (nome.Length == 0)
return "f:Preencha o campo nome.";
if (cidade.Length == 0)
return "f:Preencha o campo cidade.";
if (cpf.Length == 0)
return "f:Preencha o campo cpf.";
if (!Valida(cpf))
return "f:CPF Invalido.";
if (email.Length == 0)
return "f:Preencha o campo email.";
Regex rg = new Regex(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
if (!rg.IsMatch(email))
{
return "f:Email Invalido";
}
List<UserEntity> lst = new List<UserEntity>();
var _account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
_account.CreateCloudTableClient().CreateTableIfNotExist("fiscal");
var _context = new CRUDUserEntities(_account.TableEndpoint.ToString(), _account.Credentials);
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
account.CreateCloudTableClient().CreateTableIfNotExist("fiscal");
var context = new CRUDUserEntities(account.TableEndpoint.ToString(), account.Credentials);
UserClientEntity entity = new UserClientEntity() { nome = nome, cidade = cidade, cpf = cpf, email = email, telefone = telefone };
context.ADDUSociate(entity);
context.SaveChanges();
return "k";
}
I'm getting this error:
f:An error occurred while processing this request.| at System.Data.Services.Client.DataServiceContext.SaveResult.HandleBatchResponse()
at System.Data.Services.Client.DataServiceContext.SaveResult.EndRequest()
at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
at AzureTableLayer.CRUDUserEntities.ADDUSociate(UserClientEntity entity)
at mobile.Service1.addusr(String nome, String cidade, String cpf, String email, String telefone)
I believe that the two problems are related
EDIT: I have debugged and discovered that the StorageClient framework could not be loaded...
I'm getting this error Could not load file or assembly Microsoft.WindowsAzure.StorageClient, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
How to solve?
How are you trying to work with Table Storage? Trought the .NET SDK? PHP? Java? Node? ... Typically if you get this error it means that... the table does not exist.
Check the SDK you're using for a method similar to CreateIfNotExists in order to create the table before you start using it.
Edit:
The issue probably happens here:
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var context = new CRUDManifestacoesEntities(account.TableEndpoint.ToString(), account.Credentials);
Hashtable ht = (Hashtable)ViewState["filtro"];
if (ht == null)
GridView1.DataSource = context.SelectConc(ViewState["x"].ToString());
else
GridView1.DataSource = context.SelectConc(ht);
Add the following code after the var account = ... line:
account.CreateCloudTableClient().CreateTableIfNotExist("<name of your table>");
The API has been changed. you need to do it like this:
var key = CloudConfigurationManager.GetSetting("Setting1");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(key);
var client = storageAccount.CreateCloudTableClient();
CloudTable table = client.GetTableReference(ContactTableName);
table.CreateIfNotExists();

How to upload images on Facebook wall by using MVC3, C#?

I'm trying to upload photos into Facebook by using MVC3 C#. The code is running successfully but the photos are not uploaded into Facebook. I'm having add ID and App Secret. I tried many ways and for many days I worked hard, but the result is zero. Here is the code of my controller
[HttpPost][HttpGet]
public ActionResult Profile(HttpPostedFileBase file, FacebookOAuthResult facebookOAuthResult) {
dynamic args = new ExpandoObject();
args = new Dictionary<string, object>();
args["message"] = "hi";
args["picture"] = "http://apps.facebook.com/Uploads/photos";
string accesstoken=FacebookWebContext.Current.AccessToken;
FacebookClient fbApp = new FacebookClient(accesstoken);
try {
fbApp.Post("MYAPPID" + "/Photos", args);
} catch (FacebookOAuthException ex) {
//
}
// Verify that the user selected a file
if (file != null && file.ContentLength > 0) {
var path1 = Path.Combine(Server.MapPath("~/Content/uppoads"), file.FileName);
//file.SaveAs(path1);
fbApp.Post("MYAPPID" + "/photos", path1);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Profile");
}
Could anyone help me to find the solution? Thanks in advance.
You are Post the local path of the photo to Facebook, FB doesn't know what it is.
You should post the photo as binary in the Post body.
var media = new Facebook.FacebookMediaObject();
var filebytes = System.IO.File.ReadAllBytes(path1);
media.SetValue(filebytes);
fbApp.Post("248050331932489" + "/photos", media);

Resources