I am trying to find a stable and up to date example of a Google Analytics Reporting handler in .NET. Any information on the matter will be greatly appreciated. I have searched, and found nothing that really is for current use in .NET. I have also noticed, that the friendly friend Google did not create a library for it, but did under Java. At least from what I was able to see. Does anyone have a reference I could view, or a link with some good examples of setting up a reporting tool with this API?
Thanks in advance. :)
Here is my basic working example I finally got. Hopefully this helps, enjoy!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Gongos.AnalyticsAPI
{
public partial class _Default : Page
{
public string VisitsNumber()
{
string visits = string.Empty;
string username = "******** --> Your email";
string pass = "********** --> Your password";
string gkey = "?key= **** --> Your APY key <-- ****";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:********";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = new DateTime(2013, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
}
}
Related
I have been trying to use Cognito Sign In for my application at ASP.NET C# and I have managed to make the user sign up. However, when I am trying to implement the codes for Sign In there are 2 errors at these lines below :
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
this line result in "CognitoUser does not contain a constructor that contain 4 arguments error"
and the 2nd error at this part :
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
this line result in "CognitoUser does not contain definition for StartWithSrpAuthAsync and No Extension Method…accepting a first argument of type ” could be found" error
This is my full code :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using System.Threading.Tasks;
using System.Configuration;
using Amazon.Extensions.CognitoAuthentication;
namespace WebApplication2
{
public partial class WebForm5 : System.Web.UI.Page
{
const string PoolID = "poolid";
const string ClientID = "clientid";
static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USEast1;
protected void Page_Load(object sender, EventArgs e)
{
string username = "user1";
string password = "pass";
string email = "email1";
SignInUser(username,password);
}
static async Task SignInUser(string username, string password)
{
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
CognitoUserPool userPool = new CognitoUserPool(PoolID, ClientID, provider);
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = password
};
AuthFlowResponse authResponse = null;
try
{
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
}
catch(Exception ex)
{
Console.WriteLine("Logon Failed: {0}\n", ex.Message);
return;
}
GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;
}
}
Any help will be appreciated.
Thank You
I have a program which connects to a site and gets the list of orders using soap api. But i have a really strange issue. When a i try to get the orders of a day which there is no orders and then try get list of orders of a day i get this error. But strange thing is if a put a break point to line where i got the error and evalute the program step by step i don't get any errors. How could that happen. herre is the code.
https://api.n11.com/ws/OrderService.wsdl
using n11.Deneme.Forms.com.n11.api;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace n11.Deneme.Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strStartDate = "18/01/2020";
string strEndDate = "18/01/2020";
long totalCountValue = 50;
int currentPageValue = 0;
int pageCountValue = 1;
int pageSizeValue = 50;
Authentication auth = new Authentication();
auth.appKey = "b891a6b9-cb97-4a7e-9ffb-f7b1e2a593e8";
auth.appSecret = "pHCjYYadxwTG64Ej";
OrderSearchPeriod orderSearchPeriod = new OrderSearchPeriod();
orderSearchPeriod.startDate = strStartDate;
orderSearchPeriod.endDate = strEndDate;
OrderDataListRequest orderDataListRequest = new OrderDataListRequest();
//orderDataListRequest.status = "1";
orderDataListRequest.period = orderSearchPeriod;
//orderDataListRequest.orderNumber = "209524598478";
PagingData pagingData = new PagingData();
pagingData.currentPage = currentPageValue;
pagingData.pageCount = pageCountValue;
pagingData.pageSize = pageSizeValue;
pagingData.totalCount = totalCountValue;
DetailedOrderListRequest request = new DetailedOrderListRequest();
request.auth = auth;
request.pagingData = pagingData;
request.searchData = orderDataListRequest;
OrderServicePortService port = new OrderServicePortService();
DetailedOrderListResponse response = port.DetailedOrderList(request);
List<DetailedOrderData> orderList = response.orderList.ToList();
foreach (var order in orderList)
{
MessageBox.Show(order.totalAmount.ToString() + " - " + order.orderNumber + " - " + order.citizenshipId + " - " + order.createDate);
long orderIdValue = order.id;
OrderDataRequest orderDataRequest = new OrderDataRequest();
orderDataRequest.id = orderIdValue;
OrderDetailRequest orderdetailrequest = new OrderDetailRequest();
orderdetailrequest.auth = auth;
orderdetailrequest.orderRequest = orderDataRequest;
OrderServicePortService port1 = new OrderServicePortService();
OrderDetailResponse orderDetailResponse = port1.OrderDetail(orderdetailrequest);
OrderDetailData orderDetail = orderDetailResponse.orderDetail;
MessageBox.Show(orderDetail.orderNumber);
List<OrderSearchData> orderItemList = orderDetail.itemList.ToList();
foreach (var item in orderItemList)
{
MessageBox.Show(item.shipmentInfo.campaignNumber);
}
}
}
}
}
If you're getting the error on the line:
List<DetailedOrderData> orderList = response.orderList.ToList(); //I GOT THE ERROR ON THIS LINE
then the thing to do is to look at how response.orderList gets a value. In particular, does it do something with threads, tasks, timers, external events, or anything else like that - which could mean that it gets populated shortly after the initial return from DetailedOrderList, which could explain why it works when you debug and step through (adding a crucial delay into things).
You could also simply do:
var tmp = response.orderList;
if (tmp == null) throw new InvalidOperationException(
"hey, response.orderList was null! this is not good!");
List<DetailedOrderData> orderList = tmp.ToList();
return orderList;
which would make it very clear and explicit that this is what is happening. If you don't get this exception, but something else, then: more debugging needed!
if(response.orderList == null)
{
var temp = button1_Click.PerformClick();
return temp;
}
else
{
List<DetailedOrderData> orderList = response.orderList.ToList();
return orderList;
}
I am trying for my school to use the Bing Map API and use GeocodeAdress. I build this application: http://msdn.microsoft.com/en-us/library/dd221354.aspx and the problem is I get this error every time.
it is at line 62: this method: GeocodeServiceClient geocodeService = new GeocodeServiceClient();
!InvalidOperationException was unhandled
An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.dll
Additional information: An endpoint configuration section for contract 'GeocodeService.IGeocodeService' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BingMapsSample.GeocodeService;
using BingMapsSample.SearchService;
using BingMapsSample.ImageryService;
using BingMapsSample.RouteService;
namespace BingMapsSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private String GeocodeAddress(string address)
{
string results = "";
string key = "Validate Bing Map Education Code";
GeocodeRequest geocodeRequest = new GeocodeRequest();
// Set the credentials using a valid Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = key;
// Set the full address query
geocodeRequest.Query = address;
// Set the options to only return high confidence results
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter();
filters[0].MinimumConfidence = GeocodeService.Confidence.High;
// Add the filters to the options
GeocodeOptions geocodeOptions = new GeocodeOptions();
geocodeOptions.Filters = filters;
geocodeRequest.Options = geocodeOptions;
// Make the geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = String.Format("Latitude: {0}\nLongitude: {1}",
geocodeResponse.Results[0].Locations[0].Latitude,
geocodeResponse.Results[0].Locations[0].Longitude);
else
results = "No Results Found";
return results;
}
private string ReverseGeocodePoint(string locationString)
{
string results = "";
string key = "Validate Bing Map Education Code";
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = key;
// Set the point to use to find a matching address
GeocodeService.Location point = new GeocodeService.Location();
string[] digits = locationString.Split(',');
point.Latitude = double.Parse(digits[0].Trim());
point.Longitude = double.Parse(digits[1].Trim());
reverseGeocodeRequest.Location = point;
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = geocodeResponse.Results[0].DisplayName;
else
results = "No Results found";
return results;
}
private string SearchKeywordLocation(string keywordLocation)
{
String results = "";
String key = "Validate Bing Map Education Code";
SearchRequest searchRequest = new SearchRequest();
// Set the credentials using a valid Bing Maps key
searchRequest.Credentials = new SearchService.Credentials();
searchRequest.Credentials.ApplicationId = key;
//Create the search query
StructuredSearchQuery ssQuery = new StructuredSearchQuery();
string[] parts = keywordLocation.Split(';');
ssQuery.Keyword = parts[0];
ssQuery.Location = parts[1];
searchRequest.StructuredQuery = ssQuery;
//Define options on the search
searchRequest.SearchOptions = new SearchOptions();
searchRequest.SearchOptions.Filters =
new FilterExpression()
{
PropertyId = 3,
CompareOperator = CompareOperator.GreaterThanOrEquals,
FilterValue = 8.16
};
//Make the search request
SearchServiceClient searchService = new SearchServiceClient();
SearchResponse searchResponse = searchService.Search(searchRequest);
//Parse and format results
if (searchResponse.ResultSets[0].Results.Length > 0)
{
StringBuilder resultList = new StringBuilder("");
for (int i = 0; i < searchResponse.ResultSets[0].Results.Length; i++)
{
resultList.Append(String.Format("{0}. {1}\n", i + 1,
searchResponse.ResultSets[0].Results[i].Name));
}
results = resultList.ToString();
}
else
results = "No results found";
return results;
}
private void Geocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = GeocodeAddress(textInput.Text);
}
private void ReverseGeocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = ReverseGeocodePoint(textInput.Text);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = SearchKeywordLocation(textInput.Text);
}
}
}
I found the solution line 62 should be:
var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
Open your web.config file or app.config file. In there you will see a basic and custom binding configuration for the service. Remove the custom binding section. Clean and build your project and it should work.
As a side note. The Bing Maps SOAP services are really old and limited in functionality. They were released about 8 years ago. A newer REST based service was released about 4 years ago. REST is faster, has smaller response packages and has more features. You can find out more about the Bing Maps REST services here: http://msdn.microsoft.com/en-us/library/ff701713.aspx
I have a requirement to integerate Quickbook api with my web application. I just created a sample application to accomplish it. I am strange to this I really dont have any idea about how to connect the api or to consume the api.I have mentioned the codes that i have took from ("https://developer.intuit.com/").
I tried by creating an app in the app manager, I have atttached the image FYR. After entering all those details i am not getting "accessTokenSecret" value. Here i just entered the apptoken valuea as accessToken value. Iam getting exception as "Unauthorized" in the service context line. Help me on this.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Intuit.Ipp.Core;
using Intuit.Ipp.Services;
using Intuit.Ipp.Data;
using Intuit.Ipp.Utility;
using Intuit.Ipp.Security;
using Intuit.Ipp.Data.Qbo;
using Newtonsoft.Json;
namespace QuickBookApiConsumption
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToke = "";
string appToken = "297db54bb5526b494dba97fb2a41063192cd";
string accessTokenSecret = "297db54bb5526b494dba97fb2a41063192cd";
string consumerKey = "qyprdMSG1YHpCPSlWQZTiKVc78dywR";
string consumerSecret = "JPfXE17YnCPGU9m9vuXkF2M765bDb7blhcLB7HeF";
string companyID = "812947125";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(appToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
Invoice os = new Invoice();
Intuit.Ipp.Data.Qbo.InvoiceHeader o = new Intuit.Ipp.Data.Qbo.InvoiceHeader();
o.CustomerName = "Viki";
o.CustomerId = new Intuit.Ipp.Data.Qbo.IdType { Value = "12" };
o.ShipMethodName = "Email";
o.SubTotalAmt = 3.00m;
o.TotalAmt = 6.00m;
o.ShipAddr = new Intuit.Ipp.Data.Qbo.PhysicalAddress { City = "Chni" };
}
}
}
Image:
You should check if you are using correct BASE URL
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/0100_calling_data_services/0010_getting_the_base_url
Using some RESTClient[ ex - RestClient plugin of mozilla browser], verify the OAuth tokens.
Header(content-type) config window.
You can use the following
public void ConnectUsingAuth()
{
string accessToken = ConfigurationManager.AppSettings["AccessTokenQBD"];
string accessTokenSecret = ConfigurationManager.AppSettings["access-secret"];
string consumerKey = ConfigurationManager.AppSettings["consumerKey"];
string consumerKeySecret = ConfigurationManager.AppSettings["consumerSecret"];
string URI = "https://apiend-point";
WebRequest webRequest = WebRequest.Create(URI);
webRequest.Headers.Add("ContentType", "text/xml");
OAuthRequestValidator target = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
}
Or [ Better option ] You can download the sample program from github and configure the web.config(with proper consumer key and secret)
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/sample_code
You can test all these API endpoints using APIExplorer tool.
Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0007_firstrequest
ApiExplorer - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Thanks
I got a new question, what firewall settings is needed for blocking an IP address ? I found the property "RemoteAddress", like firewallRule.RemoteAddress, but I dont know how to use it. This is what I found on stackoverflow ( following code blocks all access to internet ), Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETCONLib;
using NATUPNPLib;
using NetFwTypeLib;
namespace WindowsFormsApplication1
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
}
}
}
You can use list of ip addresses (subnets, aliases) splitted by commas
$Rule.RemoteAddresses = RemoteAddresses = 'LocalSubnet,10.1.1.1/255.255.255.255,12.5.0.0/255.255.0.0'
As far as I can tell, you have to retrieve the RemoteAddresses list first before adding to it. Otherwise, it just overwrites each IP with the next one. The format needs to be as Jan described in his/her answer. However, the subnet "/255.255.255.255" is not needed when adding a single IP address. My app only blocks a single ip at a time, but you can put ranges in there as Jan describes. Most the credit goes to others on SO with exception of the RemoteAddresses part. If there's a better/cleaner way, I would love to hear it. Here's how I ended up doing it:
private void BlockIp(string ip, string ruleName)
{
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == ruleName).FirstOrDefault();
if (firewallRule == null)
{
firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Name = ruleName;
firewallPolicy.Rules.Add(firewallRule);
firewallRule.Description = "Block inbound traffic";
firewallRule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
//firewallRule.LocalPorts = "8080";
//firewallRule.Grouping = "#firewallapi.dll,-23255";
firewallRule.Enabled = true;
firewallRule.RemoteAddresses = ip;
//firewallPolicy.Rules.Add(firewallRule); //throws error, not needed
} else {
var remoteAddresses = firewallRule.RemoteAddresses;
firewallRule.RemoteAddresses = remoteAddresses + "," + ip;
}
}