C# Modifying multiple Dictionary Values throws error - c#

I'm using HTML Agility Pack to download some pages, I'm also storing cookie info and login info from a form. The issue I'm having is that I'm doing a GET operation to get the cookie info and form details so on the next step it can login using a username and password, I'm then trying to set the value of the username and password input fields so that I can then post to a login page. The input fields are being stored in a Dictionary<string,string>. I'm able to change one of the dictionary values, but after that I get the error:
"Object reference not set to an instance of an object.".
If I try to change password and then username the username throws the error and vice-versa. This is the code im using:
class Main
{
private void testLogin()
{
BrowserSession b = new BrowserSession();
b.Get("login.html");
b.FormElements["email_address"] = #"email";
b.FormElements["password"] = "password";
string response = b.Post("index.php?main_page=login");
}
}
}
public class BrowserSession
{
private bool _isPost;
private HtmlDocument _htmlDoc;
/// <summary>
/// System.Net.CookieCollection. Provides a collection container for instances of Cookie class
/// </summary>
public CookieCollection Cookies { get; set; }
/// <summary>
/// Provide a key-value-pair collection of form elements
/// </summary>
public FormElementCollection FormElements { get; set; }
/// <summary>
/// Makes a HTTP GET request to the given URL
/// </summary>
public string Get(string url)
{
_isPost = false;
CreateWebRequestObject().Load(url);
return _htmlDoc.DocumentNode.InnerHtml;
}
/// <summary>
/// Makes a HTTP POST request to the given URL
/// </summary>
public string Post(string url)
{
_isPost = true;
CreateWebRequestObject().Load(url, "POST");
return _htmlDoc.DocumentNode.InnerHtml;
}
/// <summary>
/// Creates the HtmlWeb object and initializes all event handlers.
/// </summary>
private HtmlWeb CreateWebRequestObject()
{
HtmlWeb web = new HtmlWeb();
web.UseCookies = true;
web.PreRequest = new HtmlWeb.PreRequestHandler(OnPreRequest);
web.PostResponse = new HtmlWeb.PostResponseHandler(OnAfterResponse);
web.PreHandleDocument = new HtmlWeb.PreHandleDocumentHandler(OnPreHandleDocument);
return web;
}
/// <summary>
/// Event handler for HtmlWeb.PreRequestHandler. Occurs before an HTTP request is executed.
/// </summary>
protected bool OnPreRequest(HttpWebRequest request)
{
AddCookiesTo(request); // Add cookies that were saved from previous requests
if (_isPost) AddPostDataTo(request); // We only need to add post data on a POST request
return true;
}
/// <summary>
/// Event handler for HtmlWeb.PostResponseHandler. Occurs after a HTTP response is received
/// </summary>
protected void OnAfterResponse(HttpWebRequest request, HttpWebResponse response)
{
SaveCookiesFrom(response); // Save cookies for subsequent requests
}
/// <summary>
/// Event handler for HtmlWeb.PreHandleDocumentHandler. Occurs before a HTML document is handled
/// </summary>
protected void OnPreHandleDocument(HtmlDocument document)
{
SaveHtmlDocument(document);
}
/// <summary>
/// Assembles the Post data and attaches to the request object
/// </summary>
private void AddPostDataTo(HttpWebRequest request)
{
string payload = FormElements.AssemblePostPayload();
byte[] buff = Encoding.UTF8.GetBytes(payload.ToCharArray());
request.ContentLength = buff.Length;
request.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream reqStream = request.GetRequestStream();
reqStream.Write(buff, 0, buff.Length);
}
/// <summary>
/// Add cookies to the request object
/// </summary>
private void AddCookiesTo(HttpWebRequest request)
{
if (Cookies != null && Cookies.Count > 0)
{
request.CookieContainer.Add(Cookies);
}
}
/// <summary>
/// Saves cookies from the response object to the local CookieCollection object
/// </summary>
private void SaveCookiesFrom(HttpWebResponse response)
{
if (response.Cookies.Count > 0)
{
if (Cookies == null) Cookies = new CookieCollection();
Cookies.Add(response.Cookies);
}
}
/// <summary>
/// Saves the form elements collection by parsing the HTML document
/// </summary>
private void SaveHtmlDocument(HtmlDocument document)
{
_htmlDoc = document;
FormElements = new FormElementCollection(_htmlDoc);
}
}
public class FormElementCollection : Dictionary<string, string>
{
/// <summary>
/// Constructor. Parses the HtmlDocument to get all form input elements.
/// </summary>
public FormElementCollection(HtmlDocument htmlDoc)
{
var inputs = htmlDoc.DocumentNode.SelectSingleNode("//div[#id = 'loginDefault']").Descendants("input");
foreach (var element in inputs)
{
string name = element.GetAttributeValue("name", "undefined");
string value = element.GetAttributeValue("value", "");
if (!name.Equals("undefined")) { Add(name, value); }
}
}
/// <summary>
/// Assembles all form elements and values to POST. Also html encodes the values.
/// </summary>
public string AssemblePostPayload()
{
StringBuilder sb = new StringBuilder();
foreach (var element in this)
{
string value = HttpUtility.UrlEncode(element.Value);
sb.Append("&" + element.Key + "=" + value);
}
return sb.ToString().Substring(1);
}
}
Any help would be much appreciated.

