exchange Ethereum into a ERC20 stable Coin (usdt or Dai)? - c#

I'm making a decentralized wallet built on the Ethereum network, and I'm currently trying to convert 1 Ethereum to get the equivalent of the StableCoin for a smart contract [in this case, DAI]
I was able to find out how to know my balance of this currency, and I think that I can also transfer money from one account to another in its Coin smart contract
The problem is that when I transfer the value of [assuming 100 DAI], it tells me that I do not have any balance value from this token (this is very logical) because I did not transfer Ethereum against this currency!!
Error Message : [Smart contract error: Dai/insufficient-balance]
Here is the question:
What is the name of the Function which I can convert my Ethereum to the currency that I deal with its smart contract??
Or is it not going this way??
//Dai Stablecoin Address on Ropsten Network =>
string SmartContractAddress = "0x31F42841c2db5173425b5223809CF3A38FEde360";
var account = new Account(PrivateKey);
web3 = new Web3(account, ropsten);
web3.TransactionManager.UseLegacyAsDefault = true;
// Get Balance Of an address
var balanceOfFunctionMessage = new BalanceOfFunction()
{
Owner = account.Address,
};
var balanceHandler = web3.Eth.GetContractQueryHandler<BalanceOfFunction>();
var balance = await balanceHandler.QueryAsync<BigInteger>(SmartContractAddress, balanceOfFunctionMessage);
// Try To transfer some DAI to receiver Address
var receiverAddress = "0xC10cAA4668427F05d0D95B9409f87D0662A25f97";
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
var transfer = new TransferFunction()
{
To = receiverAddress,
TokenAmount = 100
};
var transactionReceipt = await transferHandler.SendRequestAndWaitForReceiptAsync(SmartContractAddress, transfer);
According to my simple understanding: I think I need to know the name of the function by which I can exchange assets from Ethereum to the currency of this contract

Related

C# :OnvifClientPTZ

