using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using Nuclex.Networking.Gallery3.Responses;
using System.Web;
namespace Nuclex.Networking.Gallery3.Requests {
/// Creates requests to read or write resources
public class RequestFactory : IRequestFactory {
/// Initializs a new simple request factory
/// URL of the gallery installation
///
/// If the URL doesn't end with 'index.php', it will automatically
/// be appended to the URL. For gallery installations where index.php
/// is not required in the path, use the second constructor overload.
///
public RequestFactory(string galleryUrl) :
this(galleryUrl, false) { }
/// Initializs a new simple request factory
/// URL of the gallery installation
///
/// Whether to take to URL as it is or to append 'index.php' if it is missing
///
///
/// By default, gallery 3 installations require 'index.php' to be specified
/// in the URL with any REST request. If you have modified your gallery 3
/// installation, renamed index.php or do not want this for any other reason,
/// specifying true for the parameter makes
/// the request factory use the URL exactly as it is specified.
///
public RequestFactory(string galleryUrl, bool asIs) {
if (!asIs) {
if (!galleryUrl.EndsWith("/")) {
galleryUrl += '/';
}
if (!galleryUrl.EndsWith("index.php/")) {
galleryUrl += "index.php/";
}
}
GalleryUri = new Uri(galleryUrl);
initializeSerializer();
}
/// Creates a new request for the specified resource
/// Resource the request will access
/// The new request
///
/// The parameter is a relative path below
/// gallery's base URL. A typical resource URL would be 'rest/item/1'.
///
public IRequest CreateRequest(string resourceUrl) {
Uri requestUri = new Uri(GalleryUri, resourceUrl);
WebRequest request = HttpWebRequest.Create(requestUri);
OnRequestCreated(request);
return new Request(this.jsonSerializer, request);
}
/// Called when a new WebRequest is created
/// The new WebRequest
///
/// This method can be overridden in derived classes to modify new requests
/// created by the factory, for example in order to add authentication options.
///
protected virtual void OnRequestCreated(WebRequest request) { }
/// Base URL of the gallery installation
///
/// Should include the 'index.php' part of the URL
///
protected Uri GalleryUri { get; private set; }
/// Initializes the JSON serializer used to decode responses
private void initializeSerializer() {
this.jsonSerializer = new JavaScriptSerializer();
this.jsonSerializer.RegisterConverters(
new JavaScriptConverter[] { new GalleryDateTimeConverter() }
);
}
/// JSON serializer used to decode responses to the requests
private JavaScriptSerializer jsonSerializer;
}
} // namespace Nuclex.Networking.Gallery3.Requests