本文整理汇总了C#中XDoc类的典型用法代码示例。如果您正苦于以下问题:C# XDoc类的具体用法?C# XDoc怎么用?C# XDoc使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
XDoc类属于命名空间,在下文中一共展示了XDoc类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateUser
public void CreateUser() {
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
try {
// Define user information and generate user XML document
string name = Utils.GenerateUniqueName();
string email = "[email protected]";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user")
.Elem("username", name)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
// Create the User
DreamMessage msg = p.At("users").Post(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User creation failed");
// Assert all the information in the returned document is consistent
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["email"].AsText == email, "Email does not match that in return document");
Assert.IsTrue(msg.ToDocument()["fullname"].AsText == fullName, "Full name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["permissions.user/role"].AsText == role, "User permissions does not match that in return document");
}
// In the case the username already exists
catch(MindTouch.Dream.DreamResponseException ex) {
Assert.IsTrue(ex.Response.Status == DreamStatus.Conflict, "Username already exists, but did not return Conflict?!");
}
}
示例2: Can_provide_list_of_args_as_repeated_params_to_feature
public void Can_provide_list_of_args_as_repeated_params_to_feature()
{
MockServiceInfo mock = MockService.CreateMockService(_hostInfo);
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) {
XDoc msg = new XDoc("ids");
foreach(KeyValuePair<string, string> kv in context.GetParams()) {
if(kv.Key == "id") {
msg.Elem("id", kv.Value);
}
}
response2.Return(DreamMessage.Ok(msg));
};
Plug p = mock.AtLocalHost;
int n = 100;
List<string> ids = new List<string>();
for(int i = 0; i < n; i++) {
p = p.With("id", i);
ids.Add(i.ToString());
}
DreamMessage result = p.GetAsync().Wait();
Assert.IsTrue(result.IsSuccessful);
List<string> seen = new List<string>();
foreach(XDoc id in result.ToDocument()["id"]) {
string v = id.AsText;
Assert.Contains(v, ids);
Assert.IsFalse(seen.Contains(v));
seen.Add(v);
}
Assert.AreEqual(ids.Count, seen.Count);
}
示例3: S3Storage
//--- Constructors ---
public S3Storage(XDoc configuration, ILog log) {
_timerFactory = TaskTimerFactory.Create(this);
_log = log;
_publicKey = configuration["publickey"].AsText;
_privateKey = configuration["privatekey"].AsText;
_bucket = configuration["bucket"].AsText;
_prefix = configuration["prefix"].AsText;
if(string.IsNullOrEmpty(_publicKey)) {
throw new ArgumentException("Invalid Amazon S3 publickey");
}
if(string.IsNullOrEmpty(_privateKey)) {
throw new ArgumentException("Invalid Amazon S3 privatekey");
}
if(string.IsNullOrEmpty(_bucket)) {
throw new ArgumentException("Invalid Amazon S3 bucket");
}
if(string.IsNullOrEmpty(_prefix)) {
throw new ArgumentException("Invalid Amazon S3 prefix");
}
_tempDirectory = Path.Combine(Path.GetTempPath(), "s3_cache_" + XUri.EncodeSegment(_prefix));
if(Directory.Exists(_tempDirectory)) {
Directory.Delete(_tempDirectory, true);
}
Directory.CreateDirectory(_tempDirectory);
_allowRedirects = configuration["allowredirects"].AsBool ?? false;
_redirectTimeout = TimeSpan.FromSeconds(configuration["redirecttimeout"].AsInt ?? 60);
_cacheTtl = (configuration["cachetimeout"].AsInt ?? 60 * 60).Seconds();
// initialize S3 plug
_s3 = Plug.New("http://s3.amazonaws.com", TimeSpan.FromSeconds(configuration["timeout"].AsDouble ?? DEFAUTL_S3_TIMEOUT)).WithPreHandler(S3AuthenticationHeader).At(_bucket);
}
示例4: PageSubscriptionInstance
//--- Constructors ---
public PageSubscriptionInstance(string wikiId, XDoc config, IContainer container) {
_log.DebugFormat("created PageSubscriptionInstance for wikiid '{0}'", wikiId);
_wikiId = wikiId;
_pageSubscriptionSessionFactory = container.Resolve<IPageSubscriptionDataSessionFactory>(new NamedParameter("config", config));
// derive siteinfo
_sitename = config["ui/sitename"].AsText;
if(string.IsNullOrEmpty(_sitename)) {
_log.WarnFormat("missing ui/sitename for instance {0}", _wikiId);
}
_timezone = config["ui/timezone"].AsText;
var emailFromAddress = config["page-subscription/from-address"].AsText;
if(string.IsNullOrEmpty(emailFromAddress)) {
emailFromAddress = config["admin/email"].AsText;
}
if(string.IsNullOrEmpty(emailFromAddress)) {
_log.WarnFormat("missing page-subscription/from-address and admin/email for instance {0}", _wikiId);
} else {
var address = new MailAddress(emailFromAddress);
if(string.IsNullOrEmpty(address.DisplayName)) {
address = new MailAddress(emailFromAddress, emailFromAddress);
}
_emailFromAddress = address.ToString();
}
_emailFormat = config["page-subscription/email-format"].AsText;
_useShortEmailAddress = config["page-subscription/use-short-email-address"].AsBool ?? false;
_culture = CultureUtil.GetNonNeutralCulture(config["ui/language"].AsText) ?? CultureInfo.GetCultureInfo("en-us");
}
示例5: GetFeatureOverview
private static XDoc GetFeatureOverview(XDoc feature)
{
// generate a document containing the overview information for a feature
XDoc overviewDoc = new XDoc("html");
overviewDoc.Start("h2").Value("Overview").End();
overviewDoc.Add(GetWarning());
overviewDoc.Start("p").Start("strong").Value(feature["access"].Contents + ". ").End().Value(feature["description"].Contents).End();
XDoc uriParams = new XDoc("uriParams");
XDoc queryParams = new XDoc("queryParams");
foreach(XDoc param in feature["param"]) {
string paramName = param["name"].Contents;
if(paramName.StartsWith("{")) {
if(feature["pattern"].Contents.Contains(paramName)) {
param["name"].ReplaceValue(paramName.Trim(new char[] { '{', '}' }));
uriParams.Add(param);
}
} else {
queryParams.Add(param);
}
}
overviewDoc.Start("h5").Value("Uri Parameters").End();
overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, uriParams["param"]));
overviewDoc.Start("h5").Value("Query Parameters").End();
overviewDoc.Add(GetTable(new string[] { "Name", "Type", "Description" }, queryParams["param"]));
overviewDoc.Start("h5").Value("Return Codes").End();
XDoc statusesDoc = new XDoc("statuses");
foreach(XDoc statusDoc in feature["status"]) {
DreamStatus status = (DreamStatus)statusDoc["@value"].AsInt;
statusesDoc.Start("status").Elem("name", status.ToString()).Elem("value", (int)status).Elem("description", statusDoc.Contents).End();
}
overviewDoc.Add(GetTable(new string[] { "Name", "Value", "Description" }, statusesDoc["status"]));
return overviewDoc;
}
示例6: GlobalSetup
public void GlobalSetup() {
_log.Debug("setup");
var assemblyPath = @"MindTouch.Deki.Util.Tests.dll";
_inspector = new TypeInspector();
_inspector.InspectAssembly(assemblyPath);
_xmlDocumentation = XDocFactory.LoadFrom(@"MindTouch.Deki.Util.Tests.xml", MimeType.TEXT_XML);
}
示例7: StockQuote
public XDoc StockQuote(
[DekiExtParam("stock ticker symbol")] string symbol
) {
// check keys
string app = Config["finance-app-id"].AsText;
string sig = Config["finance-sig"].AsText;
if(string.IsNullOrEmpty(app) || string.IsNullOrEmpty(sig)) {
return new XDoc("html").Start("body").Start("span").Attr("style", "color:red;font-weight:bold;").Value("The Yahoo! Finance Application ID or Signature are missing").End().End();
}
// create control
symbol = symbol.ToUpperInvariant();
XDoc result = new XDoc("html").Start("body").Start("iframe")
.Attr("allowtransparency", "true")
.Attr("marginwidth", "0")
.Attr("marginheight", "0")
.Attr("hspace", "0")
.Attr("vspace", "0")
.Attr("frameborder", "0")
.Attr("scrolling", "no")
.Attr("src", string.Format("http://api.finance.yahoo.com/instrument/1.0/{0}/badge;quote/HTML?AppID={1}&sig={2}", XUri.EncodeSegment(symbol), XUri.EncodeQuery(app), XUri.EncodeQuery(sig)))
.Attr("width", "200px")
.Attr("height", "250px")
.Start("a").Attr("href", "http://finance.yahoo.com").Value("Yahoo! Finance").End()
.Elem("br")
.Start("a").Attr("href", string.Format("http://finance.yahoo.com/q?s={0}", XUri.EncodeQuery(symbol))).Value(string.Format("Quote for {0}", symbol)).End()
.End().End();
return result;
}
示例8: Add_recipients_to_event
public void Add_recipients_to_event()
{
XDoc msg = new XDoc("msg");
DispatcherRecipient r1 = new DispatcherRecipient(new XUri("mailto:///[email protected]"));
DispatcherRecipient r2 = new DispatcherRecipient(new XUri("mailto:///[email protected]"));
DispatcherRecipient r3 = new DispatcherRecipient(new XUri("mailto:///[email protected]"));
DispatcherEvent ev1 = new DispatcherEvent(msg, new XUri("channel://foo.com/bar"), new XUri("http://foo.com/baz"));
DispatcherEvent ev2 = ev1.WithRecipient(false, r1);
Assert.AreEqual(0, ev1.Recipients.Length);
Assert.AreEqual(1, ev2.Recipients.Length);
Assert.AreEqual(r1, ev2.Recipients[0]);
DispatcherEvent ev3 = ev2.WithRecipient(false, r2, r3);
Assert.AreEqual(3, ev3.Recipients.Length);
Assert.AreEqual(r1, ev3.Recipients[0]);
Assert.AreEqual(r2, ev3.Recipients[1]);
Assert.AreEqual(r3, ev3.Recipients[2]);
DreamMessage ev3msg = ev3.AsMessage();
Assert.AreEqual(msg, ev3msg.ToDocument());
Assert.AreEqual(ev1.Id, ev3.Id);
Assert.AreEqual("channel://foo.com/bar", ev3msg.Headers.DreamEventChannel);
Assert.AreEqual("http://foo.com/baz", ev3msg.Headers.DreamEventOrigin[0]);
string[] recipients = ev3msg.Headers.DreamEventRecipients;
Assert.AreEqual(3, recipients.Length);
Assert.AreEqual(r1.ToString(), recipients[0]);
Assert.AreEqual(r2.ToString(), recipients[1]);
Assert.AreEqual(r3.ToString(), recipients[2]);
}
示例9: GetContentHandler
public DreamMessage GetContentHandler(DreamContext context, DreamMessage message) {
user user = Authenticate(context, message, DekiUserLevel.User);
page page = Authorize(context, user, DekiAccessLevel.Read, "pageid");
DekiContext deki = new DekiContext(message, this.DekiConfig);
bool nofollow = (context.Uri.GetParam("nofollow", 0, null) != null);
string contents = page.getContent(nofollow);
string xml = string.Format(DekiWikiService.XHTML_LOOSE, contents);
XDoc doc = XDoc.FromXml(xml);
if (doc == null) {
LogUtils.LogWarning(_log, "GetContentHandler: null document page content", page.PrefixedName, contents);
throw new DreamAbortException(DreamMessage.BadRequest("null document"));
}
XDoc result = new XDoc("list");
string type = context.Uri.GetParam("type", 0, null);
string id = context.Uri.GetParam("id", 0, null);
if (id != null) {
XDoc widget = doc[string.Format("//default:span[@widgetid={0}]", id)];
if (widget.IsEmpty) {
LogUtils.LogWarning(_log, "GetContentHandler: widget not found for ID", id);
return DreamMessage.NotFound("");
}
LogUtils.LogTrace(_log, "GetContentHandler: widget by id (id, xspan)", id, widget);
result.Add(ConvertFromXSpan(widget));
} else if (type != null) {
foreach (XDoc widget in doc[string.Format("//default:span[@widgettype='{0}']", type)])
result.Add(ConvertFromXSpan(widget));
LogUtils.LogTrace(_log, "GetContentHandler: widget by type (type, #)", type, result.Count);
} else {
foreach (XDoc widget in doc["//default:span[@class='widget']"])
result.Add(ConvertFromXSpan(widget));
LogUtils.LogTrace(_log, "GetContentHandler: all widgets (#)", type, result.Count);
}
return DreamMessage.Ok(result);
}
示例10: BuildXDoc
public virtual XDoc BuildXDoc(XDoc rootDoc, string xpath, int nodeCount)
{
XDoc subdoc = rootDoc[xpath];
if(nodeCount == subdoc.ListLength) {
return subdoc;
}
string[] segments = xpath.Split('/');
// assume the doc root is out rootPath for the collection
if(nodeCount > 1 && segments.Length == 1 && segments[0].StartsWith("@")) {
throw new ArgumentException("Cannot have a collection whose xpath is an attribute on the root");
}
bool lastIsAttribute = segments[segments.Length - 1].StartsWith("@");
string last = segments[segments.Length - 1];
if(lastIsAttribute) {
last = last.Substring(1);
}
string lastElement = null;
int lastElementIndex = lastIsAttribute ? segments.Length - 2 : segments.Length - 1;
if(lastElementIndex >= 0) {
lastElement = segments[lastElementIndex];
}
int rootLength = lastIsAttribute ? segments.Length - 1 : segments.Length;
string[] rootPathSegments = new string[rootLength];
Array.Copy(segments, rootPathSegments, rootLength);
XDoc localRoot = CreateRootPath(rootDoc, rootPathSegments);
if(nodeCount == 1) {
if(lastIsAttribute && lastElement != null) {
if(localRoot[lastElement].IsEmpty) {
localRoot.Elem(lastElement);
}
localRoot = localRoot[lastElement];
}
if(lastIsAttribute) {
localRoot.Attr(last, "");
} else {
localRoot.Elem(last);
}
} else {
// dump current matches
foreach(XDoc old in localRoot[lastElement]) {
old.Remove();
}
// rebuild a fresh set
if(lastIsAttribute && lastElement != null) {
for(int i = 0; i < nodeCount; i++) {
localRoot.Start(lastElement).Attr(last,"").End();
}
} else {
for(int i = 0; i < nodeCount; i++) {
localRoot.Elem(last);
}
}
}
subdoc = rootDoc[xpath];
return subdoc;
}
示例11: Exporter_hits_export_feature_on_creation_using_relto
public void Exporter_hits_export_feature_on_creation_using_relto() {
// Arrange
XUri dekiApiUri = new XUri("http://mock/@api/deki");
XDoc exportDocument = new XDoc("export")
.Start("page")
.Attr("path", "/")
.Attr("recursive", "true")
.Attr("exclude", "all")
.End();
XDoc exportResponse = new XDoc("export")
.Start("requests")
.End()
.Start("manifest")
.Elem("justanode")
.End();
AutoMockPlug mock = MockPlug.Register(dekiApiUri);
mock.Expect("POST", dekiApiUri.At("site", "export").With("relto", 5.ToString()), exportDocument, DreamMessage.Ok(exportResponse));
// Act
Exporter exporter = Exporter.CreateAsync(Plug.New(dekiApiUri), exportDocument, 5, new Result<Exporter>()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
Assert.AreEqual(exportResponse["manifest"], exporter.Manifest);
}
示例12: SaveCommentsLinks
private void SaveCommentsLinks(XDoc spaceManifest, string space, long confluencePageId, string mtPath) {
RemoteComment[] comments = _confluenceService.GetComments(confluencePageId);
foreach(RemoteComment comment in comments) {
LogCommentConversion(spaceManifest, space, comment, mtPath);
}
}
示例13: GetSearchDescription
public Yield GetSearchDescription(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc description = new XDoc("OpenSearchDescription", "http://a9.com/-/spec/opensearch/1.1/");
description.Elem("ShortName", string.Format(DekiResources.OPENSEARCH_SHORTNAME, DekiContext.Current.Instance.SiteName))
.Elem("Description", DekiResources.OPENSEARCH_DESCRIPTION)
.Start("Query")
.Attr("role", "example")
.Attr("searchTerms", "Wiki")
.End();
// HACK HACK HACK: we can't use XUri because it encodes the "{}" characters
string uri = DekiContext.Current.ApiUri.At("site", "opensearch").ToString();
uri += "?q={searchTerms}&offset={startIndex}&limit={count?}&";
description.Start("Url")
.Attr("type", "text/html")
.Attr("indexOffset", 0)
.Attr("template", DekiContext.Current.UiUri.At("Special:Search").ToString() + "?search={searchTerms}&offset=0&limit={count?}&format=html")
.End()
.Start("Url")
.Attr("type", "application/atom+xml")
.Attr("indexOffset", 0)
.Attr("template", uri + "format=atom")
.End()
.Start("Url")
.Attr("type", "application/rss+xml")
.Attr("indexOffset", 0)
.Attr("template", uri + "format=rss")
.End()
.Start("Url")
.Attr("type", "application/x-suggestions+json")
.Attr("template", DekiContext.Current.ApiUri.At("site", "opensearch", "suggestions").ToString() + "?q={searchTerms}")
.End();
response.Return(DreamMessage.Ok(description));
yield break;
}
示例14: FromDocument
//--- Class Methods ---
public static NotificationUpdateRecord FromDocument(XDoc doc) {
var record = new NotificationUpdateRecord(doc["@wikiid"].AsText, doc["@userid"].AsUInt.Value);
foreach(var page in doc["page"]) {
record.Add(page["@id"].AsUInt.Value, page["@modified"].AsDate.Value);
}
return record;
}
示例15: AddTableStyles
//--- Class Methods ---
private static XDoc AddTableStyles(XDoc doc) {
XDoc head = doc["head"];
if(head.IsEmpty) {
doc.Elem("head");
head = doc["head"];
}
head.Start("style").Attr("type", "text/css").Value(@".feedtable {
border:1px solid #999;
line-height:1.5em;
overflow:hidden;
width:100%;
}
.feedtable th {
background-color:#ddd;
border-bottom:1px solid #999;
font-size:14px;
}
.feedtable tr {
background-color:#FFFFFF;
}
.feedtable tr.feedroweven td {
background-color:#ededed;
}").End();
return doc;
}