While debugging put a break point after calling the b constractor.
You ll find the FormElements property is Null.
You need to inialize it in BrowserSession constractor.

Related

Handle multiple binding errors from ModelBindingException in NancyFX when binding to JSON in Request.Body

I have a post route that accepts some JSON payload in the request body.
Post["/myroute/}"] = _ =>
{
try
{
var model = this.Bind<MyModel>();
}
catch (ModelBindingException e)
{
//PropertyBindException list is empty here,
//so only the first exception can be handled...
}
}
If there are multiple invalid data types (i.e. if there are several int properties defined in MyModel, and a user posts strings for those properties), I would like pass back a nice list of these errors, similar to how would use ModelState dictionary in a vanilla ASP.NET MVC application.
How can I accomplish this type of exception handling when attempting to bind the JSON payload in the request body to my Model in NancyFX?
Update:
Looking through the DefaultBinder in the Nancy source here:
https://github.com/sloncho/Nancy/blob/master/src/Nancy/ModelBinding/DefaultBinder.cs
The problem I see is that in this block:
try
{
var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext);
if (bodyDeserializedModel != null)
{
UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext);
}
}
catch (Exception exception)
{
if (!bindingContext.Configuration.IgnoreErrors)
{
throw new ModelBindingException(modelType, innerException: exception);
}
}
The Deserialize call seems to be "all or nothing" and it is handled by a plain Exception, not a ModelBindException, so I cannot see any PropertyBindExceptions here either.
Should I be needing to implement something custom for this...?
Add your own custom body serializer that uses newtonsoft to ignore errors:
public class CustomBodyDeserializer : IBodyDeserializer
{
private readonly MethodInfo deserializeMethod = typeof(JavaScriptSerializer).GetMethod("Deserialize", BindingFlags.Instance | BindingFlags.Public);
private readonly JsonConfiguration jsonConfiguration;
private readonly GlobalizationConfiguration globalizationConfiguration;
/// <summary>
/// Initializes a new instance of the <see cref="JsonBodyDeserializer"/>,
/// with the provided <paramref name="environment"/>.
/// </summary>
/// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
public CustomBodyDeserializer(INancyEnvironment environment)
{
this.jsonConfiguration = environment.GetValue<JsonConfiguration>();
this.globalizationConfiguration = environment.GetValue<GlobalizationConfiguration>();
}
/// <summary>
/// Whether the deserializer can deserialize the content type
/// </summary>
/// <param name="mediaRange">Content type to deserialize</param>
/// <param name="context">Current <see cref="BindingContext"/>.</param>
/// <returns>True if supported, false otherwise</returns>
public bool CanDeserialize(MediaRange mediaRange, BindingContext context)
{
return Json.IsJsonContentType(mediaRange);
}
/// <summary>
/// Deserialize the request body to a model
/// </summary>
/// <param name="mediaRange">Content type to deserialize</param>
/// <param name="bodyStream">Request body stream</param>
/// <param name="context">Current context</param>
/// <returns>Model instance</returns>
public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)
{
//var serializer = new JavaScriptSerializer(this.jsonConfiguration, this.globalizationConfiguration);
//serializer.RegisterConverters(this.jsonConfiguration.Converters, this.jsonConfiguration.PrimitiveConverters);
if (bodyStream.CanSeek)
{
bodyStream.Position = 0;
}
string bodyText;
using (var bodyReader = new StreamReader(bodyStream))
{
bodyText = bodyReader.ReadToEnd();
}
// var genericDeserializeMethod = this.deserializeMethod.MakeGenericMethod(context.DestinationType);
// var deserializedObject = genericDeserializeMethod.Invoke(serializer, new object[] { bodyText });
object deserializedObject = JsonConvert.DeserializeObject(bodyText, context.DestinationType, new JsonSerializerSettings
{
Error = HandleDeserializationError
});
return deserializedObject;
}
public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
{
string currentError = errorArgs.ErrorContext.Error.Message;
errorArgs.ErrorContext.Handled = true;
}
}