I am trying to develop a control IP camera with ONVIF.But I have a little problem of connect PTZ server of ONVIF.
Here is my code:
private void PTZTest(DeviceClient client, double deviceTimeOffset, string ip, int port)
{
// Create Media object
string xaddr = string.Format("http://{0}/onvif/device_service", txtIP.Text);
MediaClient mediaService = OnvifServices.GetOnvifMediaClient(xaddr, deviceTimeOffset, txtUser.Text, txtPassword.Text);
// Create PTZ object
string xaddr2 = string.Format("http://{0}/onvif/ptz_service",txtIP.Text);
PTZClient ptzService = OnvifServices.GetOnvifPTZClient(xaddr2, deviceTimeOffset, txtUser.Text, txtPassword.Text);
// Get target profile
Profile[] mediaProfiles = mediaService.GetProfiles();
Profile mediaProfile = mediaService.GetProfile(mediaProfiles[0].token);
PTZConfigurationOptions ptzConfigurationOptions = ptzService.GetConfigurationOptions(mediaProfile.PTZConfiguration.token);
PTZ.PTZSpeed velocity = new PTZ.PTZSpeed();
velocity.Zoom = new PTZ.Vector1D() { x = speed * ptzConfigurationOptions.Spaces.ContinuousZoomVelocitySpace[0].XRange.Max };
When I set a breakpoint at the line
PTZConfigurationOptions ptzConfigurationOptions = ptzService.GetConfigurationOptions(mediaProfile.PTZConfiguration.token); I got this error message:
There was no listening endpoint on
http://192.168.123.2/onvif/ptz_service that could accept the message.
This is often due to an incorrect SOAP address or action. If present,
see the InnerException element for more information.
But I dont understand why I can have the list of the PTZ services and all the informations about the mediaService, but I couldn't get the ptzconfiguration option.
Does anyone know what's the problem exactly ? And how can I resolve it, please!
Not every onvif device will host its PTZ service on the same endpoint. Generally the approach to use is to query the GetServices/GetCapabilities calls from the DeviceService. This is the only service that usually always has the same URL - "http://ip/onvif/device_service"
Approach to use is therefore(in pseudocode)
var devService = OnvifServices.GetOnvifDeviceService("http://ip/onvif/device_service)
var services = devService.GetServices() or devService.GetCapabilities()
var ptzServiceInfo = services.Where(x => x.Name.Contains("Ptz));
var ptzServiceInfo = OnvifServices.GetPtzService(ptzServiceInfo.Url);
you do not use the device_server to do any ptz_service calls, you simply use it to do a lookup for the correct URL of the device service If you do the GetService call the response will include something like
<tds:Service> <tds:Namespace>onvif.org/ver20/ptz/wsdl</tds:Namespace> <tds:XAddr>ip/onvif/ptz</tds:XAddr> </tds:Service>
See onvif.org/specs/core/ONVIF-Core-Specification-v250.pdf for more details

ReverseGeocodeQuery results in a language different to system language

I'm using ReverseGeocodeQuery class to get location names from coordinates:
ReverseGeocodeQuery query = new ReverseGeocodeQuery();
query.GeoCoordinate = new GeoCoordinate(latitude, longitude);
query.QueryCompleted += (sender, args) =>
{
var result = args.Result[0].Information.Address;
Location location = new Location(result.Street, result.City, result.State, result.Country);
};
query.QueryAsync();
The problem is that results are returned in the system language of the phone. Since I am using place names for tagging purposes, I need all of them in same language, preferably in english.
I have tried by setting the CurrentCulture to en-US:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
But I'm still getting the results in the language configured as system language.
Is ther any way to get the results from ReverseGeocodeQuery in desired language?
The results are always using the system language. Maybe you can save the name of the place and also the lat long, or use a translation service to translate to englis
Just to complete Josue's answer. An alternative to get reverse geocode results in desided language is to use one of the public REST APIs that allow to specify it (e.g. Google or Nokia Here). While the use of them is simple and are very customizable, the downside is that it is necessary to register to the services in order to get the keys.
I have decided for using HERE's API. So, below you will find the code I have used to achieve the same result as using the code present in the question, but forcing the result to be in English:
using (HttpClient client = new HttpClient())
{
string url = String.Format("http://reverse.geocoder.cit.api.here.com/6.2/reversegeocode.json"
+ "?app_id={0}"
+ "&app_code={1}"
+ "&gen=1&prox={2},{3},100"
+ "&mode=retrieveAddresses"
+ "&language=en-US",
App.NOKIA_HERE_APP_ID, App.NOKIA_HERE_APP_CODE, latitude.ToString(CultureInfo.InvariantCulture), longitude.ToString(CultureInfo.InvariantCulture));
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
dynamic loc = JObject.Parse(json);
dynamic address = JObject.Parse(loc.Response.View[0].Result[0].Location.Address.ToString());
string street = address.Street;
string city = address.City;
string state = address.State;
string country = address.Country;
Location location = new Location(street, city, state, country);
}

Bing Maps GeoCodeService and Addresses

I have some problems with my bing maps.
The first one happens when I click on My Location - from almost all locations I were it worked fine, but there are some locations that returns null, why? (It happened me in a new building that hasn't address yet and also happened in a building with no internet connections).
The method:
private async void MyLocation_Click(object sender, RoutedEventArgs e)
{
Bing.Maps.Location location = await GeoLocation.GetCurrentLocationAsync();
MapLayer.SetPosition(_flagPin, location);
map.SetView(location, 15);
}
The first line calls to my static function:
public static async Task<Bing.Maps.Location> GetCurrentLocationAsync()
{
Geolocator geo = new Geolocator();
geo.DesiredAccuracy = PositionAccuracy.Default;
Geoposition currentPosition = null;
currentPosition = await geo.GetGeopositionAsync();
return new Bing.Maps.Location()
{
Latitude = currentPosition.Coordinate.Latitude,
Longitude = currentPosition.Coordinate.Longitude
};
}
What is the problem? How to fix it?
And the second question is about addresses.
When I get an Address object, there are many formats I can select such as FormattedAddress, CountryRegion, PostalTown, I selected The FormattedAddress and there is a problem with it.
My code:
GeocodeResponse GP = await GeoLocation.ReverseGeocodeAsync(location.Latitude, location.Longitude);
EventContext.Address = GP.Results[0].Address.FormattedAddress;
The problem is when I want to send an Address and get the Location.
Sometimes this code returns null, why?
GeocodeResponse GP = await GeoLocation.GeocodeAsync(EventContext.Address);
I thought that maybe the problem is that sometimes the Address (Formatted) is not good, sometimes it gives weird addresses, such as, "Street, st. Canada", which is not found and therefore, it returns null. But what can I do to send a correctly Address? Does FomattedAddress is good?
Here are the two GeoCodeAsync and ReverseGeocodeAsync functions:
public static async Task<GeocodeResponse> GeocodeAsync(string address)
{
GeocodeService.GeocodeRequest geocodeRequest = new GeocodeService.GeocodeRequest();
// Set credentials using a Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = Application.Current.Resources["BingCredentials"] as string;
// Set the address
geocodeRequest.Query = address;
// Make the geocode request
GeocodeService.GeocodeServiceClient geocodeService = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
GeocodeResponse geocodeResponse = await geocodeService.GeocodeAsync(geocodeRequest);
return geocodeResponse;
}
public static async Task<GeocodeResponse> ReverseGeocodeAsync(double latitude, double longitude)
{
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set credentials using a Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = Application.Current.Resources["BingCredentials"] as string;
// Set the coordinates
reverseGeocodeRequest.Location = new GeocodeService.GeocodeLocation() { Latitude = latitude, Longitude = longitude };
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
GeocodeResponse geocodeResponse = await geocodeService.ReverseGeocodeAsync(reverseGeocodeRequest);
return geocodeResponse;
}
To clarify your first issue, are you getting null from the GPS or is it the address information in the result that is null the issue? If the GPS is returning null then it's possible that your GPS isn't able to get the current position where you are. This has nothing to do with Bing Maps and more so just an issue which your mobile device getting a clear view to the GPS satellites. If the issue is that the address information in the result is null then this is to be expected with new buildings that might not yet be known in the Bing Maps data set. It usually takes several months for new buildings to be found and added to the map data set. If you have no internet connection then the mobile device won't be able to connect to Bing Maps to get the address information. Note that Bing Maps is over 9 Petabytes in size so there is no local copy of the data on your mobile device.
If you already have the coordinates and the address information you shouldn't be geocoding it again. This is a waste of time and will cause issues. The geocoder will sometimes return "street" or "ramp" if the coordinate in which you pass to the reverse geocoder is on an unnamed street. Note geocoders are not designed to clean/validate addresses. They are designed to take an address and return a coordinate. Reverse geocoders are designed to take a coordinate and find the nearest address. Mixing the results from one with the other can result in odd results as the coordinates for each could be significantly different. It rare cases it's possible to loop between both services and get different results each time as the results will slightly be different and end up "walking" along a street.

Find products by specifications with Amazon Product Advertising API

I am trying to find smartphones with the amazon product advertising api.
http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl
On the amazon website you can set various filters like "storage" "features keywords".
http://www.amazon.com/s/ref=sr_nr_n_1?rh=n%3A2335752011%2Cn%3A!2335753011%2Cn%3A2407749011&bbn=2335753011&ie=UTF8&qid=1361393129&rnid=2335753011
For example I want to find smartphones from Samsung with Android OS that are cheaper than 250 USD with at least 32 GB storage.
ItemSearchRequest request = new ItemSearchRequest();
request.SearchIndex = "Electronics";
//this browsenode is for amazon.de (cell phones)
request.BrowseNode = "1384526031";
request.MaximumPrice = "250";
// ? request.Storage = 32
// ? request.OperatingSystem = "Android"
request.ResponseGroup = new string[] { "Large" };
ItemSearch itemSearch = new ItemSearch();
itemSearch.AssociateTag = "xxx";
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["accessKeyId"];
ItemSearchResponse response = amazonClient.ItemSearch(itemSearch);
foreach (var item in response.Items[0].Item)
{
Console.WriteLine(item.ItemAttributes.Title);
}
My problem is that the ItemSearchRequst class doesn't have properties like "storage" or "features" or "operating system".
I have been finding this information for more than a week but there is indeed no documentation for this feature. I believe Amazon wants to keep this, together with product technical detail and product reviews for itself. However you can filter some of these keywords (such as operating system), but not all, from itemsearch with responsegroup('Large')

How can I get the LastRunTime for a report using the Business Objects Web Services SDK?

I'm using the Business Objects Web Services SDK to access our Business Objects data. I've successfully got a list of reports, and from that found the LastSuccessfulInstance of a report that has been previously run. However, I can't seem to get the LastRunTime to be populated. When I do a query with no attributes specified it comes back as not set, and I get the same result when I ask for that attribute in particular. I've looked at the report itself and the instance and they both don't have this information. Does anyone know where I can get it from?
Here's my code (hacked from one of SAP's demos):
var sessConnUrl = serviceUrl + "/session";
var boConnection = new BusinessObjects.DSWS.Connection(sessConnUrl);
var boSession = new Session(boConnection);
// Setup the Enterprise Credentials used to login to the Enterprise System
var boEnterpriseCredential = new EnterpriseCredential
{
Domain = cmsname,
Login = username,
Password = password,
AuthType = authType
};
// Login to the Enterprise System and retrieve the SessionInfo
boSession.Login(boEnterpriseCredential);
/************************** DISPLAY INBOX OBJECTS *************************/
// Retrieve the BIPlatform Service so it can be used to add the USER
var biPlatformUrl = boSession.GetAssociatedServicesURL("BIPlatform");
var boBiPlatform = BIPlatform.GetInstance(boSession, biPlatformUrl[0]);
// Specify the query used to retrieve the inbox objects
// NOTE: Adding a "/" at the end of the query indicates that we want to
// retrieve the all the objects located directly under the inbox.
// Without the "/" Path operator, the inbox itself would be returned.
const string query = "path://InfoObjects/Root Folder/Reports/";
// Execute the query and retrieve the reports objects
var boResponseHolder = boBiPlatform.Get(query, null);
var boInfoObjects = boResponseHolder.InfoObjects.InfoObject;
// If the reports contains a list of objects, loop through and display them
if (boInfoObjects != null)
{
// Go through and display the list of documents
foreach (var boInfoObject in boInfoObjects)
{
var report = boInfoObject as Webi;
if (report == null)
continue;
if (!string.IsNullOrEmpty(report.LastSuccessfulInstanceCUID))
{
var instanceQuery = "cuid://<" + report.LastSuccessfulInstanceCUID + ">";
var instanceResponseHolder = boBiPlatform.Get(instanceQuery, null);
var instance = instanceResponseHolder.InfoObjects.InfoObject[0];
}
}
}
Both report.LastRunTimeSpecified and instance.LastRunTimeSpecified are false and both LastRunTime are 01\01\0001, but I can see a last run time in the Web Intelligence UI.
With a little help from Ted Ueda at SAP support I figured it out. Not all the properties are populated by default you need to append #* to the query string to get everything, i.e. change the line:
const string query = "path://InfoObjects/Root Folder/Reports/";
to:
const string query = "path://InfoObjects/Root Folder/Reports/#*";

Categories

Resources