Before Google Analytic Update there api this code works.
string userName = GAEmailAddress.ToString();//Its From Database
string passWord = GAPassword.ToString();//Its From Database
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService("AnalyticsApp");
if (!string.IsNullOrEmpty(userName))
{
service.setUserCredentials(userName, passWord);
}
string str = "";
try
{
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
{
str = entry.ProfileId.Value;
}
DataQuery query1 = new DataQuery(dataFeedUrl);
// Bounce Rate Calculations
query1.Ids = str;
query1.Metrics = "ga:visits,ga:bounces";//visitors
query1.Sort = "ga:visits";
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
query1.StartIndex = 1;
//Others code and other data for bound
I search in SO and and Find this link.
gapi account data url goes to 404
I replace this link :
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
with:
https://www.googleapis.com/analytics/v2.4/management/accounts?start-index=1&max-results=100&key=API_KEY
But I still I gett error:
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I still search and find this link:
https://developers.google.com/analytics/devguides/reporting/core/v2/#register
As link says I replace :
https://www.googleapis.com/analytics/v2.4/data
But still I got error ? What I am missing here? Thanks.
Related
We are using geocoding service to get geocodeAddress (latitude/longitude) but we are getting the "The service method is not found" error. Below are my code.
public static double[] GeocodeAddress(string address, string virtualearthKey)
{
net.virtualearth.dev.GeocodeRequest geocodeRequest = new net.virtualearth.dev.GeocodeRequest
{
// Set the credentials using a valid Bing Maps key
Credentials = new net.virtualearth.dev.Credentials { ApplicationId = virtualearthKey },
// Set the full address query
Query = address
};
// Set the options to only return high confidence results
net.virtualearth.dev.ConfidenceFilter[] filters = new net.virtualearth.dev.ConfidenceFilter[1];
filters[0] = new net.virtualearth.dev.ConfidenceFilter
{
MinimumConfidence = net.virtualearth.dev.Confidence.High
};
// Add the filters to the options
net.virtualearth.dev.GeocodeOptions geocodeOptions = new net.virtualearth.dev.GeocodeOptions { Filters = filters };
geocodeRequest.Options = geocodeOptions;
// Make the geocode request
net.virtualearth.dev.GeocodeService geocodeService = new net.virtualearth.dev.GeocodeService();
net.virtualearth.dev.GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
if (geocodeResponse.Results.Length > 0)
{
return new[] { geocodeResponse.Results[0].Locations[0].Latitude, geocodeResponse.Results[0].Locations[0].Longitude };
}
return new double[] { };
} // GeocodeAddress
Key is used for URL for bing map geocode service in we.config
<add key="net.virtualearth.dev.GeocodeService" value="http://dev.virtualearth.net/webservices/v1/geocodeservice/GeocodeService.svc" />
Looks like you are trying to use the old Virtual Earth SOAP Services which were deprecated and shut down last year. These were replaced by the Bing Maps REST services 7 or 8 years ago. Since you are working in .NET, take a look at the Bing Maps .NET REST Toolkit. It makes it easy to use the REST services in .NET. There is a NuGet package available as well. You can find details here: https://github.com/Microsoft/BingMapsRESTToolkit
Once you have the NuGet package added to your project, you can geocode like this:
//Create a request.
var request = new GeocodeRequest()
{
Query = "New York, NY",
IncludeIso2 = true,
IncludeNeighborhood = true,
MaxResults = 25,
BingMapsKey = "YOUR_BING_MAPS_KEY"
};
//Execute the request.
var response = await request.Execute();
if(response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
//Do something with the result.
}
I have a ASP.NET app that I'm trying to log custom parameters from to NewRelic. The code for logging looks like this:
this.searchResults = performanceMonitor.RecordQuery(() => searchManager.DoQuery(this.searchRequest));
The performanceMonitor is just an object that does this:
public TSearchResult RecordQuery<TSearchResult>(Func<TSearchResult> query) where TSearchResult : SearchResult
{
var stopwatch = Stopwatch.StartNew();
var result = query();
stopwatch.Stop();
var externalTime = stopwatch.ElapsedMilliseconds;
var internalTime = ToMilliseconds(result.ExecutionTicks);
NewRelicHelper.AddAttributeToTransaction("QueryExternalTime", externalTime);
NewRelicHelper.AddAttributeToTransaction("QueryInternalTime", internalTime);
return result;
}
All the line with NewRelicHelper does is call NewRelic.Api.Agent.NewRelic.AddCustomParameter with "QueryExternalTime" and externalTime.
Yet after executing this code on machines with NewRelic agents, when I run a NewRelic query, I cannot see either QueryExternalTime or QueryInternalTime with their respective values on any transactions.
So I am building a web application that I want to sell once Im done with it. It allows the user to enter data such as their website name, meta keywords, their contact email, phone, address etc in the admin panel. I wrote a Action Filter in order to include these values in every request that I put the filter on so I didnt have to query for them every time because these values are included in the common footer throughout the site. However, I learned that if I update the database with new or different information for these values, it does not update on the web pages which im guessing is because Action Filters are configured at application start up. In the Action Filter I am using a repository pattern to query for these values. I have included the code for the action filter below. How can I have the convenience of the Action Filter but be able to update it dynamically when the data changes in the database? Thanks!
public class ViewBagActionFilter : ActionFilterAttribute,IActionFilter
{
Repositories.SettingsRepository _repo = new Repositories.SettingsRepository();
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
string siteName = _repo.GetSiteName();
string siteDesc = _repo.GetSiteDescription();
string siteKeywords = _repo.GetSiteKeywords();
string googleAnalytics = _repo.GetGoogleAnalytics();
string streetAddress = _repo.GetStreetAddress();
string zipCode = _repo.GetZipCode();
string city = _repo.GetCity();
string state = _repo.GetState();
string aboutUs = _repo.GetAboutUs();
string phone = _repo.GetPhoneNumber();
string contactEmail = _repo.GetContactEmail();
if (!string.IsNullOrWhiteSpace(siteName) && siteName.Length > 0)
{
string[] splitSiteName = new string[siteName.Length/2];
splitSiteName = siteName.Split(' ');
if (splitSiteName.Length > 1)
{
filterContext.Controller.ViewBag.SiteName1 = splitSiteName[0];
filterContext.Controller.ViewBag.SiteName2 = splitSiteName[1];
}
else
{
filterContext.Controller.ViewBag.SiteName1 = splitSiteName[0];
filterContext.Controller.ViewBag.SiteName2 = "";
}
}
//Set default values for common viewbag items that are on every page using ternary syntax
filterContext.Controller.ViewBag.SiteDescription = (!string.IsNullOrWhiteSpace(siteDesc) && siteDesc.Length > 0) ? siteDesc : "";
filterContext.Controller.ViewBag.SiteKeywords = (!string.IsNullOrWhiteSpace(siteKeywords) && siteKeywords.Length > 0) ? siteKeywords : "";
filterContext.Controller.ViewBag.GoogleAnalytics = (!string.IsNullOrWhiteSpace(googleAnalytics) && googleAnalytics.Length > 0) ? googleAnalytics : "";
filterContext.Controller.ViewBag.StreetAddress = (!string.IsNullOrWhiteSpace(streetAddress) && streetAddress.Length > 0) ? streetAddress : "";
filterContext.Controller.ViewBag.ZipCode = (!string.IsNullOrWhiteSpace(zipCode) && zipCode.Length > 0) ? zipCode : "";
filterContext.Controller.ViewBag.City = (!string.IsNullOrWhiteSpace(city) && city.Length > 0) ? city : "";
filterContext.Controller.ViewBag.State = (!string.IsNullOrWhiteSpace(state) && state.Length > 0) ? state : "";
filterContext.Controller.ViewBag.AboutUs = (!string.IsNullOrWhiteSpace(aboutUs) && aboutUs.Length > 0) ? aboutUs : "";
filterContext.Controller.ViewBag.PhoneNumber = (!string.IsNullOrWhiteSpace(phone) && phone.Length > 0) ? phone : "";
filterContext.Controller.ViewBag.ContactEmail = (!string.IsNullOrWhiteSpace(contactEmail) && contactEmail.Length > 0) ? contactEmail : "";
base.OnActionExecuting(filterContext);
}
}
I will try to explain how action filters works.
So if you extend Action filter you can override 4 base methods :
OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.
So thats mean that you method will be called each time before Controller will run action.
Now about optimization. You have
string siteName = _repo.GetSiteName();
string siteDesc = _repo.GetSiteDescription();
string siteKeywords = _repo.GetSiteKeywords();
string googleAnalytics = _repo.GetGoogleAnalytics();
string streetAddress = _repo.GetStreetAddress();
string zipCode = _repo.GetZipCode();
string city = _repo.GetCity();
string state = _repo.GetState();
string aboutUs = _repo.GetAboutUs();
string phone = _repo.GetPhoneNumber();
string contactEmail = _repo.GetContactEmail();
I would suggest you to create one class
public class Site{
public string SiteName{get;set;}
public string City{get;set;}
//And so on just to add all properties
}
then in repository add one more method
_repo.GetSite(); //Which will return object Site
Then
filterContext.Controller.ViewBag.CurrentSite = _repo.GetSite();
And now probably the most important for you. Why it doesnot work as you want and its a bit simple. Attribute class is initialized only once on Application start and after that it doesnot reloads, and your implementation is a bit strange since
Repositories.SettingsRepository _repo = new Repositories.SettingsRepository();
I suppose here you are loading settings. So after you load you did not reload it anymore... thats mean you will get same result each time you reload page, but if you restart iis for instance you will refresh data.
Possible solution
Move initialization of _repo to OnActionExecuting then it will reload data each time, or rewrite repository as i suggested and
filterContext.Controller.ViewBag.CurrentSite = _repo.GetSite();
Should always load new data from db.
Hope it helps :)
So I have been driving myself crazy trying to figure out why I can't get my LDAP search to work.
private String getDNFromLDAP(String strUID)
{
String strDN = "";
//Create an LDAP Entry Object
DirectoryEntry entry = new DirectoryEntry("LDAP://something.blah.com/cn=people,dc=blah,dc=com");
entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
entry.Username = "cn=myaccount,cn=special,dc=blah,dc=com";
entry.Password = "supersecret";
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.SearchScope = SearchScope.Subtree;
mySearcher.Filter = "(uid=" + strUID + ")";
SearchResult result = mySearcher.FindOne();
int nIndex = result.Path.LastIndexOf("/");
strDN = result.Path.Substring((nIndex + 1)).ToString().TrimEnd();
//Clean up objects
entry.Close();
entry.Dispose();
mySearcher.Dispose();
//returns the DN
return strDN;
}
I know the object I am searching for exist (confirmed with ldapsearch), but my result keeps coming back empty. I suspect there is an issue with the base dn, but I don't know how to confirm what what DirectorySearch is using as the base dn. Any help at all would be appreciated.
You set the root using the searchroot property. The root is set to entry you pass on the constructor, so this might be why you can't find your entry.
I have a site behind basic authentication (IIS6).
Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.
However, when this happens the calling code receives a 401 Authentication Error.
I've tried a couple of things, with the general recommendation being code like this:
Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");
However, this does not seem to resolve my problem.
Any advice?
Edit
This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.
Solution: (I am almost certain this will help someone)
See this link for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.
NB: You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary.
public static void ServiceCall(Page p)
{
LocalServices.ServiceName s = new LocalServices.ServiceName();
s.PreAuthenticate = true; /* Not sure if required */
string username = "";
string password = "";
string domain = "";
GetBasicCredentials(p, ref username, ref password, ref domain);
s.Credentials = new NetworkCredential(username, password, domain);
s.ServiceMethod();
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain)
{
if (p == null)
{
return;
}
rstrUser = "";
rstrPassword = "";
rstrDomain = "";
rstrUser = p.Request.ServerVariables["AUTH_USER"];
rstrPassword = p.Request.ServerVariables["AUTH_PASSWORD"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
/* MSDN KB article 835388
BUG: The Request.ServerVariables("AUTH_PASSWORD") object does not display certain characters from an ASPX page */
string lstrHeader = p.Request.ServerVariables["HTTP_AUTHORIZATION"];
if (!string.IsNullOrEmpty(lstrHeader) && lstrHeader.StartsWith("Basic"))
{
string lstrTicket = lstrHeader.Substring(6);
lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket));
rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(":") + 1));
}
/* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication
But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION)
then we can use LOGON_USER*/
if (string.IsNullOrEmpty(rstrUser) && !string.IsNullOrEmpty(rstrPassword))
{
rstrUser = p.Request.ServerVariables["LOGON_USER"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
}
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName)
{
rstrDomainName = "";
rstrUserName = pstrDomainUserName;
int lnSlashPos = pstrDomainUserName.IndexOf("\\");
if (lnSlashPos > 0)
{
rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos);
rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1);
}
}
The Line:
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
Maybe you should try :
s.Credentials = HttpContext.Current.User.Identity;