Json Geocode address parsing in C#

I want to get address of the location
Iam using google geocode to get address by passing lat and long.
static readonly string RequestUrl = "http://maps.google.com/maps/api/geocode/json?";
/// <summary>
/// Gets the raw object.
/// </summary>
/// <returns></returns>
protected JsonGeoData GetJsonObject() {
StringBuilder url = new StringBuilder( GeoRequest.RequestUrl);
if (this.Location != null) {
url.AppendFormat("latlng={0}", this.Location.ToString());
}
else {
url.AppendFormat("address={0}", HttpUtility.UrlEncode(this.Address));
}
url.AppendFormat("&sensor={0}", this.IsSensor.ToString().ToLower());
if (!string.IsNullOrEmpty(this.Language))
url.AppendFormat("&language={0}", HttpUtility.UrlEncode(this.Language));
if(!string.IsNullOrEmpty(this.Region))
url.AppendFormat("&region={0}", HttpUtility.UrlEncode(this.Region));
WebRequest request = WebRequest.Create(url.ToString());
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<JsonGeoData>(reader.ReadToEnd());
}
}
}
/// <summary>
/// Gets the response.
/// </summary>
/// <returns></returns>
public GeoResponse GetResponse() {
return new GeoResponse(this.GetJsonObject());
}
/// <summary cref="A">
/// fetching location from web
/// </summary>
/// <typeparam name="T"></typeparam>
private string getloc(double plat, double plng)
{
try
{
GeoRequest objreq = new GeoRequest(plat, plng);
GeoResponse objres = objreq.GetResponse();
if (objres.Results.Count > 0)
{ return objres.Results[0].FormattedAddress; }
else
{ return "Unknown"; }
}
catch (FormatException) { return "Unknown"; }
catch (Exception)
{ return "Unknown"; }
}
iam trying to get json data from geocode and parse using serializer,
But iam getting error 'sublocality_level_2 is not a valid value for GeoAddressType.'

Why can I still write to session when SessionStateBehavior.ReadOnly is set on a controller and should I care?

I have a number of controllers with SessionStateBehavior.ReadOnly set on them to enable parallel processing of multiple ajax requests.
But I have noticed that this doesn't stop me from writing to session (unlike SessionStateBehavior.Disabled which throws an exception).
My application uses Microsoft Charting and the chart and image map are generated in response to an ajax request with the chart being stored in session until the image markup is rendered by the browser at which point the image src triggers the browser to request the chart image which is retrieved from session. So there are no issues here with attempting to read from session before its been written.
Everything works fine, I have multiple ajax requests being processed in parallel and my charts are being returned correctly so does it matter that I have declared SessionStateBehavior.ReadOnly when I am writing to session?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using Mdl.Rcm.Web.Areas.Dashboards.Models;
using Mdl.Web.Security;
using Mdl.Persistence.UoW;
using Mdl.Rcm.Business.Dashboards;
using Mdl.Rcm.Business.Dashboards.Models;
using Mdl.Rcm.Web.Areas.Dashboards.Charts;
using Mdl.Rcm.Web.Areas.Dashboards.Charts.OrganisationConnectionsByRole;
using Mdl.Web.Mvc;
namespace Mdl.Rcm.Web.Areas.Dashboards.Controllers
{
/// <summary>
/// Controller for the Organisation Connections By Role chart.
/// </summary>
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
[RedirectingAuthorize(Roles = "Dashboards")]
[Area(IsSiteRoot = false)]
public class ChartOrganisationConnectionsByRoleController : Controller
{
private readonly IRelationshipAndRiskService relationshipAndRiskService;
private readonly IConfigurationService configurationService;
private readonly IOrganisationConnectionsByRoleChartBuilder chartBuilder;
private readonly IListService listService;
private BarConfiguration barConfiguration;
private const string TempDataKey = "OrganisationConnectionsByRoleData";
public ChartOrganisationConnectionsByRoleController(IOrganisationConnectionsByRoleChart organisationConnectionsByRoleChart, IRelationshipAndRiskService relationshipAndRiskService, IConfigurationService configurationService, IOrganisationConnectionsByRoleChartBuilder chartBuilder, IListService listService)
{
this.relationshipAndRiskService = relationshipAndRiskService;
this.configurationService = configurationService;
this.chartBuilder = chartBuilder;
this.listService = listService;
}
/// <summary>
/// Standard Organisation Connections by Role component loader
/// </summary>
/// <param name="listId">The list id.</param>
/// <param name="degree">The active degree.</param>
/// <param name="barIndex">Index of the active bar.</param>
/// <returns></returns>
[HandleAjaxError]
public ActionResult Load(int listId, int degree, int barIndex)
{
using (UnitOfWork.Start("Analysis"))
{
// Get the data
var relationshipPlanningData = GetChartDataForInitialLoadParentComponent(listId);
var connectionsFound = relationshipPlanningData.SeriesModels.Count > 0;
var listName = listService.GetListName(listId).Name;
var information = new InformationModel(degree, true) { ConnectionsFound = connectionsFound, NumberOfOrganisationsInList = relationshipPlanningData.TotalNumberOfOrganisations, ListName = listName };
return PartialView("OrganisationConnectionsByRoleComponent", new OrganisationConnectionsByRoleComponentModel { ListId = listId, ActiveDegree = degree, ActiveBarIndex = barIndex, BarConfiguration = configurationService.GetBarConfiguration(), ConnectionsFound = connectionsFound, Information = information});
}
}
/// <summary>
/// Creates the Connections by Role chart and stores it in Session then returns the chart map.
/// The chart image map is always created first, the chart is created as part of the process of creating the map.
/// </summary>
/// <returns></returns>
public ActionResult Chart(Guid chartId, int listId)
{
using (UnitOfWork.Start("Analysis"))
{
barConfiguration = configurationService.GetBarConfiguration();
var relationshipPlanningData = GetChartDataForInitialLoadChart();
if (relationshipPlanningData.SeriesModels.Count == 0)
{
return PartialView("InfoMessage", "No connections found");
}
// Set up the chart
return GenerateChart(relationshipPlanningData, listId, chartId);
}
}
private ActionResult GenerateChart(OrganisationConnectionsByRoleData relationshipPlanningData, int listId, Guid chartId)
{
var chartAndXPoints = chartBuilder.BuildChart(2, relationshipPlanningData, barConfiguration, SetActiveBarIndex(-1), listId);
// Store the chart in session for retrieval by the browser as the src on an image tag.
ChartSession.GenerateChartToSession(chartId, chartAndXPoints.Chart, Session);
// Get y data for use client side
var yPointsDataView = GetYPointsDataView(relationshipPlanningData);
// Get x co-ordinates for use client side. Must be done after the chart has been generated to session.
var xPointsView = GetXPointsView(chartAndXPoints.XPoints);
// Render the image tag and image map
return this.Chart(chartAndXPoints.Chart, xPointsView + yPointsDataView, chartId, "ConnectionsByRoleImage");
}
/// <summary>
/// Gets the chart data for use by the main component.
/// </summary>
/// <param name="listId">The list id.</param>
/// <returns></returns>
private OrganisationConnectionsByRoleData GetChartDataForInitialLoadParentComponent(int listId)
{
// This is the call from the load action so get the data and store it for use by the chart action to save the performance hit
var data = relationshipAndRiskService.GetOrganisationConnectionsByRoleChartData(listId);
TempData[TempDataKey] = data;
return data;
}
/// <summary>
/// Gets the chart data for use by the main component chart.
/// </summary>
/// <returns></returns>
private OrganisationConnectionsByRoleData GetChartDataForInitialLoadChart()
{
// This call is from the chart action so use the data that was retreived on the load action
return (OrganisationConnectionsByRoleData)TempData[TempDataKey];
}
/// <summary>
/// Return the Connections By Role chart from session.
/// </summary>
/// <returns></returns>
public ActionResult ConnectionsByRoleImage(Guid chartId)
{
var chart = ChartSession.GetChartFromSession(chartId, Session);
return File(chart, "image");
}
/// <summary>
/// Return the Connections By Role chart from session.
/// </summary>
/// <param name="listId">The list id.</param>
/// <param name="degree">The active degree.</param>
/// <param name="barIndex">Index of the active bar.</param>
/// <returns></returns>
public ActionResult ConnectionsByRoleActive(int listId, int degree, int barIndex)
{
using (UnitOfWork.Start("Analysis"))
{
barConfiguration = configurationService.GetBarConfiguration();
// Get the data
var relationshipPlanningData = relationshipAndRiskService.GetOrganisationConnectionsByRoleChartData(listId);
if (relationshipPlanningData.SeriesModels.Count == 0)
{
return PartialView("InfoMessage", "No connections found");
}
// Set up the chart
var chartAndXPoints = chartBuilder.BuildChart(SetActiveDegree(degree), relationshipPlanningData, barConfiguration, SetActiveBarIndex(-1), listId);
var ms = new MemoryStream();
chartAndXPoints.Chart.SaveImage(ms, ChartImageFormat.Png);
return File(ms.ToArray(), "image");
}
}
/// <summary>
/// Gets the graph X points and render them as a javascript object for use by the view.
/// </summary>
/// <param name="xPoints">The x points.</param>
/// <returns></returns>
private string GetXPointsView(List<float> xPoints)
{
var model = new XPointsModel
{
ChartName = "Connections By Role",
Points = xPoints
};
return this.ViewAsString("XPoints", model);
}
/// <summary>
/// Gets the Y points data and render them as a javascript object for use by the view.
/// </summary>
/// <param name="relationshipPlanningData">The relationship planning data.</param>
/// <returns></returns>
private string GetYPointsDataView(OrganisationConnectionsByRoleData relationshipPlanningData)
{
var degree1DataPoints = relationshipPlanningData.SeriesModels[0].DataPoints.Select(p => p.Y).ToList();
var degree2DataPoints = relationshipPlanningData.SeriesModels[1].DataPoints.Select(p => p.Y).ToList();
var model = new YPointsDegree1And2Model
{
ChartName = "Connections By Role",
Degree1Data = degree1DataPoints,
Degree2Data = degree2DataPoints
};
return this.ViewAsString("YPointsDegree1And2", model);
}
private int SetActiveBarIndex(int barIndex)
{
if (barIndex == -1)
{
barIndex = barConfiguration.Bars.First(b => b.IsDefaultActive).Index;
}
return barIndex;
}
private static int SetActiveDegree(int degree)
{
if (degree == -1)
{
degree = 2;
}
return degree;
}
}
}
public class ChartSession
{
public static byte[] GetChartFromSession(Guid chartId, HttpSessionStateBase session)
{
// Get the chart from session
var data = session[chartId.ToString()] as byte[];
// Clear the session
session[chartId.ToString()] = null;
return data;
}
public static void GenerateChartToSession(Guid chartId, Chart chart, HttpSessionStateBase session)
{
var ms = new MemoryStream();
chart.SaveImage(ms, ChartImageFormat.Png);
session[chartId.ToString()] = ms.ToArray();
}
SessionStateBehavior only tells ASP.NET what locks to put on the Session
See this question: Controller SessionStateBehavior is ReadOnly and I can update Session Variable

Google Adwords API C# Client Library

I downloaded the Adwords API client library for DOTNET. I am trying to use the GetAccountHierarchy.cs file example to get the account client list from Adwords Account. The code is appended as below:
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201209;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201209 {
/// <summary>
/// This code example illustrates how to retrieve the account hierarchy under
/// an account. This code example won't work with Test Accounts. See
/// https://developers.google.com/adwords/api/docs/test-accounts
///
/// Tags: ManagedCustomerService.get
/// </summary>
public class GetAccountHierarchy : ExampleBase {
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args) {
GetAccountHierarchy codeExample = new GetAccountHierarchy();
Console.WriteLine(codeExample.Description);
try {
codeExample.Run(new AdWordsUser());
} catch (Exception ex) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(ex));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example illustrates how to retrieve the account hierarchy under" +
" an account. This code example won't work with Test Accounts. See " +
"https://developers.google.com/adwords/api/docs/test-accounts";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
public void Run(AdWordsUser user) {
// Get the ManagedCustomerService.
ManagedCustomerService managedCustomerService = (ManagedCustomerService) user.GetService(
AdWordsService.v201209.ManagedCustomerService);
managedCustomerService.RequestHeader.clientCustomerId = null;
// Create selector.
Selector selector = new Selector();
selector.fields = new String[] {"Login", "CustomerId", "Name"};
try {
// Get results.
ManagedCustomerPage page = managedCustomerService.get(selector);
// Display serviced account graph.
if (page.entries != null) {
// Create map from customerId to customer node.
Dictionary<long, ManagedCustomerTreeNode> customerIdToCustomerNode =
new Dictionary<long, ManagedCustomerTreeNode>();
// Create account tree nodes for each customer.
foreach (ManagedCustomer customer in page.entries) {
ManagedCustomerTreeNode node = new ManagedCustomerTreeNode();
node.Account = customer;
customerIdToCustomerNode.Add(customer.customerId, node);
}
// For each link, connect nodes in tree.
if (page.links != null) {
foreach (ManagedCustomerLink link in page.links) {
ManagedCustomerTreeNode managerNode =
customerIdToCustomerNode[link.managerCustomerId];
ManagedCustomerTreeNode childNode = customerIdToCustomerNode[link.clientCustomerId];
childNode.ParentNode = managerNode;
if (managerNode != null) {
managerNode.ChildAccounts.Add(childNode);
}
}
}
// Find the root account node in the tree.
ManagedCustomerTreeNode rootNode = null;
foreach (ManagedCustomer account in page.entries) {
if (customerIdToCustomerNode[account.customerId].ParentNode == null) {
rootNode = customerIdToCustomerNode[account.customerId];
break;
}
}
// Display account tree.
Console.WriteLine("Login, CustomerId, Name");
Console.WriteLine(rootNode.ToTreeString(0, new StringBuilder()));
} else {
Console.WriteLine("No serviced accounts were found.");
}
} catch (Exception ex) {
throw new System.ApplicationException("Failed to create ad groups.", ex);
}
}
/**
* Example implementation of a node that would exist in an account tree.
*/
class ManagedCustomerTreeNode {
/// <summary>
/// The parent node.
/// </summary>
private ManagedCustomerTreeNode parentNode;
/// <summary>
/// The account associated with this node.
/// </summary>
private ManagedCustomer account;
/// <summary>
/// The list of child accounts.
/// </summary>
private List<ManagedCustomerTreeNode> childAccounts = new List<ManagedCustomerTreeNode>();
/// <summary>
/// Gets or sets the parent node.
/// </summary>
public ManagedCustomerTreeNode ParentNode {
get { return parentNode; }
set { parentNode = value; }
}
/// <summary>
/// Gets or sets the account.
/// </summary>
public ManagedCustomer Account {
get { return account; }
set { account = value; }
}
/// <summary>
/// Gets the child accounts.
/// </summary>
public List<ManagedCustomerTreeNode> ChildAccounts {
get { return childAccounts; }
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString() {
String login = String.IsNullOrEmpty(account.login) ? "(no login)" : account.login;
return String.Format("{0}, {1}, {2}", login, account.customerId, account.name);
}
/// <summary>
/// Returns a string representation of the current level of the tree and
/// recursively returns the string representation of the levels below it.
/// </summary>
/// <param name="depth">The depth of the node.</param>
/// <param name="sb">The String Builder containing the tree
/// representation.</param>
/// <returns>The tree string representation.</returns>
public StringBuilder ToTreeString(int depth, StringBuilder sb) {
sb.Append(new String('-', depth * 2));
sb.Append(this);
sb.Append("\n");
foreach (ManagedCustomerTreeNode childAccount in childAccounts) {
childAccount.ToTreeString(depth + 1, sb);
}
return sb;
}
}
}
}
I am trying to figure out where i can pass the parameter like my account username, password, developer token and access token to this function? Does anybody know how i can pass those info to this code? Thanks.
It seems to me, wildly guessing, the account, username and password are present in some secondary resource files not passed in as arguments, or typed into the program as input, but loaded automatically from some 'special' location by the Google API.
Do you, perhaps, have a PGP type keys downloaded from the AdWords program?
I know this getting old but you can pass parameter in your app.config/web.config
<add key="ClientCustomerId" value="insert your client customer id"/>
<add key="AuthorizationMethod" value="OAuth2"/>
<add key="OAuth2ClientId" value="insert oauth2 client id"/>
<add key="OAuth2ClientSecret" value="insert oauth client scret"/>
<add key="OAuth2RefreshToken" value="insert oauth2 refresh token"/>
all oauth2 value you can get from google API Manager

C# & ASP.NET - Anyone create a library to talk to EdgeCast CDN via FTP?

For one of my projects we utilize a Content Delivery Network (EdgeCast) and I was wondering if anyone knew of an existing (open source) library for C# that we could leverage? In a nutshell, I am investigating the ability to create directories, upload files, and allow some general maintenance (rename files, delete files) via our admin panel. Any insight would be appreciated.
NOTE: My code to do this. I don't know if they have an updated API at this point so please check. This code is circa 2009 (as-is, no warranties, use at your own risk, etc).
EdgeCast.cs
using System;
using edgeCastWS = [DOMAIN].com.edgecast.api.EdgeCastWebServices;
namespace [DOMAIN].IO.ContentDeliveryNetwork
{
/// <summary>
/// <b>Authentication</b>
/// <para>Each web service call will include a string parameter called strCredential which will ensure that customers may only access data related to their own accounts. This credential is a string made up of a few separate pieces of information.</para>
/// <para>A typical credential a customer would use may look like: “c:bas:user#email.com:password”</para>
/// <para> * The field format of this string is delimited with a colon “:” character.</para>
/// <para> * The first field is the type of client which is calling the web service. “c” represents an individual customer.</para>
/// <para> * The second field is the security type. “bas” represents Basic Authentication.</para>
/// <para> * With basic authentication the third field is the username which is usually in email address notation.</para>
/// <para> * With basic authentication the fourth field is the password associated with the user.</para>
/// <para>If the username and password are not valid, then the credential will prevent the specified function from proceeding. A SOAP exception will be generated and sent back to the client that called the function. The message contained in the exception will contain the string “Access Denied.”</para>
/// </summary>
public class EdgeCast : IDisposable
{
#region Declarations
[ThreadStatic]
private static EdgeCast _current;
private static EdgeCastCredential _credential = null;
private static string _customerID = string.Empty;
private static edgeCastWS _edgeCastWS = null;
#endregion
#region Constructor
public EdgeCast()
{
if (_current != null)
{
throw new InvalidOperationException("Only one ContentDeliveryNetwork may be created on a given thread.");
}
_current = this;
_edgeCastWS = new edgeCastWS();
ConstructCredentials();
_customerID = AppSettings.EdgeCast_CustomerID;
}
#endregion
#region API Methods
/// <summary>
/// Purges a file from all of the EdgeCast caching servers. This process may take a few minutes to fully complete.
/// </summary>
/// <param name="Path">This is path of the file or folder to purge, in URL format. To specify a folder, please put a trailing slash at the end of the URL. All files under that folder will be purged</param>
/// <param name="MediaType">HTTP Large Object = 3, HTTP Small Object = 8, Flash = 2, Windows = 1</param>
/// <returns>An integer that indicates whether or not the transaction was successful. 0 represents yes, -1 represents no</returns>
internal static short PurgeFileFromEdge(string Path, int MediaType)
{
return _edgeCastWS.PurgeFileFromEdge(_credential.Credential, _customerID, Path, MediaType);
}
/// <summary>
/// Loads a file to disk on all of the EdgeCast caching servers. This process may take a few minutes to fully complete.
/// </summary>
/// <param name="Path">This is path of the file to load, in URL format. Folders may not be loaded and will be ignored</param>
/// <param name="MediaType">HTTP Large Object = 3, HTTP Small Object = 8</param>
/// <returns>An integer that indicates whether or not the transaction was successful. 0 represents yes, -1 represents no</returns>
internal static short LoadFileToEdge(string Path, int MediaType)
{
return _edgeCastWS.LoadFileToEdge(_credential.Credential, _customerID, Path, MediaType);
}
/// <summary>
/// This method call is used to add a token authentication directory. All additions and changes should be processed every 30 minutes
/// </summary>
/// <param name="Dir">Directory Path should be starting from the root. Example: /directory1/directory2</param>
/// <param name="MediaType">Use 1 for Windows, 2 for Flash, 3 for HTTP Caching / Progressive download.</param>
/// <returns></returns>
internal static short TokenDirAdd(string Dir, int MediaType)
{
return _edgeCastWS.TokenDirAdd(_credential.Credential, _customerID, Dir, MediaType);
}
internal static string TokenEncrypt(string Key, string Args)
{
return _edgeCastWS.TokenEncrypt(_credential.Credential, Key, Args);
}
internal static short TokenKeyUpdate(string Key, int MediaType)
{
return _edgeCastWS.TokenKeyUpdate(_credential.Credential, _customerID, Key, MediaType);
}
#endregion
#region FTP Methods
/// <summary>
/// Does a FTP Upload of a file on the local system
/// </summary>
/// <param name="targetPath">The full path to save to on the FTP server (.\Campaigns\Prod\[Company GUID])</param>
/// <param name="sourceFileName">The full path and filename of the file to be uploaded (C:\[DOMAIN]\files\[filename])</param>
internal static void FTP_UploadFile(string targetPath, string sourceFileName)
{
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// Make sure the directories are there and change down to the bottom most directory...
foreach (string dirName in dirs)
{
bool dirExists = true;
try { myFTP.chdir(dirName); }
catch { dirExists = false; }
if (!dirExists)
{
myFTP.mkdir(dirName);
myFTP.chdir(dirName);
}
}
// upload the file now...
myFTP.upload(sourceFileName);
}
}
/// <summary>
/// Returns a string array of files in the target directory
/// </summary>
/// <param name="targetPath">The target directory</param>
/// <returns>string array or null if no files found</returns>
internal static string[] FTP_GetFileList(string targetPath)
{
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
string[] files = null;
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// Make sure the directories are there and change down to the bottom most directory...
foreach (string dirName in dirs)
{
bool dirExists = true;
try { myFTP.chdir(dirName); }
catch { dirExists = false; }
if (!dirExists)
{
myFTP.mkdir(dirName);
myFTP.chdir(dirName);
}
}
// get the list of files now...
files = myFTP.getFileList("*.*");
}
return files;
}
/// <summary>
/// Checks to see if a file exists
/// </summary>
/// <param name="targetPath">The CDN directory path to look in</param>
/// <param name="targetFile">The file to look for</param>
/// <returns>true = found, false = not found</returns>
internal static bool FTP_DoesFileExist(string targetPath, string targetFile)
{
bool retFlag = true;
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// change to the target directory - if it does not exists, neither does the file! simple...
foreach (string dirName in dirs)
{
try { myFTP.chdir(dirName); }
catch { retFlag = false; }
}
if (retFlag)
{
try { retFlag = myFTP.getFileSize(targetFile) > 0; }
catch { retFlag = false; }
}
}
return retFlag;
}
internal static bool FTP_DoesFileExist(string targetFile)
{
string targetPath = targetFile.Replace(#"http://", "");
targetPath = targetPath.Replace(#"https://", "");
targetPath = targetPath.Replace(#"cdn1.[DOMAIN].com/", "");
targetPath = targetPath.Replace(#"/", #"\");
targetPath = targetPath.Substring(0, targetPath.LastIndexOf(#"\"));
targetFile = targetFile.Substring(targetFile.LastIndexOf(#"/") + 1);
return FTP_DoesFileExist(targetPath, targetFile);
}
#endregion
#region Helper Methods
static private string ConstructCredentials()
{
_credential = new EdgeCastCredential();
return _credential.Credential;
}
static private string ConstructCredentials(string credentials)
{
_credential = new EdgeCastCredential(credentials);
return _credential.Credential;
}
static private string ConstructCredentials(string typeOfClient, string securityType, string userName, string password)
{
_credential = new EdgeCastCredential(typeOfClient, securityType, userName, password);
return _credential.Credential;
}
#endregion
#region IDisposable Members
public void Dispose()
{
_current = null;
}
#endregion
}
}
EdgeCastCredential.cs
using System;
using rivSecurity = [DOMAIN].Security.Cryptography.Internal;
namespace [DOMAIN].IO.ContentDeliveryNetwork
{
internal class EdgeCastCredential
{
#region Properties
public string TypeOfClient;
public string SecurityType;
public string UserName;
public string Password;
public string Credential { get { return String.Format("{0}:{1}:{2}:{3}", TypeOfClient, SecurityType, UserName, Password); } }
#endregion
#region Constructor
public EdgeCastCredential()
{
TypeOfClient = AppSettings.EdgeCast_TypeOfClient;
SecurityType = AppSettings.EdgeCast_SecurityType;
UserName = rivSecurity.Decrypt(AppSettings.EdgeCast_UserName);
Password = rivSecurity.Decrypt(AppSettings.EdgeCast_Password);
}
public EdgeCastCredential(string credentials)
{
string[] parts = credentials.Split(new char[] { ':' });
}
public EdgeCastCredential(string typeOfClient, string securityType, string userName, string password)
{
TypeOfClient = typeOfClient;
SecurityType = securityType;
UserName = userName;
Password = password;
}
#endregion
}
}
Never mind. I created a FTP library and used what little they had for an API. I can not now read/upload/delete files and purge the CDN.

Categories