context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2014 lambdalice
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
namespace CoreTweet
{
public static partial class OAuth
{
public class OAuthSession
{
/// <summary>
/// Gets or sets the consumer key.
/// </summary>
/// <value>The consumer key.</value>
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the consumer secret.
/// </summary>
/// <value>The consumer secret.</value>
public string ConsumerSecret { get; set; }
/// <summary>
/// Gets or sets the request token.
/// </summary>
/// <value>The request token.</value>
public string RequestToken { get; set; }
/// <summary>
/// Gets or sets the request token secret.
/// </summary>
/// <value>The request token secret.</value>
public string RequestTokenSecret { get; set; }
/// <summary>
/// Gets or sets the options of connection.
/// </summary>
public ConnectionOptions ConnectionOptions { get; set; }
/// <summary>
/// Gets the authorize URL.
/// </summary>
/// <value>The authorize URL.</value>
public Uri AuthorizeUri
{
get
{
return new Uri(AuthorizeUrl + "?oauth_token=" + RequestToken);
}
}
}
/// <summary>
/// The request token URL.
/// </summary>
static readonly string RequestTokenUrl = "https://api.twitter.com/oauth/request_token";
/// <summary>
/// The access token URL.
/// </summary>
static readonly string AccessTokenUrl = "https://api.twitter.com/oauth/access_token";
/// <summary>
/// The authorize URL.
/// </summary>
static readonly string AuthorizeUrl = "https://api.twitter.com/oauth/authorize";
#if !PCL
/// <summary>
/// Generates the authorize URI.
/// Then call GetTokens(string) after get the pin code.
/// </summary>
/// <returns>
/// The authorize URI.
/// </returns>
/// <param name="consumerKey">
/// Consumer key.
/// </param>
/// <param name="consumerSecret">
/// Consumer secret.
/// </param>
/// <param name="oauthCallback">
/// <para>For OAuth 1.0a compliance this parameter is required. The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account. Set this to oob for out-of-band pin mode. This is also how you specify custom callbacks for use in desktop/mobile applications.</para>
/// <para>Always send an oauth_callback on this step, regardless of a pre-registered callback.</para>
/// </param>
/// <param name="proxy">
/// Proxy information for the request.
/// </param>
public static OAuthSession Authorize(string consumerKey, string consumerSecret, string oauthCallback = "oob", ConnectionOptions options = null)
{
// Note: Twitter says,
// "If you're using HTTP-header based OAuth, you shouldn't include oauth_* parameters in the POST body or querystring."
var prm = new Dictionary<string,object>();
if(!string.IsNullOrEmpty(oauthCallback))
prm.Add("oauth_callback", oauthCallback);
var header = Tokens.Create(consumerKey, consumerSecret, null, null)
.CreateAuthorizationHeader(MethodType.Get, RequestTokenUrl, prm);
var dic = from x in Request.HttpGet(RequestTokenUrl, prm, header, options).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select y.ReadToEnd()
.Split('&')
.Where(z => z.Contains('='))
.Select(z => z.Split('='))
.ToDictionary(z => z[0], z => z[1]);
return new OAuthSession()
{
RequestToken = dic["oauth_token"],
RequestTokenSecret = dic["oauth_token_secret"],
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
ConnectionOptions = options
};
}
/// <summary>
/// Gets the OAuth tokens.
/// Be sure to call GenerateAuthUri(string,string) before call this.
/// </summary>
/// <param name='pin'>
/// Pin code.
/// </param>
/// <param name='session'>
/// OAuth session.
/// </para>
/// <returns>
/// The tokens.
/// </returns>
public static Tokens GetTokens(this OAuthSession session, string pin)
{
var prm = new Dictionary<string,object>() { { "oauth_verifier", pin } };
var header = Tokens.Create(session.ConsumerKey, session.ConsumerSecret, session.RequestToken, session.RequestTokenSecret)
.CreateAuthorizationHeader(MethodType.Get, AccessTokenUrl, prm);
var dic = from x in Request.HttpGet(AccessTokenUrl, prm, header, session.ConnectionOptions).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select y.ReadToEnd()
.Split('&')
.Where(z => z.Contains('='))
.Select(z => z.Split('='))
.ToDictionary(z => z[0], z => z[1]);
var t = Tokens.Create(session.ConsumerKey, session.ConsumerSecret,
dic["oauth_token"], dic["oauth_token_secret"], long.Parse(dic["user_id"]), dic["screen_name"]);
t.ConnectionOptions = session.ConnectionOptions;
return t;
}
#endif
}
public static partial class OAuth2
{
/// <summary>
/// The access token URL.
/// </summary>
static readonly string AccessTokenUrl = "https://api.twitter.com/oauth2/token";
/// <summary>
/// The URL to revoke a OAuth2 Bearer Token.
/// </summary>
static readonly string InvalidateTokenUrl = "https://api.twitter.com/oauth2/invalidate_token";
private static string CreateCredentials(string consumerKey, string consumerSecret)
{
return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
}
#if !PCL
/// <summary>
/// Gets the OAuth 2 Bearer Token.
/// </summary>
/// <param name="consumerKey">Consumer key.</param>
/// <param name="consumerSecret">Consumer secret.</param>
/// <param name="proxy">Proxy information for the request.</param>
/// <returns>The tokens.</returns>
public static OAuth2Token GetToken(string consumerKey, string consumerSecret, ConnectionOptions options = null)
{
var token = from x in Request.HttpPost(
AccessTokenUrl,
new Dictionary<string,object>() { { "grant_type", "client_credentials" } }, // At this time, only client_credentials is allowed.
CreateCredentials(consumerKey, consumerSecret),
options).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select (string)JObject.Parse(y.ReadToEnd())["access_token"];
var t = OAuth2Token.Create(consumerKey, consumerSecret, token);
t.ConnectionOptions = options;
return t;
}
/// <summary>
/// Invalidates the OAuth 2 Bearer Token.
/// </summary>
/// <param name="tokens">An instance of OAuth2Tokens.</param>
/// <returns>The invalidated token.</returns>
public static string InvalidateToken(this OAuth2Token tokens)
{
return from x in Request.HttpPost(
InvalidateTokenUrl,
new Dictionary<string,object>() { { "access_token", Uri.UnescapeDataString(tokens.BearerToken) } },
CreateCredentials(tokens.ConsumerKey, tokens.ConsumerSecret),
tokens.ConnectionOptions).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select (string)JObject.Parse(y.ReadToEnd())["access_token"];
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Xml;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Site.Configuration;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Author: Joe Audette
/// Created: 1/18/2004
/// Last Modified: 2/7/2004
/// </summary>
public partial class RSS : Page
{
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
if (Request.Params.Get("mID") != null)
{
try
{
int ModuleID = int.Parse(Request.Params.Get("mID"));
RenderRSS(ModuleID);
}
catch (Exception ex)
{
RenderError(ex.Message);
}
}
else
{
RenderError("Invalid ModuleID");
}
}
/// <summary>
/// Renders the RSS.
/// </summary>
/// <param name="moduleID">The module ID.</param>
private void RenderRSS(int moduleID)
{
/*
For more info on RSS 2.0
http://www.feedvalidator.org/docs/rss2.html
Fields not implemented yet:
<blogChannel:blogRoll>http://radio.weblogs.com/0001015/userland/scriptingNewsLeftLinks.opml</blogChannel:blogRoll>
<blogChannel:mySubscriptions>http://radio.weblogs.com/0001015/gems/mySubscriptions.opml</blogChannel:mySubscriptions>
<blogChannel:blink>http://diveintomark.org/</blogChannel:blink>
<lastBuildDate>Mon, 30 Sep 2002 11:00:00 GMT</lastBuildDate>
<docs>http://backend.userland.com/rss</docs>
*/
Response.ContentType = "text/xml";
Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleID);
Encoding encoding = new UTF8Encoding();
XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteComment("RSS generated by Rainbow Portal Blog Module V 1.0 on " +
DateTime.Now.ToLongDateString());
xmlTextWriter.WriteStartElement("rss");
xmlTextWriter.WriteStartAttribute("version", "http://rainbowportal.net/blogmodule");
xmlTextWriter.WriteString("2.0");
xmlTextWriter.WriteEndAttribute();
xmlTextWriter.WriteStartElement("channel");
/*
RSS 2.0
Required elements for channel are title link and description
*/
xmlTextWriter.WriteStartElement("title");
//try
//{
//xmlTextWriter.WriteString(moduleSettings["MODULESETTINGS_TITLE_en-US"].ToString());
//}
//catch
//{
//HACK: Get MODULESETTINGS_TITLE from where?
xmlTextWriter.WriteString(TitleText(moduleSettings));
//}
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("link");
xmlTextWriter.WriteString(
Request.Url.ToString().Replace("DesktopModules/Blog/RSS.aspx", "DesktopDefault.aspx"));
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("description");
xmlTextWriter.WriteString(moduleSettings["Description"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("copyright");
xmlTextWriter.WriteString(moduleSettings["Copyright"].ToString());
xmlTextWriter.WriteEndElement();
// begin optional RSS 2.0 fields
//ttl = time to live in minutes, how long a channel can be cached before refreshing from the source
xmlTextWriter.WriteStartElement("ttl");
xmlTextWriter.WriteString(moduleSettings["RSS Cache Time In Minutes"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("managingEditor");
xmlTextWriter.WriteString(moduleSettings["Author Email"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("language");
xmlTextWriter.WriteString(moduleSettings["Language"].ToString());
xmlTextWriter.WriteEndElement();
// jes1111 - if(ConfigurationSettings.AppSettings.Get("webMaster") != null)
if (Config.WebMaster.Length != 0)
{
xmlTextWriter.WriteStartElement("webMaster");
xmlTextWriter.WriteString(ConfigurationManager.AppSettings.Get("webMaster"));
xmlTextWriter.WriteEndElement();
}
xmlTextWriter.WriteStartElement("generator");
xmlTextWriter.WriteString("Rainbow Portal Blog Module V 1.0");
xmlTextWriter.WriteEndElement();
BlogDB blogDB = new BlogDB();
SqlDataReader dr = blogDB.GetBlogs(moduleID);
try
{
//write channel items
while (dr.Read())
{
//beginning of blog entry
xmlTextWriter.WriteStartElement("item");
/*
RSS 2.0
All elements of an item are optional, however at least one of title or description
must be present.
*/
xmlTextWriter.WriteStartElement("title");
xmlTextWriter.WriteString(dr["Title"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("link");
xmlTextWriter.WriteString(Request.Url.ToString().Replace("RSS.aspx", "blogview.aspx") + "&ItemID=" +
dr["ItemID"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("pubDate");
xmlTextWriter.WriteString(
DateTime.Parse(dr["StartDate"].ToString()).ToString("dddd MMMM d yyyy hh:mm:ss tt zzz"));
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("guid");
xmlTextWriter.WriteString(Request.Url.ToString().Replace("RSS.aspx", "blogview.aspx") + "&ItemID=" +
dr["ItemID"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("comments");
xmlTextWriter.WriteString(Request.Url.ToString().Replace("RSS.aspx", "blogview.aspx") + "&ItemID=" +
dr["ItemID"].ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("description");
xmlTextWriter.WriteCData(Server.HtmlDecode((string) dr["Description"].ToString()));
xmlTextWriter.WriteEndElement();
//end blog entry
xmlTextWriter.WriteEndElement();
}
}
finally
{
dr.Close();
}
//end of document
xmlTextWriter.WriteEndElement();
xmlTextWriter.Close();
}
/// <summary>
/// The module title as it will be displayed on the page. Handles cultures automatically.
/// </summary>
/// <param name="moduleSettings">The module settings.</param>
/// <returns></returns>
private string TitleText(Hashtable moduleSettings)
{
string titleText = "Rainbow Blog";
if (HttpContext.Current != null) // if it is not design time (and not overriden - Jes1111)
{
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"];
if (portalSettings.PortalContentLanguage != CultureInfo.InvariantCulture
&& moduleSettings["MODULESETTINGS_TITLE_" + portalSettings.PortalContentLanguage.Name] != null
&&
moduleSettings["MODULESETTINGS_TITLE_" + portalSettings.PortalContentLanguage.Name].ToString().
Length > 0)
{
titleText =
moduleSettings["MODULESETTINGS_TITLE_" + portalSettings.PortalContentLanguage.Name].ToString();
}
}
return titleText;
}
/// <summary>
/// Renders the error.
/// </summary>
/// <param name="message">The message.</param>
private void RenderError(string message)
{
Response.Write(message);
Response.End();
}
#region Web Form Designer generated code
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(this.Page_Load);
base.OnInit(e);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Analysis.Tokenattributes
{
using Lucene.Net.Support;
using NUnit.Framework;
using BytesRef = Lucene.Net.Util.BytesRef;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestCharTermAttributeImpl : LuceneTestCase
{
[Test]
public virtual void TestResize()
{
CharTermAttribute t = new CharTermAttribute();
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, content.Length);
for (int i = 0; i < 2000; i++)
{
t.ResizeBuffer(i);
Assert.IsTrue(i <= t.Buffer().Length);
Assert.AreEqual("hello", t.ToString());
}
}
[Test]
public virtual void TestGrow()
{
CharTermAttribute t = new CharTermAttribute();
StringBuilder buf = new StringBuilder("ab");
for (int i = 0; i < 20; i++)
{
char[] content = buf.ToString().ToCharArray();
t.CopyBuffer(content, 0, content.Length);
Assert.AreEqual(buf.Length, t.Length);
Assert.AreEqual(buf.ToString(), t.ToString());
buf.Append(buf.ToString());
}
Assert.AreEqual(1048576, t.Length);
// now as a StringBuilder, first variant
t = new CharTermAttribute();
buf = new StringBuilder("ab");
for (int i = 0; i < 20; i++)
{
t.SetEmpty().Append(buf);
Assert.AreEqual(buf.Length, t.Length);
Assert.AreEqual(buf.ToString(), t.ToString());
buf.Append(t);
}
Assert.AreEqual(1048576, t.Length);
// Test for slow growth to a long term
t = new CharTermAttribute();
buf = new StringBuilder("a");
for (int i = 0; i < 20000; i++)
{
t.SetEmpty().Append(buf);
Assert.AreEqual(buf.Length, t.Length);
Assert.AreEqual(buf.ToString(), t.ToString());
buf.Append("a");
}
Assert.AreEqual(20000, t.Length);
}
[Test]
public virtual void TestToString()
{
char[] b = new char[] { 'a', 'l', 'o', 'h', 'a' };
CharTermAttribute t = new CharTermAttribute();
t.CopyBuffer(b, 0, 5);
Assert.AreEqual("aloha", t.ToString());
t.SetEmpty().Append("hi there");
Assert.AreEqual("hi there", t.ToString());
}
[Test]
public virtual void TestClone()
{
CharTermAttribute t = new CharTermAttribute();
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, 5);
char[] buf = t.Buffer();
CharTermAttribute copy = TestToken.AssertCloneIsEqual(t);
Assert.AreEqual(t.ToString(), copy.ToString());
Assert.AreNotSame(buf, copy.Buffer());
}
[Test]
public virtual void TestEquals()
{
CharTermAttribute t1a = new CharTermAttribute();
char[] content1a = "hello".ToCharArray();
t1a.CopyBuffer(content1a, 0, 5);
CharTermAttribute t1b = new CharTermAttribute();
char[] content1b = "hello".ToCharArray();
t1b.CopyBuffer(content1b, 0, 5);
CharTermAttribute t2 = new CharTermAttribute();
char[] content2 = "hello2".ToCharArray();
t2.CopyBuffer(content2, 0, 6);
Assert.IsTrue(t1a.Equals(t1b));
Assert.IsFalse(t1a.Equals(t2));
Assert.IsFalse(t2.Equals(t1b));
}
[Test]
public virtual void TestCopyTo()
{
CharTermAttribute t = new CharTermAttribute();
CharTermAttribute copy = TestToken.AssertCopyIsEqual(t);
Assert.AreEqual("", t.ToString());
Assert.AreEqual("", copy.ToString());
t = new CharTermAttribute();
char[] content = "hello".ToCharArray();
t.CopyBuffer(content, 0, 5);
char[] buf = t.Buffer();
copy = TestToken.AssertCopyIsEqual(t);
Assert.AreEqual(t.ToString(), copy.ToString());
Assert.AreNotSame(buf, copy.Buffer());
}
[Test]
public virtual void TestAttributeReflection()
{
CharTermAttribute t = new CharTermAttribute();
t.Append("foobar");
TestUtil.AssertAttributeReflection(t, new Dictionary<string, object>()
{
{ typeof(ICharTermAttribute).Name + "#term", "foobar" },
{ typeof(ITermToBytesRefAttribute).Name + "#bytes", new BytesRef("foobar") }
});
}
[Test]
public virtual void TestCharSequenceInterface()
{
const string s = "0123456789";
CharTermAttribute t = new CharTermAttribute();
t.Append(s);
Assert.AreEqual(s.Length, t.Length);
Assert.AreEqual("12", t.SubSequence(1, 3).ToString());
Assert.AreEqual(s, t.SubSequence(0, s.Length).ToString());
//Assert.IsTrue(Pattern.matches("01\\d+", t));
//Assert.IsTrue(Pattern.matches("34", t.SubSequence(3, 5)));
Assert.AreEqual(s.Substring(3, 4), t.SubSequence(3, 7).ToString());
for (int i = 0; i < s.Length; i++)
{
Assert.IsTrue(t.CharAt(i) == s[i]);
}
}
[Test]
public virtual void TestAppendableInterface()
{
/*CharTermAttribute t = new CharTermAttribute();
Formatter formatter = new Formatter(t, Locale.ROOT);
formatter.format("%d", 1234);
Assert.AreEqual("1234", t.ToString());
formatter.format("%d", 5678);
Assert.AreEqual("12345678", t.ToString());
t.Append('9');
Assert.AreEqual("123456789", t.ToString());
t.Append(new StringCharSequenceWrapper("0"));
Assert.AreEqual("1234567890", t.ToString());
t.Append(new StringCharSequenceWrapper("0123456789"), 1, 3);
Assert.AreEqual("123456789012", t.ToString());
t.Append((ICharSequence) CharBuffer.wrap("0123456789".ToCharArray()), 3, 5);
Assert.AreEqual("12345678901234", t.ToString());
t.Append((ICharSequence) t);
Assert.AreEqual("1234567890123412345678901234", t.ToString());
t.Append((ICharSequence) new StringBuilder("0123456789"), 5, 7);
Assert.AreEqual("123456789012341234567890123456", t.ToString());
t.Append((ICharSequence) new StringBuilder(t));
Assert.AreEqual("123456789012341234567890123456123456789012341234567890123456", t.ToString());
// very wierd, to test if a subSlice is wrapped correct :)
CharBuffer buf = CharBuffer.wrap("0123456789".ToCharArray(), 3, 5);
Assert.AreEqual("34567", buf.ToString());
t.SetEmpty().Append((ICharSequence) buf, 1, 2);
Assert.AreEqual("4", t.ToString());
ICharTermAttribute t2 = new CharTermAttribute();
t2.Append("test");
t.Append((ICharSequence) t2);
Assert.AreEqual("4test", t.ToString());
t.Append((ICharSequence) t2, 1, 2);
Assert.AreEqual("4teste", t.ToString());
try
{
t.Append((ICharSequence) t2, 1, 5);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException iobe)
{
}
try
{
t.Append((ICharSequence) t2, 1, 0);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException iobe)
{
}
t.Append((ICharSequence) null);
Assert.AreEqual("4testenull", t.ToString());*/
}
[Test]
public virtual void TestAppendableInterfaceWithLongSequences()
{
/*CharTermAttribute t = new CharTermAttribute();
t.Append(new StringCharSequenceWrapper("01234567890123456789012345678901234567890123456789"));
t.Append((ICharSequence) CharBuffer.wrap("01234567890123456789012345678901234567890123456789".ToCharArray()), 3, 50);
Assert.AreEqual("0123456789012345678901234567890123456789012345678934567890123456789012345678901234567890123456789", t.ToString());
t.SetEmpty().Append((ICharSequence) new StringBuilder("01234567890123456789"), 5, 17);
Assert.AreEqual(new StringCharSequenceWrapper("567890123456"), t.ToString());
t.Append(new StringBuilder(t));
Assert.AreEqual(new StringCharSequenceWrapper("567890123456567890123456"), t.ToString());
// very wierd, to test if a subSlice is wrapped correct :)
CharBuffer buf = CharBuffer.wrap("012345678901234567890123456789".ToCharArray(), 3, 15);
Assert.AreEqual("345678901234567", buf.ToString());
t.SetEmpty().Append(buf, 1, 14);
Assert.AreEqual("4567890123456", t.ToString());
// finally use a completely custom ICharSequence that is not catched by instanceof checks
const string longTestString = "012345678901234567890123456789";
t.Append(new CharSequenceAnonymousInnerClassHelper(this, longTestString));
Assert.AreEqual("4567890123456" + longTestString, t.ToString());*/
}
private class CharSequenceAnonymousInnerClassHelper : ICharSequence
{
private readonly TestCharTermAttributeImpl OuterInstance;
private string LongTestString;
public CharSequenceAnonymousInnerClassHelper(TestCharTermAttributeImpl outerInstance, string longTestString)
{
this.OuterInstance = outerInstance;
this.LongTestString = longTestString;
}
public char CharAt(int i)
{
return LongTestString[i];
}
public int Length
{
get
{
return LongTestString.Length;
}
}
public ICharSequence SubSequence(int start, int end)
{
return new StringCharSequenceWrapper(LongTestString.Substring(start, end));
}
public override string ToString()
{
return LongTestString;
}
}
[Test]
public virtual void TestNonCharSequenceAppend()
{
CharTermAttribute t = new CharTermAttribute();
t.Append("0123456789");
t.Append("0123456789");
Assert.AreEqual("01234567890123456789", t.ToString());
t.Append(new StringBuilder("0123456789"));
Assert.AreEqual("012345678901234567890123456789", t.ToString());
ICharTermAttribute t2 = new CharTermAttribute();
t2.Append("test");
t.Append(t2);
Assert.AreEqual("012345678901234567890123456789test", t.ToString());
t.Append((string)null);
t.Append((StringBuilder)null);
t.Append((ICharTermAttribute)null);
Assert.AreEqual("012345678901234567890123456789testnullnullnull", t.ToString());
}
[Test]
public virtual void TestExceptions()
{
CharTermAttribute t = new CharTermAttribute();
t.Append("test");
Assert.AreEqual("test", t.ToString());
try
{
t.CharAt(-1);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException)
{
}
try
{
t.CharAt(4);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException)
{
}
try
{
t.SubSequence(0, 5);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException)
{
}
try
{
t.SubSequence(5, 0);
Assert.Fail("Should throw IndexOutOfBoundsException");
}
catch (System.IndexOutOfRangeException)
{
}
}
/*
// test speed of the dynamic instanceof checks in append(ICharSequence),
// to find the best max length for the generic while (start<end) loop:
public void testAppendPerf() {
CharTermAttributeImpl t = new CharTermAttributeImpl();
final int count = 32;
ICharSequence[] csq = new ICharSequence[count * 6];
final StringBuilder sb = new StringBuilder();
for (int i=0,j=0; i<count; i++) {
sb.append(i%10);
final String testString = sb.toString();
CharTermAttribute cta = new CharTermAttributeImpl();
cta.append(testString);
csq[j++] = cta;
csq[j++] = testString;
csq[j++] = new StringBuilder(sb);
csq[j++] = new StringBuffer(sb);
csq[j++] = CharBuffer.wrap(testString.toCharArray());
csq[j++] = new ICharSequence() {
public char charAt(int i) { return testString.charAt(i); }
public int length() { return testString.length(); }
public ICharSequence subSequence(int start, int end) { return testString.subSequence(start, end); }
public String toString() { return testString; }
};
}
Random rnd = newRandom();
long startTime = System.currentTimeMillis();
for (int i=0; i<100000000; i++) {
t.SetEmpty().append(csq[rnd.nextInt(csq.length)]);
}
long endTime = System.currentTimeMillis();
System.out.println("Time: " + (endTime-startTime)/1000.0 + " s");
}
*/
}
}
| |
//
// ChainedStream.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
namespace MimeKit.IO {
/// <summary>
/// A chained stream.
/// </summary>
/// <remarks>
/// Chains multiple streams together such that reading or writing beyond the end
/// of one stream spills over into the next stream in the chain. The idea is to
/// make it appear is if the chain of streams is all one continuous stream.
/// </remarks>
public class ChainedStream : Stream
{
readonly List<Stream> streams;
readonly List<bool> leaveOpen;
long position;
bool disposed;
int current;
bool eos;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.IO.ChainedStream"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="ChainedStream"/>.
/// </remarks>
public ChainedStream ()
{
leaveOpen = new List<bool> ();
streams = new List<Stream> ();
}
/// <summary>
/// Add the specified stream to the chained stream.
/// </summary>
/// <remarks>
/// Adds the stream to the end of the chain.
/// </remarks>
/// <param name="stream">The stream.</param>
/// <param name="leaveOpen"><c>true</c> if the <paramref name="stream"/>
/// should remain open after the <see cref="ChainedStream"/> is disposed;
/// otherwise, <c>false</c>.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
public void Add (Stream stream, bool leaveOpen = false)
{
if (stream == null)
throw new ArgumentNullException ("stream");
this.leaveOpen.Add (leaveOpen);
streams.Add (stream);
eos = false;
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException ("ChainedStream");
}
void CheckCanSeek ()
{
if (!CanSeek)
throw new NotSupportedException ("The stream does not support seeking");
}
void CheckCanRead ()
{
if (!CanRead)
throw new NotSupportedException ("The stream does not support reading");
}
void CheckCanWrite ()
{
if (!CanWrite)
throw new NotSupportedException ("The stream does not support writing");
}
/// <summary>
/// Checks whether or not the stream supports reading.
/// </summary>
/// <remarks>
/// The <see cref="ChainedStream"/> only supports reading if all of its
/// streams support it.
/// </remarks>
/// <value><c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value>
public override bool CanRead {
get {
foreach (var stream in streams) {
if (!stream.CanRead)
return false;
}
return streams.Count > 0;
}
}
/// <summary>
/// Checks whether or not the stream supports writing.
/// </summary>
/// <remarks>
/// The <see cref="ChainedStream"/> only supports writing if all of its
/// streams support it.
/// </remarks>
/// <value><c>true</c> if the stream supports writing; otherwise, <c>false</c>.</value>
public override bool CanWrite {
get {
foreach (var stream in streams) {
if (!stream.CanWrite)
return false;
}
return streams.Count > 0;
}
}
/// <summary>
/// Checks whether or not the stream supports seeking.
/// </summary>
/// <remarks>
/// The <see cref="ChainedStream"/> only supports seeking if all of its
/// streams support it.
/// </remarks>
/// <value><c>true</c> if the stream supports seeking; otherwise, <c>false</c>.</value>
public override bool CanSeek {
get {
foreach (var stream in streams) {
if (!stream.CanSeek)
return false;
}
return streams.Count > 0;
}
}
/// <summary>
/// Checks whether or not I/O operations can timeout.
/// </summary>
/// <remarks>
/// The <see cref="ChainedStream"/> only supports timeouts if all of its
/// streams support them.
/// </remarks>
/// <value><c>true</c> if I/O operations can timeout; otherwise, <c>false</c>.</value>
public override bool CanTimeout {
get { return false; }
}
/// <summary>
/// Gets the length of the stream, in bytes.
/// </summary>
/// <remarks>
/// The length of a <see cref="ChainedStream"/> is the combined lenths of all
/// of its chained streams.
/// </remarks>
/// <value>The length of the stream in bytes.</value>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Length {
get {
long length = 0;
CheckDisposed ();
foreach (var stream in streams)
length += stream.Length;
return length;
}
}
/// <summary>
/// Gets or sets the current position within the stream.
/// </summary>
/// <remarks>
/// It is always possible to get the position of a <see cref="ChainedStream"/>,
/// but setting the position is only possible if all of its streams are seekable.
/// </remarks>
/// <value>The position of the stream.</value>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Position {
get { return position; }
set { Seek (value, SeekOrigin.Begin); }
}
static void ValidateArguments (byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0 || count > (buffer.Length - offset))
throw new ArgumentOutOfRangeException ("count");
}
/// <summary>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <remarks>
/// Reads up to the requested number of bytes if reading is supported. If the
/// current child stream does not have enough remaining data to complete the
/// read, the read will progress into the next stream in the chain in order
/// to complete the read.
/// </remarks>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
/// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset into the buffer to start reading data.</param>
/// <param name="count">The number of bytes to read.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes starting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support reading.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override int Read (byte[] buffer, int offset, int count)
{
CheckDisposed ();
CheckCanRead ();
ValidateArguments (buffer, offset, count);
if (count == 0 || eos)
return 0;
int n, nread = 0;
while (current < streams.Count) {
while (nread < count && (n = streams[current].Read (buffer, offset + nread, count - nread)) > 0)
nread += n;
if (nread == count)
break;
current++;
}
if (nread > 0)
position += nread;
else
eos = true;
return nread;
}
/// <summary>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <remarks>
/// Writes the requested number of bytes if writing is supported. If the
/// current child stream does not have enough remaining space to fit the
/// complete buffer, the data will spill over into the next stream in the
/// chain in order to complete the write.
/// </remarks>
/// <param name="buffer">The buffer to write.</param>
/// <param name="offset">The offset of the first byte to write.</param>
/// <param name="count">The number of bytes to write.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes starting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void Write (byte[] buffer, int offset, int count)
{
CheckDisposed ();
CheckCanWrite ();
ValidateArguments (buffer, offset, count);
if (current >= streams.Count)
current = streams.Count - 1;
int nwritten = 0;
while (current < streams.Count && nwritten < count) {
int n = count - nwritten;
if (current + 1 < streams.Count) {
long left = streams[current].Length - streams[current].Position;
if (left < n)
n = (int) left;
}
streams[current].Write (buffer, offset + nwritten, n);
position += n;
nwritten += n;
if (nwritten < count) {
streams[current].Flush ();
current++;
}
}
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <remarks>
/// Seeks to the specified position within the stream if all child streams
/// support seeking.
/// </remarks>
/// <returns>The new position within the stream.</returns>
/// <param name="offset">The offset into the stream relative to the <paramref name="origin"/>.</param>
/// <param name="origin">The origin to seek from.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="origin"/> is not a valid <see cref="System.IO.SeekOrigin"/>.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override long Seek (long offset, SeekOrigin origin)
{
CheckDisposed ();
CheckCanSeek ();
long length = -1;
long real;
switch (origin) {
case SeekOrigin.Begin:
real = offset;
break;
case SeekOrigin.Current:
real = position + offset;
break;
case SeekOrigin.End:
length = Length;
real = length + offset;
break;
default:
throw new ArgumentOutOfRangeException ("origin", "Invalid SeekOrigin specified");
}
// sanity check the resultant offset
if (real < 0)
throw new IOException ("Cannot seek to a position before the beginning of the stream");
// short-cut if we are seeking to our current position
if (real == position)
return position;
if (real > (length < 0 ? Length : length))
throw new IOException ("Cannot seek beyond the end of the stream");
if (real > position) {
while (current < streams.Count && position < real) {
long left = streams[current].Length - streams[current].Position;
long n = Math.Min (left, real - position);
streams[current].Seek (n, SeekOrigin.Current);
position += n;
if (position < real)
current++;
}
eos = current >= streams.Count;
} else {
int max = Math.Min (streams.Count - 1, current);
int cur = 0;
position = 0;
while (cur <= max) {
length = streams[cur].Length;
if (real < position + length) {
// this is the stream which encompasses our seek offset
streams[cur].Seek (real - position, SeekOrigin.Begin);
position = real;
break;
}
position += length;
cur++;
}
current = cur++;
// reset any streams between our new current stream and our old current stream
while (cur <= max)
streams[cur++].Seek (0, SeekOrigin.Begin);
eos = false;
}
return position;
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </summary>
/// <remarks>
/// If all of the child streams support writing, then the current child stream
/// will be flushed.
/// </remarks>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void Flush ()
{
CheckDisposed ();
CheckCanWrite ();
if (current < streams.Count)
streams[current].Flush ();
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <remarks>
/// Setting the length of a <see cref="ChainedStream"/> is not supported.
/// </remarks>
/// <param name="value">The desired length of the stream in bytes.</param>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support setting the length.
/// </exception>
public override void SetLength (long value)
{
CheckDisposed ();
throw new NotSupportedException ("Cannot set a length on the stream");
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="ChainedStream"/> and
/// optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only the unmanaged resources.</param>
protected override void Dispose (bool disposing)
{
if (disposing && !disposed) {
for (int i = 0; i < streams.Count; i++) {
if (!leaveOpen[i])
streams[i].Dispose ();
}
}
base.Dispose (disposing);
disposed = true;
}
}
}
| |
using System;
/// <summary>
/// ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)
/// </summary>
public class DateTimeCtor6
{
#region Private Fields
private int m_ErrorNo = 0;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor to constructor a new DateTime instance by using valid value");
try
{
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56, 900);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor to constructor a new DateTime instance by using MAX/MIN values");
try
{
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59, 0);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor to constructor a new DateTime instance by using correct day/month pair");
try
{
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, 100);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999.");
try
{
m_ErrorNo++;
DateTime value = new DateTime(0, 1, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(10000, 1, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 0, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 13, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 0, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 32, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 2, 29, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 4, 31, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException should be thrown when hour is less than 0 or greater than 23");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, -1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 24, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is greater than 23");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException should be thrown when minute is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, -1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown minute year is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 60, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when minute is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException should be thrown when second is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, -1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 60, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentOutOfRangeException should be thrown when millisecond is less than 0 or greater than 999");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, -1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when millisecond is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, 1000);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when millisecond is greater than 999");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
#endregion
public static int Main()
{
DateTimeCtor6 test = new DateTimeCtor6();
TestLibrary.TestFramework.BeginTestCase("DateTimeCtor6");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerifyDateTimeHelper(int desiredYear,
int desiredMonth,
int desiredDay,
int desiredHour,
int desiredMinute,
int desiredSecond,
int desiredMillisecond)
{
bool retVal = true;
DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay,
desiredHour, desiredMinute, desiredSecond, desiredMillisecond);
m_ErrorNo++;
if ((desiredYear != value.Year) ||
(desiredMonth != value.Month) ||
(desiredDay != value.Day) ||
(desiredHour != value.Hour) ||
(desiredMinute != value.Minute) ||
(desiredSecond != value.Second) ||
(desiredMillisecond != value.Millisecond) )
{
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Calling ctor constructors a wrong DateTime instance by using valid value");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() +
", desiredMonth = " + desiredMonth.ToString() +
", desiredDay = " + desiredDay.ToString() +
", desiredHour = " + desiredHour.ToString() +
", desiredMinute = " + desiredMinute.ToString() +
", desiredSecond = " + desiredSecond.ToString() +
", desiredMillisecond = " + desiredMillisecond.ToString() +
", actualYear = " + value.Year.ToString() +
", actualMonth = " + value.Month.ToString() +
", actualDay = " + value.Day.ToString() +
", actualHour = " + value.Hour.ToString() +
", actualMinute = " + value.Minute.ToString() +
", actualSecond = " + value.Second.ToString() +
", actualMillisecond = " + value.Millisecond.ToString());
retVal = false;
}
m_ErrorNo++;
if (value.Kind != DateTimeKind.Unspecified)
{
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Calling ctor constructors a wrong DateTime instance by using valid value");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredKind = DateTimeKind.Unspecified" + ", actualKind = " + value.Kind.ToString());
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Rest.Generator.Azure.NodeJS.Templates
{
#line 1 "AzureServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.NodeJS
#line default
#line hidden
;
#line 2 "AzureServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Azure.NodeJS
#line default
#line hidden
;
#line 3 "AzureServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.NodeJS.Templates
#line default
#line hidden
;
#line 4 "AzureServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Azure.NodeJS.Templates
#line default
#line hidden
;
#line 5 "AzureServiceClientTemplate.cshtml"
using Microsoft.Rest.Generator.Utilities
#line default
#line hidden
;
#line 6 "AzureServiceClientTemplate.cshtml"
using System.Linq
#line default
#line hidden
;
using System.Threading.Tasks;
public class AzureServiceClientTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.Azure.NodeJS.AzureServiceClientTemplateModel>
{
#line hidden
public AzureServiceClientTemplate()
{
}
#pragma warning disable 1998
public override async Task ExecuteAsync()
{
#line 8 "AzureServiceClientTemplate.cshtml"
Write(Header("/// "));
#line default
#line hidden
WriteLiteral("\r\n/* jshint latedef:false */\r\n/* jshint forin:false */\r\n/* jshint noempty:false *" +
"/\r\n");
#line 12 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n\'use strict\';\r\n");
#line 14 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\nvar util = require(\'util\');\r\nvar msRest = require(\'ms-rest\');\r\nvar msRestAzure " +
"= require(\'ms-rest-azure\');\r\nvar ServiceClient = msRestAzure.AzureServiceClient;" +
"\r\nvar WebResource = msRest.WebResource;\r\n\r\n");
#line 21 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n");
#line 22 "AzureServiceClientTemplate.cshtml"
if (Model.ModelTypes.Any())
{
#line default
#line hidden
WriteLiteral("var models = require(\'./models\');\r\n");
#line 25 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
#line 26 "AzureServiceClientTemplate.cshtml"
if (Model.MethodGroups.Any())
{
#line default
#line hidden
WriteLiteral("var operations = require(\'./operations\');\r\n");
#line 29 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
#line 30 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n");
#line 31 "AzureServiceClientTemplate.cshtml"
var parameters = Model.Properties.Where(p => p.IsRequired);
#line default
#line hidden
WriteLiteral("\r\n/**\r\n * @class\r\n * Initializes a new instance of the ");
#line 34 "AzureServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral(" class.\r\n * @constructor\r\n *\r\n");
#line 37 "AzureServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
WriteLiteral(" * @param {");
#line 39 "AzureServiceClientTemplate.cshtml"
Write(param.Type.Name);
#line default
#line hidden
WriteLiteral("} [");
#line 39 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral("] ");
#line 39 "AzureServiceClientTemplate.cshtml"
Write(param.Documentation);
#line default
#line hidden
WriteLiteral("\r\n *\r\n");
#line 41 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(@" * @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*
* @param {bool} [options.noRetryPolicy] - If set to true, turn off default retry policy
*/
function ");
#line 53 "AzureServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral("(");
#line 53 "AzureServiceClientTemplate.cshtml"
Write(Model.RequiredConstructorParameters);
#line default
#line hidden
WriteLiteral(", options) {\r\n");
#line 54 "AzureServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
WriteLiteral(" if (");
#line 56 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(" === null || ");
#line 56 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(" === undefined) {\r\n throw new Error(\'\\\'");
#line 57 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral("\\\' cannot be null.\');\r\n }\r\n");
#line 59 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 60 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n if (!options) options = {};\r\n ");
#line 62 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n ");
#line 63 "AzureServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral("[\'super_\'].call(this, ");
#line 63 "AzureServiceClientTemplate.cshtml"
Write(parameters.Any(p => p.Name == "credentials") ? "credentials" : "null");
#line default
#line hidden
WriteLiteral(", options);\r\n this.baseUri = baseUri;\r\n if (!this.baseUri) {\r\n this.baseUri " +
"= \'");
#line 66 "AzureServiceClientTemplate.cshtml"
Write(Model.BaseUrl);
#line default
#line hidden
WriteLiteral("\';\r\n }\r\n");
#line 68 "AzureServiceClientTemplate.cshtml"
foreach (var param in parameters)
{
#line default
#line hidden
WriteLiteral(" this.");
#line 70 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(" = ");
#line 70 "AzureServiceClientTemplate.cshtml"
Write(param.Name);
#line default
#line hidden
WriteLiteral(";\r\n");
#line 71 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 72 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n");
#line 73 "AzureServiceClientTemplate.cshtml"
#line default
#line hidden
#line 73 "AzureServiceClientTemplate.cshtml"
foreach (var property in Model.Properties.Where(p => p.DefaultValue != null))
{
#line default
#line hidden
WriteLiteral(" if(!this.");
#line 75 "AzureServiceClientTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral(") {\r\n this.");
#line 76 "AzureServiceClientTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral(" = ");
#line 76 "AzureServiceClientTemplate.cshtml"
Write(property.DefaultValue);
#line default
#line hidden
WriteLiteral(";\r\n }\r\n");
#line 78 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" \r\n");
#line 80 "AzureServiceClientTemplate.cshtml"
#line default
#line hidden
#line 80 "AzureServiceClientTemplate.cshtml"
foreach (var methodGroup in Model.MethodGroupModels)
{
#line default
#line hidden
WriteLiteral(" this.");
#line 82 "AzureServiceClientTemplate.cshtml"
Write(methodGroup.MethodGroupName);
#line default
#line hidden
WriteLiteral(" = new operations.");
#line 82 "AzureServiceClientTemplate.cshtml"
Write(methodGroup.MethodGroupType);
#line default
#line hidden
WriteLiteral("(this);\r\n");
#line 83 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" \r\n");
#line 85 "AzureServiceClientTemplate.cshtml"
#line default
#line hidden
#line 85 "AzureServiceClientTemplate.cshtml"
if (Model.ModelTypes.Any())
{
#line default
#line hidden
WriteLiteral(" this._models = models;\r\n");
#line 88 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral("}\r\n\r\n");
#line 91 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\nutil.inherits(");
#line 92 "AzureServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral(", ServiceClient);\r\n");
#line 93 "AzureServiceClientTemplate.cshtml"
foreach (var method in Model.MethodTemplateModels)
{
#line default
#line hidden
#line 95 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
#line 95 "AzureServiceClientTemplate.cshtml"
#line default
#line hidden
#line 96 "AzureServiceClientTemplate.cshtml"
Write(Include(new AzureMethodTemplate(), method as AzureMethodTemplateModel));
#line default
#line hidden
WriteLiteral("\r\n");
#line 97 "AzureServiceClientTemplate.cshtml"
}
#line default
#line hidden
#line 98 "AzureServiceClientTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\nmodule.exports = ");
#line 99 "AzureServiceClientTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
WriteLiteral(";");
}
#pragma warning restore 1998
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.Reflection;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class JsonDataContract
{
[SecurityCritical]
private JsonDataContractCriticalHelper _helper;
[SecuritySafeCritical]
protected JsonDataContract(DataContract traditionalDataContract)
{
_helper = new JsonDataContractCriticalHelper(traditionalDataContract);
}
[SecuritySafeCritical]
protected JsonDataContract(JsonDataContractCriticalHelper helper)
{
_helper = helper;
}
internal virtual string TypeName
{
get { return null; }
}
protected JsonDataContractCriticalHelper Helper
{
[SecurityCritical]
get
{ return _helper; }
}
protected DataContract TraditionalDataContract
{
[SecuritySafeCritical]
get
{ return _helper.TraditionalDataContract; }
}
private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
}
public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c)
{
// this method used to be rewritten by an IL transform
// with the restructuring for multi-file, this is no longer true - instead
// this has become a normal method
JsonReadWriteDelegates result;
#if NET_NATIVE
// The c passed in could be a clone which is different from the original key,
// We'll need to get the original key data contract from generated assembly.
DataContract keyDc = DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType);
return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result) ? result : null;
#else
return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null;
#endif
}
internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
{
JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
if (result == null)
{
throw new InvalidDataContractException(string.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString()));
}
else
{
return result;
}
}
[SecuritySafeCritical]
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
}
public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
PushKnownDataContracts(context);
object deserializedObject = ReadJsonValueCore(jsonReader, context);
PopKnownDataContracts(context);
return deserializedObject;
}
public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
return TraditionalDataContract.ReadXmlValue(jsonReader, context);
}
public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
PushKnownDataContracts(context);
WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
PopKnownDataContracts(context);
}
public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
}
protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
while (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString))
{
reader.Skip();
reader.MoveToElement();
return true;
}
reader.MoveToElement();
return false;
}
protected void PopKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Pop();
}
}
protected void PushKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Push(KnownDataContracts);
}
}
internal class JsonDataContractCriticalHelper
{
private static object s_cacheLock = new object();
private static object s_createDataContractLock = new object();
private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32];
private static int s_dataContractID = 0;
private static TypeHandleRef s_typeHandleRef = new TypeHandleRef();
private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts;
private DataContract _traditionalDataContract;
private string _typeName;
internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
{
_traditionalDataContract = traditionalDataContract;
AddCollectionItemContractsToKnownDataContracts();
_typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
}
internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
get { return _knownDataContracts; }
}
internal DataContract TraditionalDataContract
{
get { return _traditionalDataContract; }
}
internal virtual string TypeName
{
get { return _typeName; }
}
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle);
JsonDataContract dataContract = s_dataContractCache[id];
if (dataContract == null)
{
dataContract = CreateJsonDataContract(id, traditionalDataContract);
s_dataContractCache[id] = dataContract;
}
return dataContract;
}
internal static int GetId(RuntimeTypeHandle typeHandle)
{
lock (s_cacheLock)
{
IntRef id;
s_typeHandleRef.Value = typeHandle;
if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id))
{
int value = s_dataContractID++;
if (value >= s_dataContractCache.Length)
{
int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
if (newSize <= value)
{
Fx.Assert("DataContract cache overflow");
throw new SerializationException(SR.DataContractCacheOverflow);
}
Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize);
}
id = new IntRef(value);
try
{
s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
}
}
return id.Value;
}
}
private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
{
lock (s_createDataContractLock)
{
JsonDataContract dataContract = s_dataContractCache[id];
if (dataContract == null)
{
Type traditionalDataContractType = traditionalDataContract.GetType();
if (traditionalDataContractType == typeof(ObjectDataContract))
{
dataContract = new JsonObjectDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(StringDataContract))
{
dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(UriDataContract))
{
dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(QNameDataContract))
{
dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ByteArrayDataContract))
{
dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
}
else if (traditionalDataContract.IsPrimitive ||
traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ClassDataContract))
{
dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(EnumDataContract))
{
dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
}
else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
(traditionalDataContractType == typeof(SpecialTypeDataContract)))
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(CollectionDataContract))
{
dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(XmlDataContract))
{
dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
}
else
{
throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), "traditionalDataContract");
}
}
return dataContract;
}
}
private void AddCollectionItemContractsToKnownDataContracts()
{
if (_traditionalDataContract.KnownDataContracts != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts)
{
if (!object.ReferenceEquals(knownDataContract, null))
{
CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
if (_knownDataContracts == null)
{
_knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
}
if (!_knownDataContracts.ContainsKey(itemContract.StableName))
{
_knownDataContracts.Add(itemContract.StableName, itemContract);
}
if (collectionDataContract.ItemType.GetTypeInfo().IsGenericType
&& collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetTypeInfo().GenericTypeArguments));
if (!_knownDataContracts.ContainsKey(itemDataContract.StableName))
{
_knownDataContracts.Add(itemDataContract.StableName, itemDataContract);
}
}
if (!(itemContract is CollectionDataContract))
{
break;
}
collectionDataContract = itemContract as CollectionDataContract;
}
}
}
}
}
}
}
#if NET_NATIVE
public class JsonReadWriteDelegates
#else
internal class JsonReadWriteDelegates
#endif
{
// this is the global dictionary for JSON delegates introduced for multi-file
private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>();
public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates()
{
return s_jsonDelegates;
}
public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; }
public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; }
public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; }
public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; }
public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; }
}
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceLineItem (editable child object).<br/>
/// This is a generated base class of <see cref="InvoiceLineItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="InvoiceLineCollection"/> collection.
/// </remarks>
[Serializable]
public partial class InvoiceLineItem : BusinessBase<InvoiceLineItem>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceLineId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> InvoiceLineIdProperty = RegisterProperty<Guid>(p => p.InvoiceLineId, "Invoice Line Id");
/// <summary>
/// Gets or sets the Invoice Line Id.
/// </summary>
/// <value>The Invoice Line Id.</value>
public Guid InvoiceLineId
{
get { return GetProperty(InvoiceLineIdProperty); }
set { SetProperty(InvoiceLineIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductId"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id");
/// <summary>
/// Gets or sets the Product Id.
/// </summary>
/// <value>The Product Id.</value>
public Guid ProductId
{
get { return GetProperty(ProductIdProperty); }
set { SetProperty(ProductIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Cost"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> CostProperty = RegisterProperty<decimal>(p => p.Cost, "Cost");
/// <summary>
/// Gets or sets the Cost.
/// </summary>
/// <value>The Cost.</value>
public decimal Cost
{
get { return GetProperty(CostProperty); }
set { SetProperty(CostProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="PercentDiscount"/> property.
/// </summary>
public static readonly PropertyInfo<byte> PercentDiscountProperty = RegisterProperty<byte>(p => p.PercentDiscount, "Percent Discount");
/// <summary>
/// Gets or sets the Percent Discount.
/// </summary>
/// <value>The Percent Discount.</value>
public byte PercentDiscount
{
get { return GetProperty(PercentDiscountProperty); }
set { SetProperty(PercentDiscountProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceLineItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceLineItem()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="InvoiceLineItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(InvoiceLineIdProperty, Guid.NewGuid());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="InvoiceLineItem"/> object from the given <see cref="InvoiceLineItemDto"/>.
/// </summary>
/// <param name="data">The InvoiceLineItemDto to use.</param>
private void Child_Fetch(InvoiceLineItemDto data)
{
// Value properties
LoadProperty(InvoiceLineIdProperty, data.InvoiceLineId);
LoadProperty(ProductIdProperty, data.ProductId);
LoadProperty(CostProperty, data.Cost);
LoadProperty(PercentDiscountProperty, data.PercentDiscount);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="InvoiceLineItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(InvoiceEdit parent)
{
var dto = new InvoiceLineItemDto();
dto.Parent_InvoiceId = parent.InvoiceId;
dto.InvoiceLineId = InvoiceLineId;
dto.ProductId = ProductId;
dto.Cost = Cost;
dto.PercentDiscount = PercentDiscount;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="InvoiceLineItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new InvoiceLineItemDto();
dto.InvoiceLineId = InvoiceLineId;
dto.ProductId = ProductId;
dto.Cost = Cost;
dto.PercentDiscount = PercentDiscount;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="InvoiceLineItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(InvoiceLineIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Thrift.Transport
{
// ReSharper disable once InconsistentNaming
public class TBufferedTransport : TLayeredTransport
{
private readonly int DesiredBufferSize;
private readonly Client.TMemoryBufferTransport ReadBuffer;
private readonly Client.TMemoryBufferTransport WriteBuffer;
private bool IsDisposed;
public class Factory : TTransportFactory
{
public override TTransport GetTransport(TTransport trans)
{
return new TBufferedTransport(trans);
}
}
//TODO: should support only specified input transport?
public TBufferedTransport(TTransport transport, int bufSize = 1024)
: base(transport)
{
if (bufSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufSize), "Buffer size must be a positive number.");
}
DesiredBufferSize = bufSize;
WriteBuffer = new Client.TMemoryBufferTransport(InnerTransport.Configuration, bufSize);
ReadBuffer = new Client.TMemoryBufferTransport(InnerTransport.Configuration, bufSize);
Debug.Assert(DesiredBufferSize == ReadBuffer.Capacity);
Debug.Assert(DesiredBufferSize == WriteBuffer.Capacity);
}
public TTransport UnderlyingTransport
{
get
{
CheckNotDisposed();
return InnerTransport;
}
}
public override bool IsOpen => !IsDisposed && InnerTransport.IsOpen;
public override async Task OpenAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
await InnerTransport.OpenAsync(cancellationToken);
}
public override void Close()
{
CheckNotDisposed();
InnerTransport.Close();
}
public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// do we have something buffered?
var count = ReadBuffer.Length - ReadBuffer.Position;
if (count > 0)
{
return await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken);
}
// does the request even fit into the buffer?
// Note we test for >= instead of > to avoid nonsense buffering
if (length >= ReadBuffer.Capacity)
{
return await InnerTransport.ReadAsync(buffer, offset, length, cancellationToken);
}
// buffer a new chunk of bytes from the underlying transport
ReadBuffer.Length = ReadBuffer.Capacity;
ArraySegment<byte> bufSegment;
ReadBuffer.TryGetBuffer(out bufSegment);
ReadBuffer.Length = await InnerTransport.ReadAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
ReadBuffer.Position = 0;
// deliver the bytes
return await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
CheckNotDisposed();
ValidateBufferArgs(buffer, offset, length);
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// enough space left in buffer?
var free = WriteBuffer.Capacity - WriteBuffer.Length;
if (length > free)
{
ArraySegment<byte> bufSegment;
WriteBuffer.TryGetBuffer(out bufSegment);
await InnerTransport.WriteAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
WriteBuffer.SetLength(0);
}
// do the data even fit into the buffer?
// Note we test for < instead of <= to avoid nonsense buffering
if (length < WriteBuffer.Capacity)
{
await WriteBuffer.WriteAsync(buffer, offset, length, cancellationToken);
return;
}
// write thru
await InnerTransport.WriteAsync(buffer, offset, length, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
CheckNotDisposed();
if (!IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
if (WriteBuffer.Length > 0)
{
ArraySegment<byte> bufSegment;
WriteBuffer.TryGetBuffer(out bufSegment);
await InnerTransport.WriteAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);
WriteBuffer.SetLength(0);
}
await InnerTransport.FlushAsync(cancellationToken);
}
public override void CheckReadBytesAvailable(long numBytes)
{
var buffered = ReadBuffer.Length - ReadBuffer.Position;
if (buffered < numBytes)
{
numBytes -= buffered;
InnerTransport.CheckReadBytesAvailable(numBytes);
}
}
private void CheckNotDisposed()
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(InnerTransport));
}
}
// IDisposable
protected override void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
ReadBuffer?.Dispose();
WriteBuffer?.Dispose();
InnerTransport?.Dispose();
}
}
IsDisposed = true;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// X509Certificate.cs
//
namespace System.Security.Cryptography.X509Certificates {
using Microsoft.Win32;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Util;
using System.Text;
using System.Runtime.Versioning;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public enum X509ContentType {
Unknown = 0x00,
Cert = 0x01,
SerializedCert = 0x02,
#if !FEATURE_PAL
Pfx = 0x03,
Pkcs12 = Pfx,
#endif // !FEATURE_PAL
SerializedStore = 0x04,
Pkcs7 = 0x05,
Authenticode = 0x06
}
// DefaultKeySet, UserKeySet and MachineKeySet are mutually exclusive
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum X509KeyStorageFlags {
DefaultKeySet = 0x00,
UserKeySet = 0x01,
MachineKeySet = 0x02,
Exportable = 0x04,
UserProtected = 0x08,
PersistKeySet = 0x10
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class X509Certificate :
IDisposable,
IDeserializationCallback,
ISerializable {
private const string m_format = "X509";
private string m_subjectName;
private string m_issuerName;
private byte[] m_serialNumber;
private byte[] m_publicKeyParameters;
private byte[] m_publicKeyValue;
private string m_publicKeyOid;
private byte[] m_rawData;
private byte[] m_thumbprint;
private DateTime m_notBefore;
private DateTime m_notAfter;
[System.Security.SecurityCritical] // auto-generated
private SafeCertContextHandle m_safeCertContext;
private bool m_certContextCloned = false;
//
// public constructors
//
[System.Security.SecuritySafeCritical] // auto-generated
private void Init()
{
m_safeCertContext = SafeCertContextHandle.InvalidHandle;
}
public X509Certificate ()
{
Init();
}
public X509Certificate (byte[] data):this() {
if ((data != null) && (data.Length != 0))
LoadCertificateFromBlob(data, null, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate (byte[] rawData, string password):this() {
#if FEATURE_LEGACYNETCF
if ((rawData != null) && (rawData.Length != 0)) {
#endif
LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet);
#if FEATURE_LEGACYNETCF
}
#endif
}
#if FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, SecureString password):this() {
LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet);
}
#endif // FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags):this() {
#if FEATURE_LEGACYNETCF
if ((rawData != null) && (rawData.Length != 0)) {
#endif
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
#if FEATURE_LEGACYNETCF
}
#endif
}
#if FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public X509Certificate (string fileName):this() {
LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public X509Certificate (string fileName, string password):this() {
LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public X509Certificate (string fileName, SecureString password):this() {
LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
#endif // FEATURE_X509_SECURESTRINGS
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public X509Certificate (string fileName, string password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
// Package protected constructor for creating a certificate from a PCCERT_CONTEXT
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
public X509Certificate (IntPtr handle):this() {
if (handle == IntPtr.Zero)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
Contract.EndContractBlock();
X509Utils._DuplicateCertContext(handle, ref m_safeCertContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
public X509Certificate (X509Certificate cert):this() {
if (cert == null)
throw new ArgumentNullException("cert");
Contract.EndContractBlock();
if (cert.m_safeCertContext.pCertContext != IntPtr.Zero) {
m_safeCertContext = cert.GetCertContextForCloning();
m_certContextCloned = true;
}
}
public X509Certificate (SerializationInfo info, StreamingContext context):this() {
byte[] rawData = (byte[]) info.GetValue("RawData", typeof(byte[]));
if (rawData != null)
LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static X509Certificate CreateFromCertFile (string filename) {
return new X509Certificate(filename);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static X509Certificate CreateFromSignedFile (string filename) {
return new X509Certificate(filename);
}
[System.Runtime.InteropServices.ComVisible(false)]
public IntPtr Handle {
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
get {
return m_safeCertContext.pCertContext;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetName() {
ThrowIfContextInvalid();
return X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetIssuerName() {
ThrowIfContextInvalid();
return X509Utils._GetIssuerName(m_safeCertContext, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetSerialNumber() {
ThrowIfContextInvalid();
if (m_serialNumber == null)
m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext);
return (byte[]) m_serialNumber.Clone();
}
public virtual string GetSerialNumberString() {
return SerialNumber;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetKeyAlgorithmParameters() {
ThrowIfContextInvalid();
if (m_publicKeyParameters == null)
m_publicKeyParameters = X509Utils._GetPublicKeyParameters(m_safeCertContext);
return (byte[]) m_publicKeyParameters.Clone();
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string GetKeyAlgorithmParametersString() {
ThrowIfContextInvalid();
return Hex.EncodeHexString(GetKeyAlgorithmParameters());
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string GetKeyAlgorithm() {
ThrowIfContextInvalid();
if (m_publicKeyOid == null)
m_publicKeyOid = X509Utils._GetPublicKeyOid(m_safeCertContext);
return m_publicKeyOid;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetPublicKey() {
ThrowIfContextInvalid();
if (m_publicKeyValue == null)
m_publicKeyValue = X509Utils._GetPublicKeyValue(m_safeCertContext);
return (byte[]) m_publicKeyValue.Clone();
}
public virtual string GetPublicKeyString() {
return Hex.EncodeHexString(GetPublicKey());
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetRawCertData() {
return RawData;
}
public virtual string GetRawCertDataString() {
return Hex.EncodeHexString(GetRawCertData());
}
public virtual byte[] GetCertHash() {
SetThumbprint();
return (byte[]) m_thumbprint.Clone();
}
public virtual string GetCertHashString() {
SetThumbprint();
return Hex.EncodeHexString(m_thumbprint);
}
public virtual string GetEffectiveDateString() {
return NotBefore.ToString();
}
public virtual string GetExpirationDateString() {
return NotAfter.ToString();
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals (Object obj) {
if (!(obj is X509Certificate)) return false;
X509Certificate other = (X509Certificate) obj;
return this.Equals(other);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual bool Equals (X509Certificate other) {
if (other == null)
return false;
if (m_safeCertContext.IsInvalid)
return other.m_safeCertContext.IsInvalid;
if (!this.Issuer.Equals(other.Issuer))
return false;
if (!this.SerialNumber.Equals(other.SerialNumber))
return false;
return true;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int GetHashCode() {
if (m_safeCertContext.IsInvalid)
return 0;
SetThumbprint();
int value = 0;
for (int i = 0; i < m_thumbprint.Length && i < 4; ++i) {
value = value << 8 | m_thumbprint[i];
}
return value;
}
public override string ToString() {
return ToString(false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string ToString (bool fVerbose) {
if (fVerbose == false || m_safeCertContext.IsInvalid)
return GetType().FullName;
StringBuilder sb = new StringBuilder();
// Subject
sb.Append("[Subject]" + Environment.NewLine + " ");
sb.Append(this.Subject);
// Issuer
sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + " ");
sb.Append(this.Issuer);
// Serial Number
sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + " ");
sb.Append(this.SerialNumber);
// NotBefore
sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + " ");
sb.Append(FormatDate(this.NotBefore));
// NotAfter
sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + " ");
sb.Append(FormatDate(this.NotAfter));
// Thumbprint
sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + " ");
sb.Append(this.GetCertHashString());
sb.Append(Environment.NewLine);
return sb.ToString();
}
/// <summary>
/// Convert a date to a string.
///
/// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into
/// the future into strings. If the expiration date of an X.509 certificate is beyond the range
/// of one of these these cases, we need to fall back to a calendar which can express the dates
/// </summary>
protected static string FormatDate(DateTime date) {
CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) {
// The most common case of culture failing to work is in the Um-AlQuara calendar. In this case,
// we can fall back to the Hijri calendar, otherwise fall back to the invariant culture.
if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) {
culture = culture.Clone() as CultureInfo;
culture.DateTimeFormat.Calendar = new HijriCalendar();
}
else
{
culture = CultureInfo.InvariantCulture;
}
}
return date.ToString(culture);
}
public virtual string GetFormat() {
return m_format;
}
public string Issuer {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_issuerName == null)
m_issuerName = X509Utils._GetIssuerName(m_safeCertContext, false);
return m_issuerName;
}
}
public string Subject {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_subjectName == null)
m_subjectName = X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, false);
return m_subjectName;
}
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
// auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(byte[] rawData) {
Reset();
LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
// auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(string fileName) {
Reset();
LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet);
}
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public virtual byte[] Export(X509ContentType contentType) {
return ExportHelper(contentType, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public virtual byte[] Export(X509ContentType contentType, string password) {
return ExportHelper(contentType, password);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] Export(X509ContentType contentType, SecureString password) {
return ExportHelper(contentType, password);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Reset () {
m_subjectName = null;
m_issuerName = null;
m_serialNumber = null;
m_publicKeyParameters = null;
m_publicKeyValue = null;
m_publicKeyOid = null;
m_rawData = null;
m_thumbprint = null;
m_notBefore = DateTime.MinValue;
m_notAfter = DateTime.MinValue;
if (!m_safeCertContext.IsInvalid) {
// Free the current certificate handle
if (!m_certContextCloned) {
m_safeCertContext.Dispose();
}
m_safeCertContext = SafeCertContextHandle.InvalidHandle;
}
m_certContextCloned = false;
}
public void Dispose() {
Dispose(true);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
if (disposing) {
Reset();
}
}
#if FEATURE_SERIALIZATION
/// <internalonly/>
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
if (m_safeCertContext.IsInvalid)
info.AddValue("RawData", null);
else
info.AddValue("RawData", this.RawData);
}
/// <internalonly/>
void IDeserializationCallback.OnDeserialization(Object sender) {}
#endif
//
// internal.
//
internal SafeCertContextHandle CertContext {
[System.Security.SecurityCritical] // auto-generated
get {
return m_safeCertContext;
}
}
/// <summary>
/// Returns the SafeCertContextHandle. Use this instead of the CertContext property when
/// creating another X509Certificate object based on this one to ensure the underlying
/// cert context is not released at the wrong time.
/// </summary>
[System.Security.SecurityCritical]
internal SafeCertContextHandle GetCertContextForCloning() {
m_certContextCloned = true;
return m_safeCertContext;
}
//
// private methods.
//
[System.Security.SecurityCritical] // auto-generated
private void ThrowIfContextInvalid() {
if (m_safeCertContext.IsInvalid)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHandle"), "m_safeCertContext");
}
private DateTime NotAfter {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_notAfter == DateTime.MinValue) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME();
X509Utils._GetDateNotAfter(m_safeCertContext, ref fileTime);
m_notAfter = DateTime.FromFileTime(fileTime.ToTicks());
}
return m_notAfter;
}
}
private DateTime NotBefore {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_notBefore == DateTime.MinValue) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME();
X509Utils._GetDateNotBefore(m_safeCertContext, ref fileTime);
m_notBefore = DateTime.FromFileTime(fileTime.ToTicks());
}
return m_notBefore;
}
}
private byte[] RawData {
[System.Security.SecurityCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_rawData == null)
m_rawData = X509Utils._GetCertRawData(m_safeCertContext);
return (byte[]) m_rawData.Clone();
}
}
private string SerialNumber {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_serialNumber == null)
m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext);
return Hex.EncodeHexStringFromInt(m_serialNumber);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
private void SetThumbprint () {
ThrowIfContextInvalid();
if (m_thumbprint == null)
m_thumbprint = X509Utils._GetThumbprint(m_safeCertContext);
}
[System.Security.SecurityCritical] // auto-generated
private byte[] ExportHelper (X509ContentType contentType, object password) {
switch(contentType) {
case X509ContentType.Cert:
break;
#if FEATURE_CORECLR
case (X509ContentType)0x02 /* X509ContentType.SerializedCert */:
case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */:
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"),
new NotSupportedException());
#else // FEATURE_CORECLR
case X509ContentType.SerializedCert:
break;
#if !FEATURE_PAL
case X509ContentType.Pkcs12:
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export);
kp.Demand();
break;
#endif // !FEATURE_PAL
#endif // FEATURE_CORECLR else
default:
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"));
}
#if !FEATURE_CORECLR
IntPtr szPassword = IntPtr.Zero;
byte[] encodedRawData = null;
SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this);
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
safeCertStoreHandle.Dispose();
}
if (encodedRawData == null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed"));
return encodedRawData;
#else // !FEATURE_CORECLR
return RawData;
#endif // !FEATURE_CORECLR
}
[System.Security.SecuritySafeCritical] // auto-generated
private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) {
if (rawData == null || rawData.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData");
Contract.EndContractBlock();
X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData));
#if !FEATURE_CORECLR && !FEATURE_PAL
if (contentType == X509ContentType.Pkcs12 &&
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
kp.Demand();
}
#endif // !FEATURE_CORECLR && !FEATURE_PAL
uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
IntPtr szPassword = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
X509Utils._LoadCertFromBlob(rawData,
szPassword,
dwFlags,
#if FEATURE_CORECLR
false,
#else // FEATURE_CORECLR
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
ref m_safeCertContext);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
}
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) {
if (fileName == null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
string fullPath = Path.GetFullPathInternal(fileName);
new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand();
X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName));
#if !FEATURE_CORECLR && !FEATURE_PAL
if (contentType == X509ContentType.Pkcs12 &&
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
kp.Demand();
}
#endif // !FEATURE_CORECLR && !FEATURE_PAL
uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
IntPtr szPassword = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
X509Utils._LoadCertFromFile(fileName,
szPassword,
dwFlags,
#if FEATURE_CORECLR
false,
#else // FEATURE_CORECLR
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
ref m_safeCertContext);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
}
}
#if FEATURE_LEGACYNETCF
protected internal String CreateHexString(byte[] sArray) {
return Hex.EncodeHexString(sArray);
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for VirtualMachinesOperations.
/// </summary>
public static partial class VirtualMachinesOperationsExtensions
{
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<LabVirtualMachine> List(this IVirtualMachinesOperations operations, string labName, ODataQuery<LabVirtualMachine> odataQuery = default(ODataQuery<LabVirtualMachine>))
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAsync(labName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LabVirtualMachine>> ListAsync(this IVirtualMachinesOperations operations, string labName, ODataQuery<LabVirtualMachine> odataQuery = default(ODataQuery<LabVirtualMachine>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(labName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($expand=artifacts,computeVm,networkInterface,applicableSchedule)'
/// </param>
public static LabVirtualMachine Get(this IVirtualMachinesOperations operations, string labName, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).GetAsync(labName, name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($expand=artifacts,computeVm,networkInterface,applicableSchedule)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabVirtualMachine> GetAsync(this IVirtualMachinesOperations operations, string labName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(labName, name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing Virtual machine. This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
public static LabVirtualMachine CreateOrUpdate(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachine labVirtualMachine)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).CreateOrUpdateAsync(labName, name, labVirtualMachine), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing Virtual machine. This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabVirtualMachine> CreateOrUpdateAsync(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachine labVirtualMachine, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(labName, name, labVirtualMachine, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing Virtual machine. This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
public static LabVirtualMachine BeginCreateOrUpdate(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachine labVirtualMachine)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginCreateOrUpdateAsync(labName, name, labVirtualMachine), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing Virtual machine. This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabVirtualMachine> BeginCreateOrUpdateAsync(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachine labVirtualMachine, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(labName, name, labVirtualMachine, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void Delete(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DeleteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void BeginDelete(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDeleteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Modify properties of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
public static LabVirtualMachine Update(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachineFragment labVirtualMachine)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).UpdateAsync(labName, name, labVirtualMachine), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Modify properties of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='labVirtualMachine'>
/// A virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LabVirtualMachine> UpdateAsync(this IVirtualMachinesOperations operations, string labName, string name, LabVirtualMachineFragment labVirtualMachine, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(labName, name, labVirtualMachine, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Attach a new or existing data disk to virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='dataDiskProperties'>
/// Request body for adding a new or existing data disk to a virtual machine.
/// </param>
public static void AddDataDisk(this IVirtualMachinesOperations operations, string labName, string name, DataDiskProperties dataDiskProperties)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).AddDataDiskAsync(labName, name, dataDiskProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Attach a new or existing data disk to virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='dataDiskProperties'>
/// Request body for adding a new or existing data disk to a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddDataDiskAsync(this IVirtualMachinesOperations operations, string labName, string name, DataDiskProperties dataDiskProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.AddDataDiskWithHttpMessagesAsync(labName, name, dataDiskProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Attach a new or existing data disk to virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='dataDiskProperties'>
/// Request body for adding a new or existing data disk to a virtual machine.
/// </param>
public static void BeginAddDataDisk(this IVirtualMachinesOperations operations, string labName, string name, DataDiskProperties dataDiskProperties)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginAddDataDiskAsync(labName, name, dataDiskProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Attach a new or existing data disk to virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='dataDiskProperties'>
/// Request body for adding a new or existing data disk to a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginAddDataDiskAsync(this IVirtualMachinesOperations operations, string labName, string name, DataDiskProperties dataDiskProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginAddDataDiskWithHttpMessagesAsync(labName, name, dataDiskProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Apply artifacts to virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// Request body for applying artifacts to a virtual machine.
/// </param>
public static void ApplyArtifacts(this IVirtualMachinesOperations operations, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ApplyArtifactsAsync(labName, name, applyArtifactsRequest), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Apply artifacts to virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// Request body for applying artifacts to a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ApplyArtifactsAsync(this IVirtualMachinesOperations operations, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ApplyArtifactsWithHttpMessagesAsync(labName, name, applyArtifactsRequest, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Apply artifacts to virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// Request body for applying artifacts to a virtual machine.
/// </param>
public static void BeginApplyArtifacts(this IVirtualMachinesOperations operations, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginApplyArtifactsAsync(labName, name, applyArtifactsRequest), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Apply artifacts to virtual machine. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='applyArtifactsRequest'>
/// Request body for applying artifacts to a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginApplyArtifactsAsync(this IVirtualMachinesOperations operations, string labName, string name, ApplyArtifactsRequest applyArtifactsRequest, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginApplyArtifactsWithHttpMessagesAsync(labName, name, applyArtifactsRequest, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Take ownership of an existing virtual machine This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void Claim(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ClaimAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Take ownership of an existing virtual machine This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ClaimAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ClaimWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Take ownership of an existing virtual machine This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void BeginClaim(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginClaimAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Take ownership of an existing virtual machine This operation can take a
/// while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginClaimAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginClaimWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Detach the specified disk from the virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='detachDataDiskProperties'>
/// Request body for detaching data disk from a virtual machine.
/// </param>
public static void DetachDataDisk(this IVirtualMachinesOperations operations, string labName, string name, DetachDataDiskProperties detachDataDiskProperties)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DetachDataDiskAsync(labName, name, detachDataDiskProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Detach the specified disk from the virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='detachDataDiskProperties'>
/// Request body for detaching data disk from a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DetachDataDiskAsync(this IVirtualMachinesOperations operations, string labName, string name, DetachDataDiskProperties detachDataDiskProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DetachDataDiskWithHttpMessagesAsync(labName, name, detachDataDiskProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Detach the specified disk from the virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='detachDataDiskProperties'>
/// Request body for detaching data disk from a virtual machine.
/// </param>
public static void BeginDetachDataDisk(this IVirtualMachinesOperations operations, string labName, string name, DetachDataDiskProperties detachDataDiskProperties)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDetachDataDiskAsync(labName, name, detachDataDiskProperties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Detach the specified disk from the virtual machine. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='detachDataDiskProperties'>
/// Request body for detaching data disk from a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDetachDataDiskAsync(this IVirtualMachinesOperations operations, string labName, string name, DetachDataDiskProperties detachDataDiskProperties, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDetachDataDiskWithHttpMessagesAsync(labName, name, detachDataDiskProperties, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists all applicable schedules
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static ApplicableSchedule ListApplicableSchedules(this IVirtualMachinesOperations operations, string labName, string name)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListApplicableSchedulesAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all applicable schedules
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicableSchedule> ListApplicableSchedulesAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListApplicableSchedulesWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Start a virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void Start(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).StartAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start a virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StartAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StartWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Start a virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void BeginStart(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginStartAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Start a virtual machine. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStartAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStartWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stop a virtual machine This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void Stop(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).StopAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stop a virtual machine This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StopAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StopWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stop a virtual machine This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
public static void BeginStop(this IVirtualMachinesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginStopAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stop a virtual machine This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStopAsync(this IVirtualMachinesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStopWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LabVirtualMachine> ListNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List virtual machines in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LabVirtualMachine>> ListNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata;
namespace System.Reflection.PortableExecutable
{
public abstract class PEBuilder
{
public PEHeaderBuilder Header { get; }
public Func<IEnumerable<Blob>, BlobContentId> IdProvider { get; }
public bool IsDeterministic { get; }
private readonly Lazy<ImmutableArray<Section>> _lazySections;
private Blob _lazyChecksum;
protected readonly struct Section
{
public readonly string Name;
public readonly SectionCharacteristics Characteristics;
public Section(string name, SectionCharacteristics characteristics)
{
if (name == null)
{
Throw.ArgumentNull(nameof(name));
}
Name = name;
Characteristics = characteristics;
}
}
private readonly struct SerializedSection
{
public readonly BlobBuilder Builder;
public readonly string Name;
public readonly SectionCharacteristics Characteristics;
public readonly int RelativeVirtualAddress;
public readonly int SizeOfRawData;
public readonly int PointerToRawData;
public SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData)
{
Name = name;
Characteristics = characteristics;
Builder = builder;
RelativeVirtualAddress = relativeVirtualAddress;
SizeOfRawData = sizeOfRawData;
PointerToRawData = pointerToRawData;
}
public int VirtualSize => Builder.Count;
}
protected PEBuilder(PEHeaderBuilder header, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider)
{
if (header == null)
{
Throw.ArgumentNull(nameof(header));
}
IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider();
IsDeterministic = deterministicIdProvider != null;
Header = header;
_lazySections = new Lazy<ImmutableArray<Section>>(CreateSections);
}
protected ImmutableArray<Section> GetSections()
{
var sections = _lazySections.Value;
if (sections.IsDefault)
{
throw new InvalidOperationException(SR.Format(SR.MustNotReturnNull, nameof(CreateSections)));
}
return sections;
}
protected abstract ImmutableArray<Section> CreateSections();
protected abstract BlobBuilder SerializeSection(string name, SectionLocation location);
protected internal abstract PEDirectoriesBuilder GetDirectories();
public BlobContentId Serialize(BlobBuilder builder)
{
// Define and serialize sections in two steps.
// We need to know about all sections before serializing them.
var serializedSections = SerializeSections();
// The positions and sizes of directories are calculated during section serialization.
var directories = GetDirectories();
Blob stampFixup;
WritePESignature(builder);
WriteCoffHeader(builder, serializedSections, out stampFixup);
WritePEHeader(builder, directories, serializedSections);
WriteSectionHeaders(builder, serializedSections);
builder.Align(Header.FileAlignment);
foreach (var section in serializedSections)
{
builder.LinkSuffix(section.Builder);
builder.Align(Header.FileAlignment);
}
var contentId = IdProvider(builder.GetBlobs());
// patch timestamp in COFF header:
var stampWriter = new BlobWriter(stampFixup);
stampWriter.WriteUInt32(contentId.Stamp);
Debug.Assert(stampWriter.RemainingBytes == 0);
return contentId;
}
private ImmutableArray<SerializedSection> SerializeSections()
{
var sections = GetSections();
var result = ImmutableArray.CreateBuilder<SerializedSection>(sections.Length);
int sizeOfPeHeaders = Header.ComputeSizeOfPEHeaders(sections.Length);
var nextRva = BitArithmetic.Align(sizeOfPeHeaders, Header.SectionAlignment);
var nextPointer = BitArithmetic.Align(sizeOfPeHeaders, Header.FileAlignment);
foreach (var section in sections)
{
var builder = SerializeSection(section.Name, new SectionLocation(nextRva, nextPointer));
var serialized = new SerializedSection(
builder,
section.Name,
section.Characteristics,
relativeVirtualAddress: nextRva,
sizeOfRawData: BitArithmetic.Align(builder.Count, Header.FileAlignment),
pointerToRawData: nextPointer);
result.Add(serialized);
nextRva = BitArithmetic.Align(serialized.RelativeVirtualAddress + serialized.VirtualSize, Header.SectionAlignment);
nextPointer = serialized.PointerToRawData + serialized.SizeOfRawData;
}
return result.MoveToImmutable();
}
private void WritePESignature(BlobBuilder builder)
{
// MS-DOS stub (128 bytes)
builder.WriteBytes(s_dosHeader);
// PE Signature "PE\0\0"
builder.WriteUInt32(PEHeaders.PESignature);
}
private static readonly byte[] s_dosHeader = new byte[]
{
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00, // NT Header offset (0x80 == s_dosHeader.Length)
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd,
0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e,
0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
internal static int DosHeaderSize = s_dosHeader.Length;
private void WriteCoffHeader(BlobBuilder builder, ImmutableArray<SerializedSection> sections, out Blob stampFixup)
{
// Machine
builder.WriteUInt16((ushort)(Header.Machine == 0 ? Machine.I386 : Header.Machine));
// NumberOfSections
builder.WriteUInt16((ushort)sections.Length);
// TimeDateStamp:
stampFixup = builder.ReserveBytes(sizeof(uint));
// PointerToSymbolTable (TODO: not supported):
// The file pointer to the COFF symbol table, or zero if no COFF symbol table is present.
// This value should be zero for a PE image.
builder.WriteUInt32(0);
// NumberOfSymbols (TODO: not supported):
// The number of entries in the symbol table. This data can be used to locate the string table,
// which immediately follows the symbol table. This value should be zero for a PE image.
builder.WriteUInt32(0);
// SizeOfOptionalHeader:
// The size of the optional header, which is required for executable files but not for object files.
// This value should be zero for an object file (TODO).
builder.WriteUInt16((ushort)PEHeader.Size(Header.Is32Bit));
// Characteristics
builder.WriteUInt16((ushort)Header.ImageCharacteristics);
}
private void WritePEHeader(BlobBuilder builder, PEDirectoriesBuilder directories, ImmutableArray<SerializedSection> sections)
{
builder.WriteUInt16((ushort)(Header.Is32Bit ? PEMagic.PE32 : PEMagic.PE32Plus));
builder.WriteByte(Header.MajorLinkerVersion);
builder.WriteByte(Header.MinorLinkerVersion);
// SizeOfCode:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsCode));
// SizeOfInitializedData:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsInitializedData));
// SizeOfUninitializedData:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsUninitializedData));
// AddressOfEntryPoint:
builder.WriteUInt32((uint)directories.AddressOfEntryPoint);
// BaseOfCode:
int codeSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsCode);
builder.WriteUInt32((uint)(codeSectionIndex != -1 ? sections[codeSectionIndex].RelativeVirtualAddress : 0));
if (Header.Is32Bit)
{
// BaseOfData:
int dataSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsInitializedData);
builder.WriteUInt32((uint)(dataSectionIndex != -1 ? sections[dataSectionIndex].RelativeVirtualAddress : 0));
builder.WriteUInt32((uint)Header.ImageBase);
}
else
{
builder.WriteUInt64(Header.ImageBase);
}
// NT additional fields:
builder.WriteUInt32((uint)Header.SectionAlignment);
builder.WriteUInt32((uint)Header.FileAlignment);
builder.WriteUInt16(Header.MajorOperatingSystemVersion);
builder.WriteUInt16(Header.MinorOperatingSystemVersion);
builder.WriteUInt16(Header.MajorImageVersion);
builder.WriteUInt16(Header.MinorImageVersion);
builder.WriteUInt16(Header.MajorSubsystemVersion);
builder.WriteUInt16(Header.MinorSubsystemVersion);
// Win32VersionValue (reserved, should be 0)
builder.WriteUInt32(0);
// SizeOfImage:
var lastSection = sections[sections.Length - 1];
builder.WriteUInt32((uint)BitArithmetic.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, Header.SectionAlignment));
// SizeOfHeaders:
builder.WriteUInt32((uint)BitArithmetic.Align(Header.ComputeSizeOfPEHeaders(sections.Length), Header.FileAlignment));
// Checksum:
// Shall be zero for strong name signing.
_lazyChecksum = builder.ReserveBytes(sizeof(uint));
new BlobWriter(_lazyChecksum).WriteUInt32(0);
builder.WriteUInt16((ushort)Header.Subsystem);
builder.WriteUInt16((ushort)Header.DllCharacteristics);
if (Header.Is32Bit)
{
builder.WriteUInt32((uint)Header.SizeOfStackReserve);
builder.WriteUInt32((uint)Header.SizeOfStackCommit);
builder.WriteUInt32((uint)Header.SizeOfHeapReserve);
builder.WriteUInt32((uint)Header.SizeOfHeapCommit);
}
else
{
builder.WriteUInt64(Header.SizeOfStackReserve);
builder.WriteUInt64(Header.SizeOfStackCommit);
builder.WriteUInt64(Header.SizeOfHeapReserve);
builder.WriteUInt64(Header.SizeOfHeapCommit);
}
// LoaderFlags
builder.WriteUInt32(0);
// The number of data-directory entries in the remainder of the header.
builder.WriteUInt32(16);
// directory entries:
builder.WriteUInt32((uint)directories.ExportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ExportTable.Size);
builder.WriteUInt32((uint)directories.ImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ImportTable.Size);
builder.WriteUInt32((uint)directories.ResourceTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ResourceTable.Size);
builder.WriteUInt32((uint)directories.ExceptionTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ExceptionTable.Size);
// Authenticode CertificateTable directory. Shall be zero before the PE is signed.
builder.WriteUInt32(0);
builder.WriteUInt32(0);
builder.WriteUInt32((uint)directories.BaseRelocationTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.BaseRelocationTable.Size);
builder.WriteUInt32((uint)directories.DebugTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.DebugTable.Size);
builder.WriteUInt32((uint)directories.CopyrightTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.CopyrightTable.Size);
builder.WriteUInt32((uint)directories.GlobalPointerTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.GlobalPointerTable.Size);
builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.Size);
builder.WriteUInt32((uint)directories.LoadConfigTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.LoadConfigTable.Size);
builder.WriteUInt32((uint)directories.BoundImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.BoundImportTable.Size);
builder.WriteUInt32((uint)directories.ImportAddressTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.ImportAddressTable.Size);
builder.WriteUInt32((uint)directories.DelayImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.DelayImportTable.Size);
builder.WriteUInt32((uint)directories.CorHeaderTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)directories.CorHeaderTable.Size);
// Reserved, should be 0
builder.WriteUInt64(0);
}
private void WriteSectionHeaders(BlobBuilder builder, ImmutableArray<SerializedSection> serializedSections)
{
foreach (var serializedSection in serializedSections)
{
WriteSectionHeader(builder, serializedSection);
}
}
private static void WriteSectionHeader(BlobBuilder builder, SerializedSection serializedSection)
{
if (serializedSection.VirtualSize == 0)
{
return;
}
for (int j = 0, m = serializedSection.Name.Length; j < 8; j++)
{
if (j < m)
{
builder.WriteByte((byte)serializedSection.Name[j]);
}
else
{
builder.WriteByte(0);
}
}
builder.WriteUInt32((uint)serializedSection.VirtualSize);
builder.WriteUInt32((uint)serializedSection.RelativeVirtualAddress);
builder.WriteUInt32((uint)serializedSection.SizeOfRawData);
builder.WriteUInt32((uint)serializedSection.PointerToRawData);
// PointerToRelocations (TODO: not supported):
builder.WriteUInt32(0);
// PointerToLinenumbers (TODO: not supported):
builder.WriteUInt32(0);
// NumberOfRelocations (TODO: not supported):
builder.WriteUInt16(0);
// NumberOfLinenumbers (TODO: not supported):
builder.WriteUInt16(0);
builder.WriteUInt32((uint)serializedSection.Characteristics);
}
private static int IndexOfSection(ImmutableArray<SerializedSection> sections, SectionCharacteristics characteristics)
{
for (int i = 0; i < sections.Length; i++)
{
if ((sections[i].Characteristics & characteristics) == characteristics)
{
return i;
}
}
return -1;
}
private static int SumRawDataSizes(ImmutableArray<SerializedSection> sections, SectionCharacteristics characteristics)
{
int result = 0;
for (int i = 0; i < sections.Length; i++)
{
if ((sections[i].Characteristics & characteristics) == characteristics)
{
result += sections[i].SizeOfRawData;
}
}
return result;
}
// internal for testing
internal static IEnumerable<Blob> GetContentToSign(BlobBuilder peImage, int peHeadersSize, int peHeaderAlignment, Blob strongNameSignatureFixup)
{
// Signed content includes
// - PE header without its alignment padding
// - all sections including their alignment padding and excluding strong name signature blob
// PE specification:
// To calculate the PE image hash, Authenticode orders the sections that are specified in the section table
// by address range, then hashes the resulting sequence of bytes, passing over the exclusion ranges.
//
// Note that sections are by construction ordered by their address, so there is no need to reorder.
int remainingHeaderToSign = peHeadersSize;
int remainingHeader = BitArithmetic.Align(peHeadersSize, peHeaderAlignment);
foreach (var blob in peImage.GetBlobs())
{
int blobStart = blob.Start;
int blobLength = blob.Length;
while (blobLength > 0)
{
if (remainingHeader > 0)
{
int length;
if (remainingHeaderToSign > 0)
{
length = Math.Min(remainingHeaderToSign, blobLength);
yield return new Blob(blob.Buffer, blobStart, length);
remainingHeaderToSign -= length;
}
else
{
length = Math.Min(remainingHeader, blobLength);
}
remainingHeader -= length;
blobStart += length;
blobLength -= length;
}
else if (blob.Buffer == strongNameSignatureFixup.Buffer)
{
yield return GetPrefixBlob(new Blob(blob.Buffer, blobStart, blobLength), strongNameSignatureFixup);
yield return GetSuffixBlob(new Blob(blob.Buffer, blobStart, blobLength), strongNameSignatureFixup);
break;
}
else
{
yield return new Blob(blob.Buffer, blobStart, blobLength);
break;
}
}
}
}
// internal for testing
internal static Blob GetPrefixBlob(Blob container, Blob blob) => new Blob(container.Buffer, container.Start, blob.Start - container.Start);
internal static Blob GetSuffixBlob(Blob container, Blob blob) => new Blob(container.Buffer, blob.Start + blob.Length, container.Start + container.Length - blob.Start - blob.Length);
// internal for testing
internal static IEnumerable<Blob> GetContentToChecksum(BlobBuilder peImage, Blob checksumFixup)
{
foreach (var blob in peImage.GetBlobs())
{
if (blob.Buffer == checksumFixup.Buffer)
{
yield return GetPrefixBlob(blob, checksumFixup);
yield return GetSuffixBlob(blob, checksumFixup);
}
else
{
yield return blob;
}
}
}
internal void Sign(BlobBuilder peImage, Blob strongNameSignatureFixup, Func<IEnumerable<Blob>, byte[]> signatureProvider)
{
Debug.Assert(peImage != null);
Debug.Assert(signatureProvider != null);
int peHeadersSize = Header.ComputeSizeOfPEHeaders(GetSections().Length);
byte[] signature = signatureProvider(GetContentToSign(peImage, peHeadersSize, Header.FileAlignment, strongNameSignatureFixup));
// signature may be shorter (the rest of the reserved space is padding):
if (signature == null || signature.Length > strongNameSignatureFixup.Length)
{
throw new InvalidOperationException(SR.SignatureProviderReturnedInvalidSignature);
}
var writer = new BlobWriter(strongNameSignatureFixup);
writer.WriteBytes(signature);
// Calculate the checksum after the strong name signature has been written.
uint checksum = CalculateChecksum(peImage, _lazyChecksum);
new BlobWriter(_lazyChecksum).WriteUInt32(checksum);
}
// internal for testing
internal static uint CalculateChecksum(BlobBuilder peImage, Blob checksumFixup)
{
return CalculateChecksum(GetContentToChecksum(peImage, checksumFixup)) + (uint)peImage.Count;
}
private static unsafe uint CalculateChecksum(IEnumerable<Blob> blobs)
{
uint checksum = 0;
int pendingByte = -1;
foreach (var blob in blobs)
{
var segment = blob.GetBytes();
fixed (byte* arrayPtr = segment.Array)
{
Debug.Assert(segment.Count > 0);
byte* ptr = arrayPtr + segment.Offset;
byte* end = ptr + segment.Count;
if (pendingByte >= 0)
{
// little-endian encoding:
checksum = AggregateChecksum(checksum, (ushort)(*ptr << 8 | pendingByte));
ptr++;
}
if ((end - ptr) % 2 != 0)
{
end--;
pendingByte = *end;
}
else
{
pendingByte = -1;
}
while (ptr < end)
{
checksum = AggregateChecksum(checksum, *(ushort*)ptr);
ptr += sizeof(ushort);
}
}
}
if (pendingByte >= 0)
{
checksum = AggregateChecksum(checksum, (ushort)pendingByte);
}
return checksum;
}
private static uint AggregateChecksum(uint checksum, ushort value)
{
uint sum = checksum + value;
return (sum >> 16) + unchecked((ushort)sum);
}
}
}
| |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Teknik.Areas.Admin.ViewModels;
using Teknik.Areas.Users.Models;
using Teknik.Areas.Users.Utility;
using Teknik.Attributes;
using Teknik.Configuration;
using Teknik.Controllers;
using Teknik.Data;
using Teknik.Filters;
using Teknik.Models;
using Teknik.Utilities;
using Teknik.ViewModels;
using Teknik.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace Teknik.Areas.Admin.Controllers
{
[Authorize(Roles = "Admin")]
[Area("Admin")]
public class AdminController : DefaultController
{
public AdminController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base (logger, config, dbContext) { }
[HttpGet]
[TrackPageView]
public IActionResult Dashboard()
{
DashboardViewModel model = new DashboardViewModel();
return View(model);
}
[HttpGet]
[TrackPageView]
public IActionResult UserSearch()
{
UserSearchViewModel model = new UserSearchViewModel();
return View(model);
}
[HttpGet]
[TrackPageView]
public async Task<IActionResult> UserInfo(string username)
{
if (UserHelper.UserExists(_dbContext, username))
{
User user = UserHelper.GetUser(_dbContext, username);
UserInfoViewModel model = new UserInfoViewModel();
model.Username = user.Username;
// Get Identity User Info
var info = await IdentityHelper.GetIdentityUserInfo(_config, username);
if (info.AccountType.HasValue)
model.AccountType = info.AccountType.Value;
if (info.AccountStatus.HasValue)
model.AccountStatus = info.AccountStatus.Value;
return View(model);
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpGet]
[TrackPageView]
public IActionResult UploadSearch()
{
UploadSearchViewModel model = new UploadSearchViewModel();
return View(model);
}
[HttpGet]
[TrackPageView]
public IActionResult PasteSearch()
{
PasteSearchViewModel model = new PasteSearchViewModel();
return View(model);
}
[HttpGet]
[TrackPageView]
public IActionResult ShortenedUrlSearch()
{
ShortenedUrlSearchViewModel model = new ShortenedUrlSearchViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> GetUserSearchResults(string query, [FromServices] ICompositeViewEngine viewEngine)
{
List<UserResultViewModel> models = new List<UserResultViewModel>();
var results = _dbContext.Users.Where(u => u.Username.Contains(query)).ToList();
if (results != null)
{
foreach (User user in results)
{
try
{
UserResultViewModel model = new UserResultViewModel();
model.Username = user.Username;
if (_config.EmailConfig.Enabled)
{
model.Email = string.Format("{0}@{1}", user.Username, _config.EmailConfig.Domain);
}
var info = await IdentityHelper.GetIdentityUserInfo(_config, user.Username);
if (info.CreationDate.HasValue)
model.JoinDate = info.CreationDate.Value;
model.LastSeen = await UserHelper.GetLastAccountActivity(_dbContext, _config, user.Username);
models.Add(model);
}
catch (Exception)
{
// Skip this result
}
}
}
string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/Admin/Views/Admin/UserResults.cshtml", models);
return Json(new { result = new { html = renderedView } });
}
[HttpPost]
public async Task<IActionResult> GetUploadSearchResults(string url, [FromServices] ICompositeViewEngine viewEngine)
{
Upload.Models.Upload foundUpload = _dbContext.Uploads.Where(u => u.Url == url).FirstOrDefault();
if (foundUpload != null)
{
UploadResultViewModel model = new UploadResultViewModel();
model.Url = foundUpload.Url;
model.ContentType = foundUpload.ContentType;
model.ContentLength = foundUpload.ContentLength;
model.DateUploaded = foundUpload.DateUploaded;
model.Downloads = foundUpload.Downloads;
model.DeleteKey = foundUpload.DeleteKey;
model.Username = foundUpload.User?.Username;
string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/Admin/Views/Admin/UploadResult.cshtml", model);
return Json(new { result = new { html = renderedView } });
}
return Json(new { error = new { message = "Upload does not exist" } });
}
[HttpPost]
public async Task<IActionResult> GetPasteSearchResults(string url, [FromServices] ICompositeViewEngine viewEngine)
{
Paste.Models.Paste foundPaste = _dbContext.Pastes.Where(u => u.Url == url).FirstOrDefault();
if (foundPaste != null)
{
PasteResultViewModel model = new PasteResultViewModel();
model.Url = foundPaste.Url;
model.DatePosted = foundPaste.DatePosted;
model.Views = foundPaste.Views;
model.DeleteKey = foundPaste.DeleteKey;
model.Username = foundPaste.User?.Username;
string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/Admin/Views/Admin/PasteResult.cshtml", model);
return Json(new { result = new { html = renderedView } });
}
return Json(new { error = new { message = "Paste does not exist" } });
}
[HttpPost]
public async Task<IActionResult> GetShortenedUrlSearchResults(string url, [FromServices] ICompositeViewEngine viewEngine)
{
Shortener.Models.ShortenedUrl foundUrl = _dbContext.ShortenedUrls.Where(u => u.ShortUrl == url).FirstOrDefault();
if (foundUrl != null)
{
ShortenedUrlResultViewModel model = new ShortenedUrlResultViewModel();
model.OriginalUrl = foundUrl.OriginalUrl;
model.ShortenedUrl = foundUrl.ShortUrl;
model.CreationDate = foundUrl.DateAdded;
model.Views = foundUrl.Views;
model.Username = foundUrl.User?.Username;
string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/Admin/Views/Admin/ShortenedUrlResult.cshtml", model);
return Json(new { result = new { html = renderedView } });
}
return Json(new { error = new { message = "Shortened Url does not exist" } });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditUserAccountType(string username, AccountType accountType)
{
if (UserHelper.UserExists(_dbContext, username))
{
// Edit the user's account type
await UserHelper.EditAccountType(_dbContext, _config, username, accountType);
return Json(new { result = new { success = true } });
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditUserAccountStatus(string username, AccountStatus accountStatus)
{
if (UserHelper.UserExists(_dbContext, username))
{
// Edit the user's account type
await UserHelper.EditAccountStatus(_dbContext, _config, username, accountStatus);
return Json(new { result = new { success = true } });
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateInviteCode(string username)
{
InviteCode inviteCode = new InviteCode();
inviteCode.Active = true;
inviteCode.Code = Guid.NewGuid().ToString();
if (!string.IsNullOrEmpty(username))
{
if (!UserHelper.UserExists(_dbContext, username))
{
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
User user = UserHelper.GetUser(_dbContext, username);
inviteCode.Owner = user;
}
_dbContext.InviteCodes.Add(inviteCode);
_dbContext.SaveChanges();
return Json(new { result = new { code = inviteCode.Code } });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteAccount(string username)
{
try
{
User user = UserHelper.GetUser(_dbContext, username);
if (user != null)
{
await UserHelper.DeleteAccount(_dbContext, _config, user);
return Json(new { result = true });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
}
return Json(new { error = "Unable to delete user" });
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeleteData(string type, string id)
{
var context = new ControllerContext();
context.HttpContext = Request.HttpContext;
context.RouteData = RouteData;
context.ActionDescriptor = new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor();
switch (type)
{
case "upload":
var uploadController = new Upload.Controllers.UploadController(_logger, _config, _dbContext);
uploadController.ControllerContext = context;
return uploadController.Delete(id);
case "paste":
var pasteController = new Paste.Controllers.PasteController(_logger, _config, _dbContext);
pasteController.ControllerContext = context;
return pasteController.Delete(id);
case "shortenedUrl":
var shortenController = new Shortener.Controllers.ShortenerController(_logger, _config, _dbContext);
shortenController.ControllerContext = context;
return shortenController.Delete(id);
case "vault":
var vaultController = new Vault.Controllers.VaultController(_logger, _config, _dbContext);
vaultController.ControllerContext = context;
return vaultController.Delete(id);
}
return Json(new { error = "Invalid Type" });
}
}
}
| |
using System;
#if (FULL_BUILD)
using System.Data;
using System.Web.SessionState;
using System.Data.SqlTypes;
#endif
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Weborb;
using Weborb.Config;
using Weborb.Util;
using Weborb.Util.Logging;
using Weborb.Reader;
using Weborb.Message;
using Weborb.Types;
using Weborb.Exceptions;
using Weborb.Writer.Specialized;
namespace Weborb.Writer
{
public sealed class MessageWriter
{
private static Dictionary<Type, ITypeWriter> writers = new Dictionary<Type, ITypeWriter>();
// this writers come from config and other external places, they override main ones
private static Dictionary<Type, ITypeWriter> additionalWriters = new Dictionary<Type, ITypeWriter>();
private static ArrayWriter arrayWriter = new ArrayWriter();
private static ObjectWriter defaultWriter = new ObjectWriter();
private static NullWriter nullWriter = new NullWriter();
private static EnumerationWriter enumWriter = new EnumerationWriter();
private static CollectionWriter enumerableWriter = new CollectionWriter();
private static bool logSer;
static MessageWriter()
{
logSer = Log.isLogging( LoggingConstants.SERIALIZATION );
// numbers and primitive types
NumberWriter numWriter = new NumberWriter();
IntegerWriter intWriter = new IntegerWriter();
writers.Add( typeof( byte ), intWriter );
writers.Add( typeof( int ), intWriter );
writers.Add( typeof( short ), intWriter );
writers.Add( typeof( uint ), intWriter );
writers.Add( typeof( ushort ), intWriter );
writers.Add( typeof( float ), numWriter );
writers.Add( typeof( double ), numWriter );
writers.Add( typeof( long ), numWriter );
writers.Add( typeof( ulong ), numWriter );
writers.Add( typeof( IConvertible ), numWriter );
writers.Add( typeof( NumberObject ), new NumberObjectWriter() );
writers.Add( typeof( Boolean ), new BooleanWriter() );
StringWriter stringWriter = new StringWriter( false );
writers.Add( typeof( string ), stringWriter );
writers.Add( typeof( char[] ), stringWriter );
writers.Add( typeof( Char ), stringWriter );
writers.Add( typeof( StringBuilder ), stringWriter );
writers.Add( typeof( DateTime ), new DateWriter( false ) );
writers.Add( typeof( TimeSpan ), new TimeSpanWriter() );
writers.Add( typeof( Request ), new AMFMessageWriter() );
writers.Add( typeof( Header ), new AMFHeaderWriter() );
writers.Add( typeof( Body ), new AMFBodyWriter() );
// collections
writers.Add( typeof( AnonymousObject ), new PropertyBagWriter() );
writers.Add( typeof( IDictionary ), new BoundPropertyBagWriter() );
writers.Add( typeof( TypedObject ), new TypedObjectWriter() );
writers.Add( typeof( IEnumerator ), new EnumeratorWriter() );
writers.Add( typeof( IWebORBArrayCollection ), new ArrayCollectionWriter() );
writers.Add( typeof( IWebORBArray ), new ArrayWriter() );
#if (FULL_BUILD)
writers.Add( typeof( IWebORBVector<> ), new V3VectorWriter<object>() );
writers.Add( typeof( StringDictionary ), new StringDictionaryWriter() );
writers.Add( typeof( TypedDictionary ), new TypedDictionaryWriter() );
writers.Add( typeof( TypedDataSet ), new TypedDataSetWriter() );
writers.Add( typeof( TypedDataTable ), new TypedDataTableWriter() );
// remote references
writers.Add( typeof( RemoteReferenceObject ), new RemoteReferenceWriter() );
// sql types
writers.Add( typeof( DataSet ), new DataSetWriter() );
writers.Add( typeof( DataTable ), new DataTableWriter() );
GenericSqlTypeHandler sqlTypesHandler = new GenericSqlTypeHandler();
writers.Add( typeof( SqlDateTime ), sqlTypesHandler );
writers.Add( typeof( SqlBinary ), sqlTypesHandler );
writers.Add( typeof( SqlBoolean ), sqlTypesHandler );
writers.Add( typeof( SqlByte ), sqlTypesHandler );
writers.Add( typeof( SqlDecimal ), sqlTypesHandler );
writers.Add( typeof( SqlDouble ), sqlTypesHandler );
writers.Add( typeof( SqlInt16 ), sqlTypesHandler );
writers.Add( typeof( SqlInt32 ), sqlTypesHandler );
writers.Add( typeof( SqlInt64 ), sqlTypesHandler );
writers.Add( typeof( SqlMoney ), sqlTypesHandler );
writers.Add( typeof( SqlSingle ), sqlTypesHandler );
writers.Add( typeof( SqlString ), sqlTypesHandler );
#endif
writers.Add( typeof( ServiceException ), new ServiceExceptionWriter() );
// various .net types
writers.Add( typeof( Guid ), new GuidWriter() );
// DOM document
writers.Add( typeof( Type ), new RuntimeTypeWriter() );
#if (FULL_BUILD)
XmlWriter xmlWriter = new XmlWriter();
writers.Add( typeof( System.Xml.XmlDocument ), xmlWriter );
writers.Add( typeof( System.Xml.XmlElement ), xmlWriter );
writers.Add( typeof( System.Xml.XmlNode ), xmlWriter );
DomainObjectWriter domainObjectWriter = new DomainObjectWriter();
writers.Add( typeof( Weborb.Data.Management.DomainObject ), domainObjectWriter );
try
{
Type hibernateProxyType = TypeLoader.LoadType( "NHibernate.Proxy.INHibernateProxy" );
if ( hibernateProxyType != null )
// new version of NHibernate was added
//writers.Add( hibernateProxyType, new HibernateProxyWriter() );
writers.Add( hibernateProxyType, new Hibernate2ProxyWriter() );
}
catch ( Exception )
{
}
#if NET_35 || NET_40
try
{
Type entityObjectType = typeof( System.Data.Objects.DataClasses.EntityObject);
if (entityObjectType != null)
writers.Add(entityObjectType, new EntityObjectWriter());
}
catch (Exception e)
{
Log.log(LoggingConstants.EXCEPTION, e);
}
#endif
#endif
}
public static ObjectWriter DefaultWriter
{
get
{
return defaultWriter;
}
set
{
defaultWriter = value;
}
}
public static void AddAdditionalTypeWriter( Type mappedType, ITypeWriter writer )
{
//if( Weborb.Util.License.LicenseManager.GetInstance().IsStandardLicense() )
// throw new Exception( "cannot register custom serializers, this feature is available in WebORB Professional Edition" );
additionalWriters[ mappedType ] = writer;
}
public static void CleanAdditionalWriters()
{
additionalWriters.Clear();
}
public static void SetEnumerationWriter( EnumerationWriter writer )
{
MessageWriter.enumWriter = writer;
}
public static void SetEnumerableWriter( CollectionWriter enumerableWriter )
{
MessageWriter.enumerableWriter = enumerableWriter;
}
/*
public static Object writeObject( object obj )
{
ITypeWriter writer = getWriter( obj );
return writer.write( obj );
}
*/
public static void writeObject( object obj, IProtocolFormatter formatter )
{
ITypeWriter typeWriter = getWriter( obj, formatter );
typeWriter.write( obj, formatter );
}
internal static ITypeWriter getWriter( object obj, IProtocolFormatter formatter )
{
if ( obj == null || obj is DBNull )
return nullWriter;
Type objectType = obj.GetType();
ITypeWriter writer = formatter.getCachedWriter( objectType );
if ( writer == null )
{
// none of the interfaces matched a writer.
// perform a lookup for the object class hierarchy
writer = getWriter( objectType, formatter, true );
if ( writer == null )
{
if ( typeof( IEnumerable ).IsInstanceOfType( obj ) )
{
writer = enumerableWriter;
}
else
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "cannot find a writer for the object, will use default writer - " + defaultWriter );
writer = defaultWriter;
}
}
formatter.addCachedWriter( objectType, writer );
}
ITypeWriter referenceWriter = writer.getReferenceWriter();
if ( referenceWriter != null )
{
// if the return object implements IHTTPSessionObject
// keep it in the http session. The same object will be retrieved
// on the subsequent invocations
#if (FULL_BUILD)
if ( obj is IHttpSessionObject )
{
IHttpSessionObject httpSessionObject = (IHttpSessionObject)obj;
string id = httpSessionObject.getID();
object objectInSession = httpSessionObject.getObject();
if ( Log.isLogging( LoggingConstants.DEBUG ) )
Log.log( LoggingConstants.DEBUG, "placing object into HTTP session. ID - " + id + " object " + obj );
//TODO: check for acuracy of Add method here
HttpSessionState session = (HttpSessionState)ThreadContext.currentSession();
if ( session != null )
session.Add( id, objectInSession );
}
#endif
formatter.setContextWriter( writer );
writer = referenceWriter;
}
// if a writer is found, use it, otherwise use the default writer
return writer;
}
internal static ITypeWriter getWriter( Type type, IProtocolFormatter formatter, bool checkInterfaces )
{
// class can be null only when we traverse class hierarchy.
// when we get to the ver root of it, the superclass is null.
// return null here, so the outer code can use a default writer
if ( type == null )
return null;
// perform the lookup. Let protocol formatter do the check for any
// protocol specific type bindings
ITypeWriter writer = null;
if ( formatter != null )
writer = formatter.getWriter( type );
// check against the additional lookup table (this will override main table)
if ( writer == null )
additionalWriters.TryGetValue( type, out writer );
// check against the main lookup table
if ( writer == null )
writers.TryGetValue( type, out writer );
// if we have a writer - use it
if ( writer != null )
return writer;
if ( type.IsArray )
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "object is an array returning ArrayWriter" );
return arrayWriter;
}
else if ( typeof( Enum ).IsAssignableFrom( type ) )
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "object is an enumeration type" );
return enumWriter;
}
if ( checkInterfaces )
writer = matchInterfaces( type.GetInterfaces() );
if ( writer != null )
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "found a writer for an interface - " + writer );
return writer;
}
// go to the super class as the last resort
return getWriter( type.BaseType, formatter, true );
}
private static ITypeWriter matchInterfaces( Type[] interfaces )
{
if ( interfaces.Length == 0 )
return null;
List<Type> nextLevelInterfaces = new List<Type>();
// loop through the interfaces and check if there's a writer
for ( int i = 0; i < interfaces.Length; i++ )
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "looking up writer for " + interfaces[ i ] );
ITypeWriter writer = getWriter( interfaces[ i ], null, false );
// found a writer mapped to the interface - use it
if ( writer != null )
{
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "returning " + writer + " for interface " + interfaces[ i ] );
return writer;
}
//writer = matchInterfaces( interfaces[ i ].GetInterfaces() );
//if( writer != null )
// return writer;
nextLevelInterfaces.AddRange( interfaces[ i ].GetInterfaces() );
}
if ( nextLevelInterfaces.Count > 0 )
{
ITypeWriter intfWriter = matchInterfaces( nextLevelInterfaces.ToArray() );
if ( intfWriter != null )
return intfWriter;
}
if ( logSer )
Log.log( LoggingConstants.SERIALIZATION, "none of the interfaces matched a writer" );
return null;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.PythonTools.EnvironmentsList.Properties;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Wpf;
namespace Microsoft.PythonTools.EnvironmentsList {
internal partial class ConfigurationExtension : UserControl {
public static readonly ICommand Apply = new RoutedCommand();
public static readonly ICommand Reset = new RoutedCommand();
public static readonly ICommand AutoDetect = new RoutedCommand();
public static readonly ICommand Remove = new RoutedCommand();
private readonly ConfigurationExtensionProvider _provider;
public ConfigurationExtension(ConfigurationExtensionProvider provider) {
_provider = provider;
DataContextChanged += ConfigurationExtension_DataContextChanged;
InitializeComponent();
}
void ConfigurationExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
var view = e.NewValue as EnvironmentView;
if (view != null) {
var current = Subcontext.DataContext as ConfigurationEnvironmentView;
if (current == null || current.EnvironmentView != view) {
var cev = new ConfigurationEnvironmentView(view);
_provider.ResetConfiguration(cev);
Subcontext.DataContext = cev;
}
}
}
private void Apply_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as ConfigurationEnvironmentView;
e.CanExecute = view != null && _provider.IsConfigurationChanged(view);
e.Handled = true;
}
private void Apply_Executed(object sender, ExecutedRoutedEventArgs e) {
_provider.ApplyConfiguration((ConfigurationEnvironmentView)e.Parameter);
e.Handled = true;
}
private void Reset_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as ConfigurationEnvironmentView;
e.CanExecute = view != null && _provider.IsConfigurationChanged(view);
e.Handled = true;
}
private void Reset_Executed(object sender, ExecutedRoutedEventArgs e) {
_provider.ResetConfiguration((ConfigurationEnvironmentView)e.Parameter);
e.Handled = true;
}
private void Remove_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as ConfigurationEnvironmentView;
e.CanExecute = view != null;
e.Handled = true;
}
private void Remove_Executed(object sender, ExecutedRoutedEventArgs e) {
_provider.RemoveConfiguration((ConfigurationEnvironmentView)e.Parameter);
e.Handled = true;
}
private void Browse_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
Commands.CanExecute(null, sender, e);
}
private void Browse_Executed(object sender, ExecutedRoutedEventArgs e) {
Commands.Executed(null, sender, e);
}
private void SelectAllText(object sender, RoutedEventArgs e) {
var tb = sender as TextBox;
if (tb != null) {
tb.SelectAll();
}
}
private void AutoDetect_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as ConfigurationEnvironmentView;
e.CanExecute = view != null && !view.IsAutoDetectRunning && (
Directory.Exists(view.PrefixPath) ||
File.Exists(view.InterpreterPath) ||
File.Exists(view.WindowsInterpreterPath)
);
}
private async void AutoDetect_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (ConfigurationEnvironmentView)e.Parameter;
try {
view.IsAutoDetectRunning = true;
CommandManager.InvalidateRequerySuggested();
var newView = await AutoDetectAsync(view.Values);
view.Values = newView;
CommandManager.InvalidateRequerySuggested();
} finally {
view.IsAutoDetectRunning = false;
}
}
private async Task<ConfigurationValues> AutoDetectAsync(ConfigurationValues view) {
if (!Directory.Exists(view.PrefixPath)) {
if (File.Exists(view.InterpreterPath)) {
view.PrefixPath = Path.GetDirectoryName(view.InterpreterPath);
} else if (File.Exists(view.WindowsInterpreterPath)) {
view.PrefixPath = Path.GetDirectoryName(view.WindowsInterpreterPath);
} else if (Directory.Exists(view.LibraryPath)) {
view.PrefixPath = Path.GetDirectoryName(view.LibraryPath);
} else {
// Don't have enough information, so abort without changing
// any settings.
return view;
}
while (Directory.Exists(view.PrefixPath) && !File.Exists(PathUtils.FindFile(view.PrefixPath, "site.py"))) {
view.PrefixPath = Path.GetDirectoryName(view.PrefixPath);
}
}
if (!Directory.Exists(view.PrefixPath)) {
// If view.PrefixPath is not valid by this point, we can't find anything
// else, so abort withou changing any settings.
return view;
}
if (!File.Exists(view.InterpreterPath)) {
view.InterpreterPath = PathUtils.FindFile(
view.PrefixPath,
CPythonInterpreterFactoryConstants.ConsoleExecutable,
firstCheck: new[] { "scripts" }
);
}
if (!File.Exists(view.WindowsInterpreterPath)) {
view.WindowsInterpreterPath = PathUtils.FindFile(
view.PrefixPath,
CPythonInterpreterFactoryConstants.WindowsExecutable,
firstCheck: new[] { "scripts" }
);
}
if (!Directory.Exists(view.LibraryPath)) {
var sitePy = PathUtils.FindFile(
view.PrefixPath,
"os.py",
firstCheck: new[] { "lib" }
);
if (File.Exists(sitePy)) {
view.LibraryPath = Path.GetDirectoryName(sitePy);
}
}
if (File.Exists(view.InterpreterPath)) {
using (var output = ProcessOutput.RunHiddenAndCapture(
view.InterpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))"
)) {
var exitCode = await output;
if (exitCode == 0) {
view.VersionName = output.StandardOutputLines.FirstOrDefault() ?? view.VersionName;
}
}
var binaryType = Microsoft.PythonTools.Interpreter.NativeMethods.GetBinaryType(view.InterpreterPath);
if (binaryType == ProcessorArchitecture.Amd64) {
view.ArchitectureName = "64-bit";
} else if (binaryType == ProcessorArchitecture.X86) {
view.ArchitectureName = "32-bit";
}
}
return view;
}
}
sealed class ConfigurationExtensionProvider : IEnvironmentViewExtension {
private FrameworkElement _wpfObject;
private readonly IInterpreterOptionsService _interpreterOptions;
internal ConfigurationExtensionProvider(IInterpreterOptionsService interpreterOptions) {
_interpreterOptions = interpreterOptions;
}
public void ApplyConfiguration(ConfigurationEnvironmentView view) {
var factory = view.EnvironmentView.Factory;
if (view.Description != factory.Configuration.Description) {
// We're renaming the interpreter, remove the old one...
_interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id);
}
var newInterp = _interpreterOptions.AddConfigurableInterpreter(
view.Description,
new InterpreterConfiguration(
"",
view.Description,
view.PrefixPath,
view.InterpreterPath,
view.WindowsInterpreterPath,
view.LibraryPath,
view.PathEnvironmentVariable,
view.ArchitectureName == "64-bit" ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86,
Version.Parse(view.VersionName)
)
);
}
public bool IsConfigurationChanged(ConfigurationEnvironmentView view) {
var factory = view.EnvironmentView.Factory;
var arch = factory.Configuration.Architecture == ProcessorArchitecture.Amd64 ? "64-bit" : "32-bit";
return view.Description != factory.Configuration.Description ||
view.PrefixPath != factory.Configuration.PrefixPath ||
view.InterpreterPath != factory.Configuration.InterpreterPath ||
view.WindowsInterpreterPath != factory.Configuration.WindowsInterpreterPath ||
view.LibraryPath != factory.Configuration.LibraryPath ||
view.PathEnvironmentVariable != factory.Configuration.PathEnvironmentVariable ||
view.ArchitectureName != arch ||
view.VersionName != factory.Configuration.Version.ToString();
}
public void ResetConfiguration(ConfigurationEnvironmentView view) {
var factory = view.EnvironmentView.Factory;
view.Description = factory.Configuration.Description;
view.PrefixPath = factory.Configuration.PrefixPath;
view.InterpreterPath = factory.Configuration.InterpreterPath;
view.WindowsInterpreterPath = factory.Configuration.WindowsInterpreterPath;
view.LibraryPath = factory.Configuration.LibraryPath;
view.PathEnvironmentVariable = factory.Configuration.PathEnvironmentVariable;
view.ArchitectureName = factory.Configuration.Architecture == ProcessorArchitecture.Amd64 ? "64-bit" : "32-bit";
view.VersionName = factory.Configuration.Version.ToString();
}
public void RemoveConfiguration(ConfigurationEnvironmentView view) {
var factory = view.EnvironmentView.Factory;
_interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id);
}
public int SortPriority {
get { return -9; }
}
public string LocalizedDisplayName {
get { return Resources.ConfigurationExtensionDisplayName; }
}
public FrameworkElement WpfObject {
get {
if (_wpfObject == null) {
_wpfObject = new ConfigurationExtension(this);
}
return _wpfObject;
}
}
public object HelpContent {
get { return Resources.ConfigurationExtensionHelpContent; }
}
}
struct ConfigurationValues {
public string Description;
public string PrefixPath;
public string InterpreterPath;
public string WindowsInterpreterPath;
public string LibraryPath;
public string PathEnvironmentVariable;
public string VersionName;
public string ArchitectureName;
}
sealed class ConfigurationEnvironmentView : INotifyPropertyChanged {
private static readonly string[] _architectureNames = new[] {
"32-bit",
"64-bit"
};
private static readonly string[] _versionNames = new[] {
"2.5",
"2.6",
"2.7",
"3.0",
"3.1",
"3.2",
"3.3",
"3.4",
"3.5"
};
private readonly EnvironmentView _view;
private bool _isAutoDetectRunning;
private ConfigurationValues _values;
public ConfigurationEnvironmentView(EnvironmentView view) {
_view = view;
}
public EnvironmentView EnvironmentView {
get { return _view; }
}
public static IList<string> ArchitectureNames {
get {
return _architectureNames;
}
}
public static IList<string> VersionNames {
get {
return _versionNames;
}
}
public bool IsAutoDetectRunning {
get { return _isAutoDetectRunning; }
set {
if (_isAutoDetectRunning != value) {
_isAutoDetectRunning = value;
OnPropertyChanged();
}
}
}
public ConfigurationValues Values {
get { return _values; }
set {
Description = value.Description;
PrefixPath = value.PrefixPath;
InterpreterPath = value.InterpreterPath;
WindowsInterpreterPath = value.WindowsInterpreterPath;
LibraryPath = value.LibraryPath;
PathEnvironmentVariable = value.PathEnvironmentVariable;
VersionName = value.VersionName;
ArchitectureName = value.ArchitectureName;
}
}
public string Description {
get { return _values.Description; }
set {
if (_values.Description != value) {
_values.Description = value;
OnPropertyChanged();
}
}
}
public string PrefixPath {
get { return _values.PrefixPath; }
set {
if (_values.PrefixPath != value) {
_values.PrefixPath = value;
OnPropertyChanged();
}
}
}
public string InterpreterPath {
get { return _values.InterpreterPath; }
set {
if (_values.InterpreterPath != value) {
_values.InterpreterPath = value;
OnPropertyChanged();
}
}
}
public string WindowsInterpreterPath {
get { return _values.WindowsInterpreterPath; }
set {
if (_values.WindowsInterpreterPath != value) {
_values.WindowsInterpreterPath = value;
OnPropertyChanged();
}
}
}
public string LibraryPath {
get { return _values.LibraryPath; }
set {
if (_values.LibraryPath != value) {
_values.LibraryPath = value;
OnPropertyChanged();
}
}
}
public string PathEnvironmentVariable {
get { return _values.PathEnvironmentVariable; }
set {
if (_values.PathEnvironmentVariable != value) {
_values.PathEnvironmentVariable = value;
OnPropertyChanged();
}
}
}
public string ArchitectureName {
get { return _values.ArchitectureName; }
set {
if (_values.ArchitectureName != value) {
_values.ArchitectureName = value;
OnPropertyChanged();
}
}
}
public string VersionName {
get { return _values.VersionName; }
set {
if (_values.VersionName != value) {
_values.VersionName = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Data;
using Avalonia.Markup.Data;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Markup.UnitTests.Data
{
public class BindingExpressionTests : IClassFixture<InvariantCultureFixture>
{
[Fact]
public async Task Should_Get_Simple_Property_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(string));
var result = await target.Take(1);
Assert.Equal("foo", result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Set_Simple_Property_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(string));
target.OnNext("bar");
Assert.Equal("bar", data.StringValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Set_Indexed_Value()
{
var data = new { Foo = new[] { "foo" } };
var target = new BindingExpression(new ExpressionObserver(data, "Foo[0]"), typeof(string));
target.OnNext("bar");
Assert.Equal("bar", data.Foo[0]);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Convert_Get_String_To_Double()
{
var data = new Class1 { StringValue = "5.6" };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double));
var result = await target.Take(1);
Assert.Equal(5.6, result);
GC.KeepAlive(data);
}
[Fact]
public async Task Getting_Invalid_Double_String_Should_Return_BindingError()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double));
var result = await target.Take(1);
Assert.IsType<BindingNotification>(result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Coerce_Get_Null_Double_String_To_UnsetValue()
{
var data = new Class1 { StringValue = null };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double));
var result = await target.Take(1);
Assert.Equal(AvaloniaProperty.UnsetValue, result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Convert_Set_String_To_Double()
{
var data = new Class1 { StringValue = (5.6).ToString() };
var target = new BindingExpression(new ExpressionObserver(data, "StringValue"), typeof(double));
target.OnNext(6.7);
Assert.Equal((6.7).ToString(), data.StringValue);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Convert_Get_Double_To_String()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string));
var result = await target.Take(1);
Assert.Equal((5.6).ToString(), result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Convert_Set_Double_To_String()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string));
target.OnNext("6.7");
Assert.Equal(6.7, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
new ExpressionObserver(data, "StringValue"),
typeof(int),
42,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new InvalidCastException("'foo' is not a valid number."),
BindingErrorType.Error,
42),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value_With_Data_Validation()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
new ExpressionObserver(data, "StringValue", true),
typeof(int),
42,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new InvalidCastException("'foo' is not a valid number."),
BindingErrorType.Error,
42),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_For_Invalid_FallbackValue()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
new ExpressionObserver(data, "StringValue"),
typeof(int),
"bar",
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new AggregateException(
new InvalidCastException("'foo' is not a valid number."),
new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")),
BindingErrorType.Error),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_For_Invalid_FallbackValue_With_Data_Validation()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
new ExpressionObserver(data, "StringValue", true),
typeof(int),
"bar",
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new AggregateException(
new InvalidCastException("'foo' is not a valid number."),
new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")),
BindingErrorType.Error),
result);
GC.KeepAlive(data);
}
[Fact]
public void Setting_Invalid_Double_String_Should_Not_Change_Target()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string));
target.OnNext("foo");
Assert.Equal(5.6, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Setting_Invalid_Double_String_Should_Use_FallbackValue()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(
new ExpressionObserver(data, "DoubleValue"),
typeof(string),
"9.8",
DefaultValueConverter.Instance);
target.OnNext("foo");
Assert.Equal(9.8, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Coerce_Setting_Null_Double_To_Default_Value()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string));
target.OnNext(null);
Assert.Equal(0, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Coerce_Setting_UnsetValue_Double_To_Default_Value()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue"), typeof(string));
target.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(0, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Pass_ConverterParameter_To_Convert()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(
new ExpressionObserver(data, "DoubleValue"),
typeof(string),
converter.Object,
converterParameter: "foo");
target.Subscribe(_ => { });
converter.Verify(x => x.Convert(5.6, typeof(string), "foo", CultureInfo.CurrentCulture));
GC.KeepAlive(data);
}
[Fact]
public void Should_Pass_ConverterParameter_To_ConvertBack()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(
new ExpressionObserver(data, "DoubleValue"),
typeof(string),
converter.Object,
converterParameter: "foo");
target.OnNext("bar");
converter.Verify(x => x.ConvertBack("bar", typeof(double), "foo", CultureInfo.CurrentCulture));
GC.KeepAlive(data);
}
[Fact]
public void Should_Handle_DataValidation()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(new ExpressionObserver(data, "DoubleValue", true), typeof(string));
var result = new List<object>();
target.Subscribe(x => result.Add(x));
target.OnNext(1.2);
target.OnNext("3.4");
target.OnNext("bar");
Assert.Equal(
new[]
{
new BindingNotification("5.6"),
new BindingNotification("1.2"),
new BindingNotification("3.4"),
new BindingNotification(
new InvalidCastException("'bar' is not a valid number."),
BindingErrorType.Error)
},
result);
GC.KeepAlive(data);
}
private class Class1 : NotifyingBase
{
private string _stringValue;
private double _doubleValue;
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; RaisePropertyChanged(); }
}
public double DoubleValue
{
get { return _doubleValue; }
set { _doubleValue = value; RaisePropertyChanged(); }
}
}
}
}
| |
using System;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Execution details returned by Interactive Brokers
/// </summary>
[Serializable()]
public class Execution
{
#region Private Variables
private String accountNumber;
private int clientId;
private String exchange;
private String executionId;
private int liquidation;
private int orderId;
private int permId;
private double price;
private double shares;
private ExecutionSide side;
private String time;
private int cumQuantity;
private decimal avgPrice;
private String orderRef;
#endregion
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public Execution()
{
}
/// <summary>
/// Full Constructor
/// </summary>
/// <param name="orderId">The order id.</param>
/// <param name="clientId">TWS orders have a fixed client id of "0."</param>
/// <param name="executionId">Unique order execution id.</param>
/// <param name="time">The order execution time.</param>
/// <param name="accountNumber">The customer account number.</param>
/// <param name="exchange">Exchange that executed the order.</param>
/// <param name="side">Specifies if the transaction was a sale or a purchase.</param>
/// <param name="shares">The number of shares filled.</param>
/// <param name="price">The order execution price.</param>
/// <param name="permId">The TWS id used to identify orders, remains the same over TWS sessions.</param>
/// <param name="liquidation">Identifies the position as one to be liquidated last should the need arise.</param>
/// <param name="cumQuantity">Cumulative quantity. Used in regular trades, combo trades and legs of the combo.</param>
/// <param name="avgPrice">Average price. Used in regular trades, combo trades and legs of the combo.</param>
/// <param name="orderRef">Order Reference</param>
public Execution(int orderId, int clientId, String executionId, String time, String accountNumber,
String exchange, ExecutionSide side, int shares, double price, int permId, int liquidation,
int cumQuantity, decimal avgPrice, string orderRef)
{
this.orderId = orderId;
this.clientId = clientId;
this.executionId = executionId;
this.time = time;
this.accountNumber = accountNumber;
this.exchange = exchange;
this.side = side;
this.shares = shares;
this.price = price;
this.permId = permId;
this.liquidation = liquidation;
this.cumQuantity = cumQuantity;
this.avgPrice = avgPrice;
this.orderRef = orderRef;
}
#endregion
#region Properties
/// <summary>
/// The order id.
/// </summary>
/// <remarks>TWS orders have a fixed order id of "0."</remarks>
public int OrderId
{
get { return orderId; }
set { orderId = value; }
}
/// <summary>
/// The id of the client that placed the order.
/// </summary>
/// <remarks>TWS orders have a fixed client id of "0."</remarks>
public int ClientId
{
get { return clientId; }
set { clientId = value; }
}
/// <summary>
/// Unique order execution id.
/// </summary>
public string ExecutionId
{
get { return executionId; }
set { executionId = value; }
}
/// <summary>
/// The order execution time.
/// </summary>
public string Time
{
get { return time; }
set { time = value; }
}
/// <summary>
/// The customer account number.
/// </summary>
public string AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
/// <summary>
/// Exchange that executed the order.
/// </summary>
public string Exchange
{
get { return exchange; }
set { exchange = value; }
}
/// <summary>
/// Specifies if the transaction was a sale or a purchase.
/// </summary>
/// <remarks>Valid values are:
/// <list type="bullet">
/// <item>Bought</item>
/// <item>Sold</item>
/// </list>
/// </remarks>
public ExecutionSide Side
{
get { return side; }
set { side = value; }
}
/// <summary>
/// The number of shares filled.
/// </summary>
public double Shares
{
get { return shares; }
set { shares = value; }
}
/// <summary>
/// The order execution price.
/// </summary>
public double Price
{
get { return price; }
set { price = value; }
}
/// <summary>
/// The TWS id used to identify orders, remains the same over TWS sessions.
/// </summary>
public int PermId
{
get { return permId; }
set { permId = value; }
}
/// <summary>
/// Identifies the position as one to be liquidated last should the need arise.
/// </summary>
public int Liquidation
{
get { return liquidation; }
set { liquidation = value; }
}
/// <summary>
/// Cumulative Quantity
/// </summary>
public int CumQuantity
{
get { return cumQuantity; }
set { cumQuantity = value; }
}
/// <summary>
/// Average Price
/// </summary>
public decimal AvgPrice
{
get { return avgPrice; }
set { avgPrice = value; }
}
/// <summary>
/// OrderRef.
/// </summary>
public string OrderRef
{
get { return orderRef; }
set { orderRef = value; }
}
/// <summary>
/// EvRule.
/// </summary>
public string EvRule { get; set; }
/// <summary>
/// EvMultiplier.
/// </summary>
public double EvMultipler { get; set; }
public string ModelCode { get; set; }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace CocosSharp
{
public enum GlyphCollection
{
Dynamic,
NEHE,
Ascii,
Custom
};
// font attributes
internal struct CCFontDefinition
{
public string FontName;
public float FontSize;
public CCTextAlignment Alignment;
public CCVerticalTextAlignment LineAlignment;
public CCSize Dimensions;
public CCColor3B FontFillColor;
public byte FontAlpha;
public CCLabelLineBreak LineBreak;
public bool isShouldAntialias;
};
internal struct LetterInfo
{
public CCFontLetterDefinition Definition;
public CCPoint Position;
public CCSize ContentSize;
public int AtlasIndex;
};
[Flags]
public enum CCLabelFormatFlags {
Unknown = 0x0001,
SpriteFont = 0x0002,
BitmapFont = 0x0004,
CharacterMap = 0x0008,
SystemFont = 0x0010,
}
public enum CCLabelLineBreak {
None = 0,
Character = 1,
Word = 2,
}
public sealed class CCLabelFormat : IDisposable
{
CCLabelFormatFlags formatFlags = CCLabelFormatFlags.Unknown;
public CCLabelFormat ()
{
LineBreaking = CCLabelLineBreak.Word;
}
public CCLabelFormat (CCLabelFormat format)
{
if (format == null)
throw new ArgumentNullException ("format");
Alignment = format.Alignment;
LineAlignment = format.LineAlignment;
FormatFlags = format.FormatFlags;
}
public CCLabelFormat(CCLabelFormatFlags options) : this()
{
formatFlags = options;
}
~CCLabelFormat ()
{
Dispose (false);
}
public CCTextAlignment Alignment {
get; set;
}
public CCVerticalTextAlignment LineAlignment { get; set; }
public CCLabelLineBreak LineBreaking { get; set; }
public object Clone()
{
return new CCLabelFormat (this);
}
public void Dispose ()
{
Dispose (true);
System.GC.SuppressFinalize (this);
}
void Dispose (bool disposing)
{
}
public static CCLabelFormat BitMapFont
{
get {
return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.BitmapFont };
}
}
public static CCLabelFormat SystemFont
{
get {
return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.SystemFont };
}
}
public static CCLabelFormat SpriteFont
{
get {
return new CCLabelFormat () { FormatFlags = CCLabelFormatFlags.SpriteFont };
}
}
public CCLabelFormatFlags FormatFlags {
get {
return formatFlags;
}
set {
formatFlags = value;
}
}
}
[Flags]
public enum CCLabelType
{
SpriteFont,
BitMapFont,
CharacterMap,
SystemFont
};
public partial class CCLabel : CCNode, ICCTextContainer
{
const int defaultSpriteBatchCapacity = 29;
internal static Dictionary<string, CCBMFontConfiguration> fontConfigurations = new Dictionary<string, CCBMFontConfiguration>();
protected CCLabelLineBreak lineBreak;
protected CCTextAlignment horzAlignment = CCTextAlignment.Center;
protected CCVerticalTextAlignment vertAlignment = CCVerticalTextAlignment.Top;
internal CCBMFontConfiguration FontConfiguration { get; set; }
protected string fntConfigFile;
protected string labelText;
protected CCPoint ImageOffset { get; set; }
protected CCSize labelDimensions;
protected bool IsDirty { get; set; }
public CCTextureAtlas TextureAtlas { get ; private set; }
protected CCRawList<CCSprite> Descendants { get; private set; }
protected bool isColorModifiedByOpacity = false;
public CCBlendFunc BlendFunc { get; set; }
public CCLabelType LabelType { get; protected internal set; }
private CCFontAtlas fontAtlas;
private List<LetterInfo> lettersInfo = new List<LetterInfo>();
//! used for optimization
CCSprite reusedLetter;
CCRect reusedRect;
// System font
bool systemFontDirty;
string systemFont;
float systemFontSize;
float lineHeight = 0;
float additionalKerning = 0;
CCLabelFormat labelFormat;
CCQuadCommand quadCommand = null;
// Static properties
public static float DefaultTexelToContentSizeRatio
{
set { DefaultTexelToContentSizeRatios = new CCSize(value, value); }
}
public static CCSize DefaultTexelToContentSizeRatios { get; set; }
// Instance properties
public float LineHeight
{
get { return lineHeight; }
set
{
if (LabelType == CCLabelType.SystemFont)
CCLog.Log("Not supported system font!");
if (value != lineHeight)
{
lineHeight = value;
IsDirty = true;
}
}
}
public float AdditionalKerning
{
get { return additionalKerning; }
set
{
if (LabelType == CCLabelType.SystemFont)
CCLog.Log("Not supported system font!");
if (value != additionalKerning)
{
additionalKerning = value;
IsDirty = true;
}
}
}
public CCLabelFormat LabelFormat
{
get { return labelFormat; }
set
{
if (!labelFormat.Equals(value))
{
// TODO: Check label format flags need to be checked so they can not be
// changed after being set.
labelFormat = value;
IsDirty = true;
}
}
}
public override CCPoint AnchorPoint
{
get { return base.AnchorPoint; }
set
{
if (!AnchorPoint.Equals(value))
{
base.AnchorPoint = value;
IsDirty = true;
}
}
}
public override float Scale
{
set
{
if (!value.Equals(base.ScaleX) || !value.Equals(base.ScaleY))
{
base.Scale = value;
IsDirty = true;
}
}
}
public override float ScaleX
{
get { return base.ScaleX; }
set
{
if (!value.Equals(base.ScaleX))
{
base.ScaleX = value;
IsDirty = true;
}
}
}
public override float ScaleY
{
get { return base.ScaleY; }
set
{
if (!value.Equals(base.ScaleY))
{
base.ScaleY = value;
IsDirty = true;
}
}
}
public CCTextAlignment HorizontalAlignment
{
get { return labelFormat.Alignment; }
set
{
if (labelFormat.Alignment != value)
{
labelFormat.Alignment = value;
IsDirty = true;
}
}
}
public CCVerticalTextAlignment VerticalAlignment
{
get { return labelFormat.LineAlignment; }
set
{
if (labelFormat.LineAlignment != value)
{
labelFormat.LineAlignment = value;
IsDirty = true;
}
}
}
public override CCSize ContentSize
{
get
{
if (IsDirty || systemFontDirty)
UpdateContent();
return base.ContentSize;
}
set
{
if (base.ContentSize != value)
{
base.ContentSize = value;
IsDirty = true;
}
}
}
public CCSize Dimensions
{
get { return labelDimensions; }
set
{
if (labelDimensions != value)
{
labelDimensions = value;
IsDirty = true;
}
}
}
public CCLabelLineBreak LineBreak
{
get { return lineBreak; }
set
{
lineBreak = value;
IsDirty = true;
}
}
bool isAntialiased = CCTexture2D.DefaultIsAntialiased;
public bool IsAntialiased
{
get
{
if (TextureAtlas != null && TextureAtlas.Texture != null)
return TextureAtlas.Texture.IsAntialiased;
else if (textSprite != null)
return textSprite.IsAntialiased;
else
return CCTexture2D.DefaultIsAntialiased;
}
set
{
if (value != isAntialiased)
{
if (TextureAtlas != null && TextureAtlas.Texture != null)
TextureAtlas.Texture.IsAntialiased = value;
else if (textSprite != null)
textSprite.IsAntialiased = value;
isAntialiased = value;
}
}
}
public CCTexture2D Texture
{
get { return TextureAtlas.Texture; }
set
{
TextureAtlas.Texture = value;
UpdateBlendFunc();
}
}
void UpdateBlendFunc()
{
if (!TextureAtlas.Texture.HasPremultipliedAlpha)
{
BlendFunc = CCBlendFunc.NonPremultiplied;
}
quadCommand.BlendType = BlendFunc;
}
public virtual string Text
{
get { return labelText; }
set
{
if (labelText != value)
{
labelText = value;
IsDirty = true;
}
}
}
public string SystemFont
{
get { return systemFont; }
set
{
if (systemFont != value)
{
systemFont = value;
systemFontDirty = true;
}
}
}
public float SystemFontSize
{
get { return systemFontSize; }
set
{
if (systemFontSize != value)
{
systemFontSize = value;
systemFontDirty = true;
}
}
}
public static void PurgeCachedData()
{
if (fontConfigurations != null)
{
fontConfigurations.Clear();
}
}
#region Constructors
static CCLabel()
{
DefaultTexelToContentSizeRatios = CCSize.One;
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
public CCLabel() : this("", "")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
public CCLabel(string str, string fntFile)
: this(str, fntFile, 0.0f)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
public CCLabel(string str, string fntFile, float size)
: this(str, fntFile, size, CCTextAlignment.Left)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="alignment">Horizontal Alignment of the text.</param>
public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment)
: this(str, fntFile, size, alignment, CCPoint.Zero)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="alignment">Horizontal Alignment of the text.</param>
/// <param name="imageOffset">Image offset.</param>
public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment, CCPoint imageOffset)
: this(str, fntFile, size, alignment, imageOffset, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="alignment">Horizontal Alignment of the text.</param>
/// <param name="imageOffset">Image offset.</param>
/// <param name="texture">Texture Atlas to be used.</param>
public CCLabel(string str, string fntFile, float size, CCTextAlignment alignment, CCPoint imageOffset, CCTexture2D texture)
: this(str, fntFile, size, alignment, CCVerticalTextAlignment.Top, imageOffset, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="hAlignment">Horizontal Alignment of the text.</param>
/// <param name="vAlignment">Vertical alignment.</param>
/// <param name="imageOffset">Image offset.</param>
/// <param name="texture">Texture Atlas to be used.</param>
public CCLabel(string str, string fntFile, float size, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
CCPoint imageOffset, CCTexture2D texture)
: this(str, fntFile, size, CCSize.Zero,
new CCLabelFormat() { Alignment = hAlignment, LineAlignment = vAlignment},
imageOffset, texture)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
public CCLabel(string str, string fntFile, CCSize dimensions)
: this (str, fntFile, dimensions,
new CCLabelFormat(), CCPoint.Zero, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="hAlignment">Horizontal alignment of the text.</param>
public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment)
: this (str, fntFile, dimensions,
new CCLabelFormat() { Alignment = hAlignment},
CCPoint.Zero, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="hAlignment">Horizontal alignment of the text.</param>
/// <param name="vAlignement">Vertical alignement of the text.</param>
public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignement)
: this (str, fntFile, dimensions, hAlignment, vAlignement, CCPoint.Zero, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="hAlignment">Horizontal alignment of the text.</param>
/// <param name="vAlignment">Vertical alignement of the text.</param>
/// <param name="imageOffset">Image offset.</param>
/// <param name="texture">Texture Atlas to be used.</param>
public CCLabel(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
CCPoint imageOffset, CCTexture2D texture)
: this (str, fntFile, dimensions,
new CCLabelFormat() { Alignment = hAlignment, LineAlignment = vAlignment},
imageOffset, texture)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
public CCLabel(string str, string fntFile, CCSize dimensions, CCLabelFormat labelFormat)
: this(str, fntFile, dimensions, labelFormat, CCPoint.Zero, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
public CCLabel(string str, string fntFile, float size, CCLabelFormat labelFormat)
: this (str, fntFile, size, CCSize.Zero, labelFormat)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
public CCLabel(string str, string fntFile, float size, CCSize dimensions, CCLabelFormat labelFormat)
: this (str, fntFile, size, dimensions, labelFormat, CCPoint.Zero, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
/// <param name="imageOffset">Image offset.</param>
/// <param name="texture">Texture atlas to be used.</param>
public CCLabel(string str, string fntFile, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture)
: this (str, fntFile, 0.0f, dimensions, labelFormat, imageOffset, texture)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
public CCLabel(CCFontFNT fntFontConfig, string str, CCSize dimensions, CCLabelFormat labelFormat)
{
quadCommand = new CCQuadCommand(str.Length);
labelFormat.FormatFlags = CCLabelFormatFlags.BitmapFont;
AnchorPoint = CCPoint.AnchorMiddle;
try
{
FontAtlas = CCFontAtlasCache.SharedFontAtlasCache.GetFontAtlasFNT(fntFontConfig);
}
catch { }
if (FontAtlas == null)
{
CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check CCFontFNT file: ");
return;
}
LabelType = CCLabelType.BitMapFont;
this.labelFormat = labelFormat;
if (String.IsNullOrEmpty(str))
{
str = String.Empty;
}
// Initialize the TextureAtlas along with children.
var capacity = str.Length;
BlendFunc = CCBlendFunc.AlphaBlend;
if (capacity == 0)
{
capacity = defaultSpriteBatchCapacity;
}
UpdateBlendFunc();
// no lazy alloc in this node
Children = new CCRawList<CCNode>(capacity);
Descendants = new CCRawList<CCSprite>(capacity);
this.labelDimensions = dimensions;
horzAlignment = labelFormat.Alignment;
vertAlignment = labelFormat.LineAlignment;
IsOpacityCascaded = true;
// We use base here so we do not trigger an update internally.
base.ContentSize = CCSize.Zero;
IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
AnchorPoint = CCPoint.AnchorMiddle;
ImageOffset = CCPoint.Zero;
Text = str;
}
/// <summary>
/// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class.
/// </summary>
/// <param name="str">Initial text of the label.</param>
/// <param name="fntFile">Font definition file to use.</param>
/// <param name="size">Font point size.</param>
/// <param name="dimensions">Dimensions that the label should use to layout it's text.</param>
/// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param>
/// <param name="imageOffset">Image offset.</param>
/// <param name="texture">Texture atlas to be used.</param>
public CCLabel(string str, string fntFile, float size, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture)
{
quadCommand = new CCQuadCommand(str.Length);
this.labelFormat = (size == 0 && labelFormat.FormatFlags == CCLabelFormatFlags.Unknown)
? CCLabelFormat.BitMapFont
: labelFormat;
if (this.labelFormat.FormatFlags == CCLabelFormatFlags.Unknown)
{
// First we try loading BitMapFont
CCLog.Log("Label Format Unknown: Trying BitmapFont ...");
InitBMFont(str, fntFile, dimensions, labelFormat.Alignment, labelFormat.LineAlignment, imageOffset, texture);
// If we do not load a Bitmap Font then try a SpriteFont
if (FontAtlas == null)
{
CCLog.Log("Label Format Unknown: Trying SpriteFont ...");
InitSpriteFont(str, fntFile, size, dimensions, labelFormat, imageOffset, texture);
}
// If we do not load a Bitmap Font nor a SpriteFont then try the last time for a System Font
if (FontAtlas == null)
{
CCLog.Log("Label Format Unknown: Trying System Font ...");
LabelType = CCLabelType.SystemFont;
SystemFont = fntFile;
SystemFontSize = size;
Dimensions = dimensions;
AnchorPoint = CCPoint.AnchorMiddle;
BlendFunc = CCBlendFunc.AlphaBlend;
Text = str;
}
}
else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.BitmapFont)
{
// Initialize the BitmapFont
InitBMFont(str, fntFile, dimensions, labelFormat.Alignment, labelFormat.LineAlignment, imageOffset, texture);
}
else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.SpriteFont)
{
// Initialize the SpriteFont
InitSpriteFont(str, fntFile, size, dimensions, labelFormat, imageOffset, texture);
}
else if(this.labelFormat.FormatFlags == CCLabelFormatFlags.SystemFont)
{
LabelType = CCLabelType.SystemFont;
SystemFont = fntFile;
SystemFontSize = size;
Dimensions = dimensions;
AnchorPoint = CCPoint.AnchorMiddle;
BlendFunc = CCBlendFunc.AlphaBlend;
Text = str;
}
}
internal void Reset ()
{
systemFontDirty = false;
systemFont = "Helvetica";
systemFontSize = 12;
}
internal CCFontAtlas FontAtlas
{
get {return fontAtlas;}
set
{
if (value != fontAtlas)
{
fontAtlas = value;
if (reusedLetter == null)
{
reusedLetter = new CCSprite();
reusedLetter.IsColorModifiedByOpacity = isColorModifiedByOpacity;
reusedLetter.AnchorPoint = CCPoint.AnchorUpperLeft;
}
if (fontAtlas != null)
{
if (TextureAtlas != null)
Texture = FontAtlas.GetTexture(0);
else
TextureAtlas = new CCTextureAtlas(FontAtlas.GetTexture(0), defaultSpriteBatchCapacity);
quadCommand.Texture = TextureAtlas.Texture;
LineHeight = fontAtlas.CommonHeight;
IsDirty = true;
}
}
}
}
protected void InitBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
CCPoint imageOffset, CCTexture2D texture)
{
Debug.Assert(FontConfiguration == null, "re-init is no longer supported");
Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
"Invalid params for CCLabelBMFont");
if (!String.IsNullOrEmpty(fntFile))
{
try
{
FontAtlas = CCFontAtlasCache.SharedFontAtlasCache.GetFontAtlasFNT(fntFile, imageOffset);
}
catch {}
if (FontAtlas == null)
{
CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check file: '{0}'", fntFile);
return;
}
}
AnchorPoint = CCPoint.AnchorMiddle;
FontConfiguration = CCBMFontConfiguration.FontConfigurationWithFile(fntFile);
LabelType = CCLabelType.BitMapFont;
if (String.IsNullOrEmpty(theString))
{
theString = String.Empty;
}
// Initialize the TextureAtlas along with children.
var capacity = theString.Length;
BlendFunc = CCBlendFunc.AlphaBlend;
if (capacity == 0)
{
capacity = defaultSpriteBatchCapacity;
}
UpdateBlendFunc();
// no lazy alloc in this node
Children = new CCRawList<CCNode>(capacity);
Descendants = new CCRawList<CCSprite>(capacity);
this.labelDimensions = dimensions;
horzAlignment = hAlignment;
vertAlignment = vAlignment;
IsOpacityCascaded = true;
// We use base here so we do not trigger an update internally.
base.ContentSize = CCSize.Zero;
IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
AnchorPoint = CCPoint.AnchorMiddle;
ImageOffset = imageOffset;
Text = theString;
}
protected void InitSpriteFont(string theString, string fntFile, float fontSize, CCSize dimensions, CCLabelFormat labelFormat,
CCPoint imageOffset, CCTexture2D texture)
{
Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
"Invalid params for CCLabel SpriteFont");
if (!String.IsNullOrEmpty(fntFile))
{
try
{
FontAtlas = CCFontAtlasCache.SharedFontAtlasCache.GetFontAtlasSpriteFont(fntFile, fontSize, imageOffset);
Scale = FontAtlas.Font.FontScale;
}
catch {}
if (FontAtlas == null)
{
CCLog.Log("SpriteFont CCLabel: Impossible to create font. Please check file: '{0}'", fntFile);
return;
}
}
AnchorPoint = CCPoint.AnchorMiddle;
LabelType = CCLabelType.SpriteFont;
if (String.IsNullOrEmpty(theString))
{
theString = String.Empty;
}
// Initialize the TextureAtlas along with children.
var capacity = theString.Length;
BlendFunc = CCBlendFunc.AlphaBlend;
if (capacity == 0)
{
capacity = defaultSpriteBatchCapacity;
}
UpdateBlendFunc();
// no lazy alloc in this node
Children = new CCRawList<CCNode>(capacity);
Descendants = new CCRawList<CCSprite>(capacity);
this.labelDimensions = dimensions;
horzAlignment = labelFormat.Alignment;
vertAlignment = labelFormat.LineAlignment;
IsOpacityCascaded = true;
ContentSize = CCSize.Zero;
IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
AnchorPoint = CCPoint.AnchorMiddle;
ImageOffset = imageOffset;
Text = theString;
}
#endregion Constructors
public override void UpdateDisplayedColor(CCColor3B parentColor)
{
var displayedColor = CCColor3B.White;
displayedColor.R = (byte)(RealColor.R * parentColor.R / 255.0f);
displayedColor.G = (byte)(RealColor.G * parentColor.G / 255.0f);
displayedColor.B = (byte)(RealColor.B * parentColor.B / 255.0f);
base.UpdateDisplayedColor(displayedColor);
if (LabelType == CCLabelType.SystemFont && textSprite != null)
{
textSprite.UpdateDisplayedColor(displayedColor);
}
}
protected internal override void UpdateDisplayedOpacity(byte parentOpacity)
{
var displayedOpacity = (byte) (RealOpacity * parentOpacity / 255.0f);
base.UpdateDisplayedOpacity(displayedOpacity);
if (LabelType == CCLabelType.SystemFont && textSprite != null)
{
textSprite.UpdateDisplayedOpacity(displayedOpacity);
}
}
public override void UpdateColor()
{
if (TextureAtlas != null && !string.IsNullOrEmpty(labelText))
{
quadCommand.RequestUpdateQuads(UpdateColorCallback);
}
}
void UpdateColorCallback(ref CCV3F_C4B_T2F_Quad[] quads)
{
if (TextureAtlas == null)
{
return;
}
var color4 = new CCColor4B( DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, DisplayedOpacity );
// special opacity for premultiplied textures
if (IsColorModifiedByOpacity)
{
color4.R = (byte)(color4.R * DisplayedOpacity / 255.0f);
color4.G = (byte)(color4.G * DisplayedOpacity / 255.0f);
color4.B = (byte)(color4.B * DisplayedOpacity / 255.0f);
}
if (quads != null)
{
var totalQuads = quads.Length;
CCV3F_C4B_T2F_Quad quad;
for (int index = 0; index < totalQuads; ++index)
{
quad = quads[index];
quad.BottomLeft.Colors = color4;
quad.BottomRight.Colors = color4;
quad.TopLeft.Colors = color4;
quad.TopRight.Colors = color4;
TextureAtlas.UpdateQuad(ref quad, index);
}
}
}
public override bool IsColorModifiedByOpacity
{
get { return isColorModifiedByOpacity; }
set
{
if (isColorModifiedByOpacity != value)
{
isColorModifiedByOpacity = value;
UpdateColor();
}
}
}
bool isUpdatingContent = false;
protected void UpdateContent()
{
if (isUpdatingContent)
return;
isUpdatingContent = true;
if (string.IsNullOrEmpty(Text))
{
return;
}
if (FontAtlas != null)
{
LayoutLabel();
}
else
{
if (LabelType == CCLabelType.SystemFont)
{
var fontDefinition = new CCFontDefinition();
fontDefinition.FontName = systemFont;
fontDefinition.FontSize = systemFontSize;
fontDefinition.Alignment = labelFormat.Alignment;
fontDefinition.LineAlignment = labelFormat.LineAlignment;
fontDefinition.Dimensions = Dimensions;
fontDefinition.FontFillColor = DisplayedColor;
fontDefinition.FontAlpha = DisplayedOpacity;
fontDefinition.LineBreak = labelFormat.LineBreaking;
fontDefinition.isShouldAntialias = IsAntialiased;
CreateSpriteWithFontDefinition(fontDefinition);
}
}
IsDirty = false;
isUpdatingContent = false;
}
CCSprite textSprite = null;
void CreateSpriteWithFontDefinition(CCFontDefinition fontDefinition)
{
if (textSprite != null)
textSprite.RemoveFromParent();
var texture = CreateTextSprite(Text, fontDefinition);
textSprite = new CCSprite(texture);
textSprite.IsAntialiased = isAntialiased;
textSprite.BlendFunc = BlendFunc;
textSprite.AnchorPoint = CCPoint.AnchorLowerLeft;
base.ContentSize = textSprite.ContentSize;
base.AddChild(textSprite,0,TagInvalid);
textSprite.UpdateDisplayedColor(DisplayedColor);
textSprite.UpdateDisplayedOpacity(DisplayedOpacity);
}
protected void UpdateFont()
{
if (FontAtlas != null)
{
//CCFontAtlasCache.ReleaseFontAtlas(FontAtlas);
FontAtlas = null;
}
IsDirty = true;
systemFontDirty = false;
}
void UpdateQuads()
{
int index;
int lettersCount = lettersInfo.Count;
var contentScaleFactor = DefaultTexelToContentSizeRatios;
for (int ctr = 0; ctr < lettersCount; ++ctr)
{
var letterDef = lettersInfo[ctr].Definition;
if (letterDef.IsValidDefinition)
{
reusedRect = letterDef.Subrect;
reusedLetter.Texture = Texture;
// make sure we set AtlasIndex to not initialized here or first character does not display correctly
reusedLetter.AtlasIndex = CCMacros.CCSpriteIndexNotInitialized;
reusedLetter.TextureRectInPixels = reusedRect;
reusedLetter.ContentSize = reusedRect.Size / contentScaleFactor;
reusedLetter.Position = lettersInfo[ctr].Position;
index = TextureAtlas.TotalQuads;
var letterInfo = lettersInfo[ctr];
letterInfo.AtlasIndex = index;
lettersInfo[ctr] = letterInfo;
InsertGlyph(reusedLetter, index);
}
}
quadCommand.Quads = TextureAtlas.Quads.Elements;
quadCommand.QuadCount = TextureAtlas.Quads.Count;
}
const float MAX_BOUNDS = 8388608;
void LayoutLabel ()
{
if (FontAtlas == null || string.IsNullOrEmpty(Text))
{
ContentSize = CCSize.Zero;
return;
}
TextureAtlas.RemoveAllQuads();
Descendants.Clear();
lettersInfo.Clear();
FontAtlas.PrepareLetterDefinitions(Text);
var start = 0;
var typesetter = new CCTLTextLayout(this);
var length = Text.Length;
var insetBounds = labelDimensions;
var layoutAvailable = true;
if (insetBounds.Width <= 0)
{
insetBounds.Width = MAX_BOUNDS;
layoutAvailable = false;
}
if (insetBounds.Height <= 0)
{
insetBounds.Height = MAX_BOUNDS;
layoutAvailable = false;
}
var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width;
var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;
var scaleX = ScaleX;
var scaleY = ScaleY;
List<CCTLLine> lineList = new List<CCTLLine>();
var boundingSize = CCSize.Zero;
while (start < length)
{
// Now we ask the typesetter to break off a line for us.
// This also will take into account line feeds embedded in the text.
// Example: "This is text \n with a line feed embedded inside it"
int count = typesetter.SuggestLineBreak(start, insetBounds.Width);
var line = typesetter.GetLine(start, start + count);
lineList.Add(line);
if (line.Bounds.Width > boundingSize.Width)
boundingSize.Width = line.Bounds.Width;
boundingSize.Height += line.Bounds.Height;
start += count;
}
if (!layoutAvailable)
{
if (insetBounds.Width == MAX_BOUNDS)
{
insetBounds.Width = boundingSize.Width;
}
if (insetBounds.Height == MAX_BOUNDS)
{
insetBounds.Height = boundingSize.Height;
}
}
// Calculate our vertical starting position
var totalHeight = lineList.Count * LineHeight;
var nextFontPositionY = totalHeight;
if (layoutAvailable && labelDimensions.Height > 0)
{
var labelHeightPixel = labelDimensions.Height / scaleY * contentScaleFactorHeight;
if (totalHeight > labelHeightPixel)
{
int numLines = (int)(labelHeightPixel / LineHeight);
totalHeight = numLines * LineHeight;
}
switch (VerticalAlignment)
{
case CCVerticalTextAlignment.Top:
nextFontPositionY = labelHeightPixel;
break;
case CCVerticalTextAlignment.Center:
nextFontPositionY = (labelHeightPixel + totalHeight) * 0.5f;
break;
case CCVerticalTextAlignment.Bottom:
nextFontPositionY = totalHeight;
break;
default:
break;
}
}
var lineGlyphIndex = 0;
float longestLine = 0;
// Used for calculating overlapping on last line character
var lastCharWidth = 0.0f;
int lastCharAdvance = 0;
// Define our horizontal justification
var flushFactor = (float)HorizontalAlignment / (float)CCTextAlignment.Right;
// We now loop through all of our line's glyph runs
foreach (var line in lineList)
{
var gliphRun = line.GlyphRun;
var lineWidth = line.Bounds.Width * contentScaleFactorWidth;
var flushWidth = (layoutAvailable) ? insetBounds.Width / scaleX : boundingSize.Width;
var flush = line.PenOffsetForFlush(flushFactor, flushWidth) ;
foreach (var glyph in gliphRun)
{
var letterPosition = glyph.Position;
var letterDef = glyph.Definition;
lastCharWidth = letterDef.Width * contentScaleFactorWidth;
letterPosition.X += flush;
letterPosition.Y = (nextFontPositionY - letterDef.YOffset) / contentScaleFactorHeight;
var tmpInfo = new LetterInfo();
tmpInfo.Definition = letterDef;
tmpInfo.Position = letterPosition;
tmpInfo.ContentSize.Width = letterDef.Width;
tmpInfo.ContentSize.Height = letterDef.Height;
if (lineGlyphIndex >= lettersInfo.Count)
{
lettersInfo.Add(tmpInfo);
}
else
{
lettersInfo[lineGlyphIndex] = tmpInfo;
}
lineGlyphIndex++;
lastCharAdvance = (int)glyph.Definition.XAdvance;
}
// calculate our longest line which is used for calculating our ContentSize
if (lineWidth > longestLine)
longestLine = lineWidth;
nextFontPositionY -= LineHeight;
}
CCSize tmpSize;
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
// box
if(lastCharAdvance < lastCharWidth)
{
tmpSize.Width = longestLine - lastCharAdvance + lastCharWidth;
}
else
{
tmpSize.Width = longestLine;
}
tmpSize.Height = totalHeight;
if (labelDimensions.Height > 0)
{
tmpSize.Height = labelDimensions.Height * contentScaleFactorHeight;
}
// We use base here so we do not trigger an update internally.
base.ContentSize = tmpSize / CCLabel.DefaultTexelToContentSizeRatios;
lineList.Clear();
CCRect uvRect;
CCSprite letterSprite;
for (int c = 0; c < Children.Count; c++)
{
letterSprite = (CCSprite)Children[c];
if (letterSprite == null)
continue;
int tag = letterSprite.Tag;
if(tag >= length)
{
RemoveChild(letterSprite, true);
}
else if(tag >= 0)
{
uvRect = lettersInfo[tag].Definition.Subrect;
letterSprite.TextureRectInPixels = uvRect;
letterSprite.ContentSize = uvRect.Size;
}
}
UpdateQuads();
UpdateColor();
}
public new CCNode this[int letterIndex]
{
get
{
if (LabelType == CCLabelType.SystemFont)
{
return null;
}
if (IsDirty)
{
UpdateContent();
}
var contentScaleFactor = DefaultTexelToContentSizeRatios;
if (letterIndex < lettersInfo.Count)
{
var letter = lettersInfo[letterIndex];
if(! letter.Definition.IsValidDefinition)
return null;
var sp = (this.GetChildByTag(letterIndex)) as CCSprite;
if (sp == null)
{
var uvRect = letter.Definition.Subrect;
sp = new CCSprite(FontAtlas.GetTexture(letter.Definition.TextureID), uvRect);
// The calculations for untrimmed size already take into account the
// content scale factor so here we back it out or the sprite shows
// up with the incorrect ratio.
sp.UntrimmedSizeInPixels = uvRect.Size * contentScaleFactor;
// Calc position offset taking into account the content scale factor.
var offset = new CCSize((uvRect.Size.Width * 0.5f) / contentScaleFactor.Width,
(uvRect.Size.Height * 0.5f) / contentScaleFactor.Height);
// apply the offset to the letter position
sp.PositionX = letter.Position.X + offset.Width;
sp.PositionY = letter.Position.Y - offset.Height;
sp.Opacity = Opacity;
AddSpriteWithoutQuad(sp, letter.AtlasIndex, letterIndex);
}
return sp;
}
return null;
}
}
private void AddSpriteWithoutQuad(CCSprite child, int z, int aTag)
{
Debug.Assert(child != null, "Argument must be non-NULL");
// quad index is Z
child.AtlasIndex = z;
child.TextureAtlas = TextureAtlas;
int i = 0;
if (Descendants.Count > 0)
{
CCSprite[] elements = Descendants.Elements;
for (int j = 0, count = Descendants.Count; j < count; j++)
{
if (elements[i].AtlasIndex <= z)
{
++i;
}
}
}
Descendants.Insert(i, child);
base.AddChild(child, z, aTag);
}
#region Child management
public override void AddChild(CCNode child, int zOrder = 0, int tag = CCNode.TagInvalid)
{
Debug.Assert(false, "AddChild is not allowed on CCLabel");
}
private void InsertGlyph(CCSprite sprite, int atlasIndex)
{
Debug.Assert(sprite != null, "child should not be null");
if (TextureAtlas.TotalQuads == TextureAtlas.Capacity)
{
IncreaseAtlasCapacity();
}
sprite.AtlasIndex = atlasIndex;
sprite.TextureAtlas = TextureAtlas;
var quad = sprite.Quad;
TextureAtlas.InsertQuad(ref quad, atlasIndex);
sprite.UpdateLocalTransformedSpriteTextureQuads();
}
#endregion
protected void IncreaseAtlasCapacity()
{
// if we're going beyond the current TextureAtlas's capacity,
// all the previously initialized sprites will need to redo their texture coords
// this is likely computationally expensive
int quantity = (TextureAtlas.Capacity + 1) * 4 / 3;
CCLog.Log(string.Format(
"CocosSharp: CCLabel: resizing TextureAtlas capacity from [{0}] to [{1}].",
TextureAtlas.Capacity, quantity));
TextureAtlas.ResizeCapacity(quantity);
}
public override void Visit(ref CCAffineTransform parentWorldTransform)
{
if (!Visible || string.IsNullOrEmpty(Text))
{
return;
}
if (systemFontDirty)
{
UpdateFont();
}
if (IsDirty)
{
UpdateContent();
}
var worldTransform = CCAffineTransform.Identity;
var affineLocalTransform = AffineLocalTransform;
CCAffineTransform.Concat(ref affineLocalTransform, ref parentWorldTransform, out worldTransform);
if (textSprite != null)
textSprite.Visit(ref worldTransform);
else
VisitRenderer(ref worldTransform);
}
protected override void VisitRenderer(ref CCAffineTransform worldTransform)
{
// Optimization: Fast Dispatch
if (TextureAtlas == null || TextureAtlas.TotalQuads == 0)
{
return;
}
// Loop through each of our children nodes that may have actions attached.
foreach(CCSprite child in Children)
{
if (child.Tag >= 0)
{
child.UpdateLocalTransformedSpriteTextureQuads();
}
}
quadCommand.GlobalDepth = worldTransform.Tz;
quadCommand.WorldTransform = worldTransform;
Renderer.AddCommand(quadCommand);
}
}
}
| |
using Loon.Utils;
using Loon.Java;
namespace Loon.Core.Geom {
public class Point : Shape {
public class Point2i {
public int x;
public int y;
public Point2i() {
}
public Point2i(int x_0, int y_1) {
this.x = x_0;
this.y = y_1;
}
public Point2i(float x_0, float y_1) {
this.x = MathUtils.FromFloat(x_0);
this.y = MathUtils.FromFloat(y_1);
}
public Point2i(Point2i p) {
this.x = p.x;
this.y = p.y;
}
public bool Equals(int x_0, int y_1) {
return MathUtils.Equal(x_0, this.x) && MathUtils.Equal(y_1, this.y);
}
public int Length() {
return MathUtils.Sqrt(MathUtils.Mul(x, x) + MathUtils.Mul(y, y));
}
public void Negate() {
x = -x;
y = -y;
}
public void Offset(int x_0, int y_1) {
this.x += x_0;
this.y += y_1;
}
public void Set(int x_0, int y_1) {
this.x = x_0;
this.y = y_1;
}
public void Set(Point2i p) {
this.x = p.x;
this.y = p.y;
}
public int DistanceTo(Point2i p) {
int tx = this.x - p.x;
int ty = this.y - p.y;
return MathUtils
.Sqrt(MathUtils.Mul(tx, tx) + MathUtils.Mul(ty, ty));
}
public int DistanceTo(int x_0, int y_1) {
int tx = this.x - x_0;
int ty = this.y - y_1;
return MathUtils
.Sqrt(MathUtils.Mul(tx, tx) + MathUtils.Mul(ty, ty));
}
public override int GetHashCode()
{
return JavaRuntime.IdentityHashCode(this);
}
public int DistanceTo(Point2i p1, Point2i p2) {
int tx = p2.x - p1.x;
int ty = p2.y - p1.y;
int u = MathUtils.Div(
MathUtils.Mul(x - p1.x, tx) + MathUtils.Mul(y - p1.y, ty),
MathUtils.Mul(tx, tx) + MathUtils.Mul(ty, ty));
int ix = p1.x + MathUtils.Mul(u, tx);
int iy = p1.y + MathUtils.Mul(u, ty);
int dx = ix - x;
int dy = iy - y;
return MathUtils
.Sqrt(MathUtils.Mul(dx, dx) + MathUtils.Mul(dy, dy));
}
}
public int clazz;
public const int POINT_CONVEX = 1;
public const int POINT_CONCAVE = 2;
public Point(float x_0, float y_1) {
this.CheckPoints();
this.SetLocation(x_0, y_1);
this.type = ShapeType.POINT_SHAPE;
}
public Point(Point p) {
this.CheckPoints();
this.SetLocation(p);
this.type = ShapeType.POINT_SHAPE;
}
public override Shape Transform(Matrix transform) {
float[] result = new float[points.Length];
transform.Transform(points, 0, result, 0, points.Length / 2);
return new Point(points[0], points[1]);
}
protected internal override void CreatePoints() {
if (points == null) {
points = new float[2];
}
points[0] = GetX();
points[1] = GetY();
maxX = x;
maxY = y;
minX = x;
minY = y;
FindCenter();
CalculateRadius();
}
public override int GetHashCode()
{
return JavaRuntime.IdentityHashCode(this);
}
protected internal override void FindCenter() {
if (center == null) {
center = new float[2];
}
center[0] = points[0];
center[1] = points[1];
}
protected internal override void CalculateRadius() {
boundingCircleRadius = 0;
}
public void Set(int x_0, int y_1) {
this.x = x_0;
this.y = y_1;
}
public override void SetLocation(float x_0, float y_1) {
this.x = x_0;
this.y = y_1;
}
public void SetLocation(Point p) {
this.x = p.GetX();
this.y = p.GetY();
}
public void Translate(float dx, float dy) {
this.x += dx;
this.y += dy;
}
public void Translate(Point p) {
this.x += p.x;
this.y += p.y;
}
public void Untranslate(Point p) {
this.x -= p.x;
this.y -= p.y;
}
public int DistanceTo(Point p) {
int tx = (int) (this.x - p.x);
int ty = (int) (this.y - p.y);
return MathUtils.Sqrt(MathUtils.Mul(tx, tx) + MathUtils.Mul(ty, ty));
}
public int DistanceTo(int x_0, int y_1) {
int tx = (int) (this.x - x_0);
int ty = (int) (this.y - y_1);
return MathUtils.Sqrt(MathUtils.Mul(tx, tx) + MathUtils.Mul(ty, ty));
}
public void GetLocation(Point dest) {
dest.SetLocation(this.x, this.y);
}
public override bool Equals(object obj) {
Point p = (Point) obj;
if (p.x == this.x && p.y == this.y && p.clazz == this.clazz) {
return true;
} else {
return false;
}
}
}}
| |
//
// System.Net.RequestStream
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Net.Sockets;
using System;
using System.Runtime.InteropServices;
namespace HTTP.Net {
internal class RequestStream : Stream
{
byte [] buffer;
int offset;
int length;
long remaining_body;
bool disposed;
Stream stream;
internal RequestStream (Stream stream, byte [] buffer, int offset, int length)
: this (stream, buffer, offset, length, -1)
{
}
internal RequestStream (Stream stream, byte [] buffer, int offset, int length, long contentlength)
{
this.stream = stream;
this.buffer = buffer;
this.offset = offset;
this.length = length;
this.remaining_body = contentlength;
}
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return false; }
}
public override bool CanWrite {
get { return false; }
}
public override long Length {
get { throw new NotSupportedException (); }
}
public override long Position {
get { throw new NotSupportedException (); }
set { throw new NotSupportedException (); }
}
public override void Close ()
{
disposed = true;
}
public override void Flush ()
{
}
// Returns 0 if we can keep reading from the base stream,
// > 0 if we read something from the buffer.
// -1 if we had a content length set and we finished reading that many bytes.
int FillFromBuffer (byte [] buffer, int off, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (off < 0)
throw new ArgumentOutOfRangeException ("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
int len = buffer.Length;
if (off > len)
throw new ArgumentException ("destination offset is beyond array size");
if (off > len - count)
throw new ArgumentException ("Reading would overrun buffer");
if (this.remaining_body == 0)
return -1;
if (this.length == 0)
return 0;
int size = Math.Min (this.length, count);
if (this.remaining_body > 0)
size = (int) Math.Min (size, this.remaining_body);
if (this.offset > this.buffer.Length - size) {
size = Math.Min (size, this.buffer.Length - this.offset);
}
if (size == 0)
return 0;
Buffer.BlockCopy (this.buffer, this.offset, buffer, off, size);
this.offset += size;
this.length -= size;
if (this.remaining_body > 0)
remaining_body -= size;
return size;
}
public override int Read ([In,Out] byte[] buffer, int offset, int count)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
// Call FillFromBuffer to check for buffer boundaries even when remaining_body is 0
int nread = FillFromBuffer (buffer, offset, count);
if (nread == -1) { // No more bytes available (Content-Length)
return 0;
} else if (nread > 0) {
return nread;
}
nread = stream.Read (buffer, offset, count);
if (nread > 0 && remaining_body > 0)
remaining_body -= nread;
return nread;
}
public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
int nread = FillFromBuffer (buffer, offset, count);
if (nread > 0 || nread == -1) {
HttpStreamAsyncResult ares = new HttpStreamAsyncResult ();
ares.Buffer = buffer;
ares.Offset = offset;
ares.Count = count;
ares.Callback = cback;
ares.State = state;
ares.SynchRead = nread;
ares.Complete ();
return ares;
}
// Avoid reading past the end of the request to allow
// for HTTP pipelining
if (remaining_body >= 0 && count > remaining_body)
count = (int) Math.Min (Int32.MaxValue, remaining_body);
return stream.BeginRead (buffer, offset, count, cback, state);
}
public override int EndRead (IAsyncResult ares)
{
if (disposed)
throw new ObjectDisposedException (typeof (RequestStream).ToString ());
if (ares == null)
throw new ArgumentNullException ("async_result");
if (ares is HttpStreamAsyncResult) {
HttpStreamAsyncResult r = (HttpStreamAsyncResult) ares;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
return r.SynchRead;
}
// Close on exception?
int nread = stream.EndRead (ares);
if (remaining_body > 0 && nread > 0)
remaining_body -= nread;
return nread;
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
public override void Write (byte[] buffer, int offset, int count)
{
throw new NotSupportedException ();
}
public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
throw new NotSupportedException ();
}
public override void EndWrite (IAsyncResult async_result)
{
throw new NotSupportedException ();
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using NUnit.Framework;
using XenAdmin;
using System.Collections.Generic;
using System;
namespace XenAdminTests.UnitTests
{
[TestFixture, Category(TestCategories.Unit)]
internal class UtilTests
{
#region Test Data
private Dictionary<double, string[]> memoryMBpairs = new Dictionary<double, string[]>
{
{ 0, new[] { "0", "MB" } },
{ 1, new[] { "0", "MB" } },
{ 1024, new[] { "0", "MB" } },
{ 100000, new[] { "0", "MB" } },
{ 1048576, new[] { "1", "MB" } }, //1024*1024
{ 2100000, new[] { "2", "MB" } },
{ 2900000, new[] { "3", "MB" } },
{ 1073741824, new[] { "1024", "MB" } }, //1024*1024*1024
{ 2100000000, new[] { "2003", "MB" } }
};
private Dictionary<double, string[]> memoryVariousPairs = new Dictionary<double, string[]>
{
{ 0, new[] { "0", "B" } },
{ 1000, new[] { "1000", "B" } },
{ 1024, new[] { "1", "kB" } },
{ 100000, new[] { "98", "kB" } },
{ 1000000, new[] { "977", "kB" } },
{ 1048576, new[] { "1", "MB" } }, //1024*1024
{ 2100000, new[] { "2", "MB" } },
{ 2900000, new[] { "3", "MB" } },
{ 1073741824, new[] { "1", "GB" } }, //1024*1024*1024
{ 2100000000, new[] { "2", "GB" } },
{ 2900000000, new[] { "3", "GB" } }
};
private Dictionary<double, string[]> dataRatePairs = new Dictionary<double, string[]>
{
{ 0, new[] { "0", "B/s" } },
{ 1000, new[] { "1", "kB/s" } },
{ 1024, new[] { "1", "kB/s" } },
{ 100000, new[] { "100", "kB/s" } },
{ 1000000, new[] { "1", "MB/s" } }, //1000*1000
{ 1048576, new[] { "1", "MB/s" } }, //1024*1024
{ 2000000, new[] { "2", "MB/s" } }, //2*1000*1000
{ 2097152, new[] { "2.1", "MB/s" } }, //2*1024*1024
{ 2100000, new[] { "2.1", "MB/s" } }, //2.1*1000*1000
{ 2900000, new[] { "2.9", "MB/s" } }, //2.9*1000*1000
{ 1000000000, new[] { "1", "GB/s" } }, //1000*1000*1000
{ 1073741824, new[] { "1.1", "GB/s" } }, //1024*1024*1024
{ 2100000000, new[] { "2.1", "GB/s" } }, //2.1*1000*1000*1000
{ 2147483648, new[] { "2.1", "GB/s" } }, //2*1024*1024*1024
{ 2900000000, new[] { "2.9", "GB/s" } }, //2.9*1000*1000*1000
{ 1000000000000, new[] { "1", "TB/s" } }, //1000*1000*1000*1000
{ 1099511627776, new[] { "1.1", "TB/s" } }, //1024*1024*1024*1024
{ 2100000000000, new[] { "2.1", "TB/s" } }, //2.1*1000*1000*1000*1000
{ 2900000000000, new[] { "2.9", "TB/s" } }, //2.9*1000*1000*1000*1000
};
private Dictionary<double, string[]> nanoSecPairs = new Dictionary<double, string[]>
{
{ 0, new[] { "0", "ns" } },
{ 1, new[] { "1", "ns" } },
{ 1.1, new[] { "1", "ns" } },
{ 1.5, new[] { "2", "ns" } },
{ 1.9, new[] { "2", "ns" } },
{ 12, new[] { "12", "ns" } },
{ 1100, new[] { "1", '\u03bc'+"s" } },//greek mi
{ 1500, new[] { "2", '\u03bc'+"s" } },
{ 1900, new[] { "2", '\u03bc'+"s" } },
{ 1100000, new[] { "1", "ms" } },
{ 1500000, new[] { "2", "ms" } },
{ 1900000, new[] { "2", "ms" } },
{ 1100000000, new[] { "1", "s" } },
{ 2100000000, new[] { "2", "s" } },
{ 2900000000, new[] { "3", "s" } }
};
private Dictionary<long, string[]> diskSizeOneDpPairs = new Dictionary<long, string[]>
{
{ 0, new[] { "0", "B" } },
{ 1000, new[] { "1000", "B" } },
{ 1024, new[] { "1", "kB" } },
{ 100000, new[] { "97.7", "kB" } },
{ 1000000, new[] { "976.6", "kB" } },
{ 1048576, new[] { "1", "MB" } }, //1024*1024
{ 2100000, new[] { "2", "MB" } },
{ 2900000, new[] { "2.8", "MB" } },
{ 1073741824, new[] { "1", "GB" } }, //1024*1024*1024
{ 2100000000, new[] { "2", "GB" } },
{ 2900000000, new[] { "2.7", "GB" } }
};
#endregion
[Test]
public void TestMemorySizeStringSuitableUnits()
{
var pairs = new Dictionary<string[], string>
{
{ new [] {"1072693248", "false"}, "1023 MB"},
{ new [] {"1073741824", "false"}, "1 GB"},
{ new [] {"1073741824", "true"}, "1.0 GB"},
{ new [] {"1825361100.8", "false"}, "1.7 GB"},
{ new [] {"1825361100.8", "true"}, "1.7 GB"},
{ new [] {"536870912", "true"}, "512 MB"},
{ new [] {"537290342.4", "true"}, "512 MB"}
};
foreach(var pair in pairs)
Assert.AreEqual(pair.Value, Util.MemorySizeStringSuitableUnits(Convert.ToDouble(pair.Key[0]),Convert.ToBoolean(pair.Key[1])));
}
[Test]
public void TestMemorySizeStringVariousUnits()
{
foreach (var pair in memoryVariousPairs)
{
string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]);
Assert.AreEqual(expected, Util.MemorySizeStringVariousUnits(pair.Key));
}
}
[Test]
public void TestMemorySizeValueVariousUnits()
{
foreach (var pair in memoryVariousPairs)
{
string unit;
var value = Util.MemorySizeValueVariousUnits(pair.Key, out unit);
Assert.AreEqual(pair.Value[0], value);
Assert.AreEqual(pair.Value[1], unit);
}
}
[Test]
public void TestDataRateString()
{
foreach (var pair in dataRatePairs)
{
string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]);
Assert.AreEqual(expected, Util.DataRateString(pair.Key));
}
}
[Test]
public void TestDataRateValue()
{
foreach (var pair in dataRatePairs)
{
string unit;
var value = Util.DataRateValue(pair.Key, out unit);
Assert.AreEqual(pair.Value[0], value);
Assert.AreEqual(pair.Value[1], unit);
}
}
[Test]
public void TestDiskSizeStringUlong()
{
Assert.AreEqual("16777216 TB", Util.DiskSizeString(ulong.MaxValue));
}
[Test]
public void TestDiskSizeString()
{
foreach (var pair in diskSizeOneDpPairs)
{
string expected = string.Format("{0} {1}", pair.Value[0], pair.Value[1]);
Assert.AreEqual(expected, Util.DiskSizeString(pair.Key));
}
}
[Test]
public void TestDiskSizeStringWithoutUnits()
{
foreach (var pair in diskSizeOneDpPairs)
Assert.AreEqual(pair.Value[0], Util.DiskSizeStringWithoutUnits(pair.Key));
}
[Test]
public void TestDiskSizeStringVariousDp()
{
var pairs = new Dictionary<long[], string>
{
{ new[] { 0, 1L }, "0 B" },
{ new[] { 1000, 2L }, "1000 B" },
{ new[] { 1024, 3L }, "1 kB" },
{ new[] { 100000, 2L }, "97.66 kB" },
{ new[] { 1000000, 1L }, "976.6 kB" },
{ new[] { 1048576, 3L }, "1 MB" }, //1024*1024
{ new[] { 2100000, 3L }, "2.003 MB" },
{ new[] { 2900000, 2L }, "2.77 MB" },
{ new[] { 1073741824, 3L }, "1 GB" }, //1024*1024*1024
{ new[] { 2100000000, 3L }, "1.956 GB" }
};
foreach (var pair in pairs)
Assert.AreEqual(pair.Value, Util.DiskSizeString(pair.Key[0], (int)pair.Key[1]));
}
[Test]
public void TestNanoSecondsString()
{
foreach (var pair in nanoSecPairs)
{
string expected = string.Format("{0}{1}", pair.Value[0], pair.Value[1]);
Assert.AreEqual(expected, Util.NanoSecondsString(pair.Key));
}
}
[Test]
public void TestNanoSecondsValue()
{
foreach (var pair in nanoSecPairs)
{
string unit;
var value = Util.NanoSecondsValue(pair.Key, out unit);
Assert.AreEqual(pair.Value[0], value);
Assert.AreEqual(pair.Value[1], unit);
}
}
[Test]
public void TestCountsPerSecondString()
{
var pairs = new Dictionary<double, string>
{
{0,"0 /sec"},
{0.12,"0.12 /sec"},
{1234.56,"1234.56 /sec"}
};
foreach (var pair in pairs)
Assert.AreEqual(pair.Value, Util.CountsPerSecondString(pair.Key));
}
[Test]
public void TestPercentageString()
{
var pairs = new Dictionary<double, string>
{
{ 1, "100.0%" },
{ 0.12, "12.0%" },
{ 0.0121, "1.2%" },
{ 0.0125, "1.3%" },
{ 0.0129, "1.3%" }
};
foreach (var pair in pairs)
Assert.AreEqual(pair.Value, Util.PercentageString(pair.Key));
}
}
}
| |
//! \file ImageLFG.cs
//! \date 2018 Nov 06
//! \brief Leaf 16-color image format.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Leaf
{
internal class LfgMetaData : ImageMetaData
{
public byte Mode;
public byte KeyColor;
public int ImageSize;
}
[Export(typeof(ImageFormat))]
public class LfgFormat : ImageFormat
{
public override string Tag { get { return "LFG"; } }
public override string Description { get { return "Leaf image format"; } }
public override uint Signature { get { return 0x4641454C; } } // 'LEAFCODE'
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (0x30);
if (!header.AsciiEqual ("LEAFCODE"))
return null;
int x = header.ToInt16 (0x20);
int y = header.ToInt16 (0x22);
return new LfgMetaData {
Width = (uint)(header.ToInt16 (0x24) - x + 1) * 8,
Height = (uint)(header.ToInt16 (0x26) - y + 1),
OffsetX = x,
OffsetY = y,
BPP = 4,
Mode = header[0x28],
KeyColor = header[0x29],
ImageSize = header.ToInt32 (0x2C),
};
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new LfgReader (file, (LfgMetaData)info);
var pixels = reader.Unpack();
return ImageData.Create (info, reader.Format, reader.Palette, pixels, reader.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("LfgFormat.Write not implemented");
}
}
internal class LfgReader
{
IBinaryStream m_input;
byte[] m_output;
int m_mode;
int m_length;
int m_stride;
int m_height;
int m_key_color;
public PixelFormat Format { get { return PixelFormats.Indexed4; } }
public int Stride { get { return m_stride; } }
public BitmapPalette Palette { get; private set; }
public LfgReader (IBinaryStream input, LfgMetaData info)
{
m_input = input;
m_stride = (int)info.Width / 2;
m_height = (int)info.Height;
m_output = new byte[m_stride * m_height];
m_mode = info.Mode;
m_length = info.ImageSize;
m_key_color = info.KeyColor;
}
byte[] m_frame = new byte[0x1000];
public byte[] Unpack ()
{
m_input.Position = 8;
Palette = ReadPalette();
m_input.Position = 0x30;
int frame_pos = 0xFEE;
int dst = 0;
int x = 0, y = 0;
Action next_pixel;
if (1 == m_mode)
{
next_pixel = () => {
++dst;
if (++x >= m_stride)
{
x = 0;
dst = ++y * m_stride;
}
};
}
else
{
next_pixel = () => {
dst += m_stride;
if (++y >= m_height)
{
y = 0;
dst = ++x;
}
};
}
int pixel_count = 0;
int ctl = 0;
byte mask = 0;
while (pixel_count < m_length)
{
mask >>= 1;
if (0 == mask)
{
ctl = m_input.ReadUInt8();
mask = 0x80;
}
if ((ctl & mask) != 0)
{
byte color = ColorMap[m_input.ReadUInt8()];
m_frame[frame_pos++ & 0xFFF] = color;
m_output[dst] = color;
next_pixel();
++pixel_count;
}
else
{
int offset = m_input.ReadUInt16();
int count = (offset & 0xF) + 3;
offset >>= 4;
while (count --> 0 && pixel_count < m_length)
{
byte color = m_frame[offset++ & 0xFFF];
m_frame[frame_pos++ & 0xFFF] = color;
m_output[dst] = color;
next_pixel();
++pixel_count;
}
}
}
return m_output;
}
BitmapPalette ReadPalette ()
{
var color_data = new byte[0x18 * 2];
for (int i = 0; i < color_data.Length; i += 2)
{
byte c = m_input.ReadUInt8();
color_data[i ] = (byte)((c >> 4) * 0x11);
color_data[i+1] = (byte)((c & 0xF) * 0x11);
}
var colors = new Color[16];
int src = 0;
for (int i = 0; i < 16; ++i)
{
if (m_key_color == i)
colors[i] = Color.FromArgb (0, color_data[src], color_data[src+1], color_data[src+2]);
else
colors[i] = Color.FromRgb (color_data[src], color_data[src+1], color_data[src+2]);
src += 3;
}
// colors[15] = Color.FromRgb (0xFF, 0xFF, 0xFF);
return new BitmapPalette (colors);
}
static readonly byte[] ColorMap = {
0x00, 0x01, 0x10, 0x11, 0x02, 0x03, 0x12, 0x13, 0x20, 0x21, 0x30, 0x31, 0x22, 0x23, 0x32, 0x33,
0x04, 0x05, 0x14, 0x15, 0x06, 0x07, 0x16, 0x17, 0x24, 0x25, 0x34, 0x35, 0x26, 0x27, 0x36, 0x37,
0x40, 0x41, 0x50, 0x51, 0x42, 0x43, 0x52, 0x53, 0x60, 0x61, 0x70, 0x71, 0x62, 0x63, 0x72, 0x73,
0x44, 0x45, 0x54, 0x55, 0x46, 0x47, 0x56, 0x57, 0x64, 0x65, 0x74, 0x75, 0x66, 0x67, 0x76, 0x77,
0x08, 0x09, 0x18, 0x19, 0x0A, 0x0B, 0x1A, 0x1B, 0x28, 0x29, 0x38, 0x39, 0x2A, 0x2B, 0x3A, 0x3B,
0x0C, 0x0D, 0x1C, 0x1D, 0x0E, 0x0F, 0x1E, 0x1F, 0x2C, 0x2D, 0x3C, 0x3D, 0x2E, 0x2F, 0x3E, 0x3F,
0x48, 0x49, 0x58, 0x59, 0x4A, 0x4B, 0x5A, 0x5B, 0x68, 0x69, 0x78, 0x79, 0x6A, 0x6B, 0x7A, 0x7B,
0x4C, 0x4D, 0x5C, 0x5D, 0x4E, 0x4F, 0x5E, 0x5F, 0x6C, 0x6D, 0x7C, 0x7D, 0x6E, 0x6F, 0x7E, 0x7F,
0x80, 0x81, 0x90, 0x91, 0x82, 0x83, 0x92, 0x93, 0xA0, 0xA1, 0xB0, 0xB1, 0xA2, 0xA3, 0xB2, 0xB3,
0x84, 0x85, 0x94, 0x95, 0x86, 0x87, 0x96, 0x97, 0xA4, 0xA5, 0xB4, 0xB5, 0xA6, 0xA7, 0xB6, 0xB7,
0xC0, 0xC1, 0xD0, 0xD1, 0xC2, 0xC3, 0xD2, 0xD3, 0xE0, 0xE1, 0xF0, 0xF1, 0xE2, 0xE3, 0xF2, 0xF3,
0xC4, 0xC5, 0xD4, 0xD5, 0xC6, 0xC7, 0xD6, 0xD7, 0xE4, 0xE5, 0xF4, 0xF5, 0xE6, 0xE7, 0xF6, 0xF7,
0x88, 0x89, 0x98, 0x99, 0x8A, 0x8B, 0x9A, 0x9B, 0xA8, 0xA9, 0xB8, 0xB9, 0xAA, 0xAB, 0xBA, 0xBB,
0x8C, 0x8D, 0x9C, 0x9D, 0x8E, 0x8F, 0x9E, 0x9F, 0xAC, 0xAD, 0xBC, 0xBD, 0xAE, 0xAF, 0xBE, 0xBF,
0xC8, 0xC9, 0xD8, 0xD9, 0xCA, 0xCB, 0xDA, 0xDB, 0xE8, 0xE9, 0xF8, 0xF9, 0xEA, 0xEB, 0xFA, 0xFB,
0xCC, 0xCD, 0xDC, 0xDD, 0xCE, 0xCF, 0xDE, 0xDF, 0xEC, 0xED, 0xFC, 0xFD, 0xEE, 0xEF, 0xFE, 0xFF
};
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSAssert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
using LTAF.Engine;
using System.IO;
using System.Linq;
using Moq;
namespace LTAF.UnitTests.UI
{
[TestClass]
public class HtmlFormElementTest
{
private Mock<IBrowserCommandExecutorFactory> _commandExecutorFactory;
[TestInitialize]
public void Initialize()
{
_commandExecutorFactory = new Mock<IBrowserCommandExecutorFactory>();
ServiceLocator.BrowserCommandExecutorFactory = _commandExecutorFactory.Object;
ServiceLocator.ApplicationPathFinder = new ApplicationPathFinder("http://test");
}
[TestMethod]
public void WhenSubmit_ShouldSendSubmitCommand()
{
//arrange
var html = @"
<html>
<body>
<form id='form1'>
<input type='hidden' id='input1' value='thevalue' />
</form>
</body>
</html>";
MockCommandExecutor commandExecutor = new MockCommandExecutor();
_commandExecutorFactory.Setup(m => m.CreateBrowserCommandExecutor(It.IsAny<string>(), It.IsAny<HtmlPage>())).Returns(commandExecutor);
var testPage = new HtmlPage();
var document = HtmlElement.Create(html, testPage, false);
//act
var form = (HtmlFormElement)document.ChildElements.Find("form1");
form.Submit();
//assert
MSAssert.AreEqual("FormSubmit", commandExecutor.ExecutedCommands[0].Handler.ClientFunctionName);
MSAssert.AreEqual("FormSubmit", commandExecutor.ExecutedCommands[0].Description);
MSAssert.IsTrue(commandExecutor.ExecutedCommands[0].Handler.RequiresElementFound);
MSAssert.AreEqual("form1", commandExecutor.ExecutedCommands[0].Target.Id);
MSAssert.IsNull(commandExecutor.ExecutedCommands[0].Handler.Arguments);
}
[TestMethod]
public void BuildPostData_IfNoInputElementsExistReturnsEmpty()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.IsTrue(postData.Count == 0);
MSAssert.IsTrue(string.IsNullOrEmpty(postData.GetPostDataString()));
}
[TestMethod]
public void BuildPostData_ReturnsNameValuePairsForInputElements()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(2, postData.Count);
}
[TestMethod]
public void BuildPostData_UrlEncodesValueOfInputElements()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='val&ue1' />
<input type='text' name='input2' value='val>ue2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=val%26ue1&input2=val%3eue2", postData.GetPostDataString());
MSAssert.AreEqual(2, postData.Count);
}
[TestMethod]
public void IfFormContainsUnknownElements_BuildPostData_ShouldContainOnlyKnownElements()
{
//Arrange
string html = @"
<html>
<body>
<form id='form1' action='action' method='put'>
<input type='text' name='textbox1' value='textvalue' />
<input type='password' name='password1' value='passvalue' />
<input type='checkbox' name='checkbox1' value='checkvalue' />
<input type='radio' name='radio1' value='radiovalue' />
<input type='reset' name='reset1' value='resetvalue' />
<input type='file' name='file1' value='filevalue' />
<input type='hidden' name='hidden1' value='hiddenvalue' />
<input type='submit' name='button1' value='button1' />
<input type='search' name='search1' value='search1' />
<input type='tel' name='tel1' value='tel1' />
<input type='url' name='url1' value='url1' />
<input type='email' name='email1' value='email1' />
<input type='datetime' name='datetime1' value='datetime1' />
<input type='date' name='date1' value='10/10/1981' />
<input type='month' name='month1' value='month1' />
<input type='week' name='week1' value='week1' />
<input type='time' name='time1' value='time1' />
<input type='number' name='number1' value='11' />
</form>
</body>
</html>";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("textbox1=textvalue&password1=passvalue&file1=filevalue&hidden1=hiddenvalue&button1=button1&search1=search1&tel1=tel1&url1=url1&email1=email1&datetime1=datetime1&date1=10%2f10%2f1981&month1=month1&week1=week1&time1=time1&number1=11", postData.GetPostDataString());
MSAssert.AreEqual(15, postData.Count);
}
[TestMethod]
public void IfFormContainsDifferentInputElements_PostDataCollection_ShouldBeAbleToFilter()
{
//Arrange
string html = @"
<html>
<body>
<form id='form1' action='action' method='put'>
<input type='text' name='textbox1' value='textvalue' />
<input type='password' name='password1' value='passvalue' />
<input type='checkbox' name='checkbox1' value='checkvalue' />
<input type='radio' name='radio1' value='radiovalue' />
<input type='reset' name='reset1' value='resetvalue' />
<input type='file' name='file1' value='filevalue' />
<input type='file' name='file2' value='filevalue2' />
</form>
</body>
</html>";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("textbox1=textvalue&password1=passvalue", postData.GetPostDataString(PostDataFieldType.Text));
MSAssert.AreEqual(4, postData.Count);
MSAssert.AreEqual(2, postData.FindAll(e => (e.Type == PostDataFieldType.File)).Count());
}
[TestMethod]
public void WhenGetPostData_IfCheckboxPresentAndChecked_ShouldBeIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='checkbox' name='check1' checked />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&check1=on&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(3, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfCheckboxPresentAndUnchecked_ShouldNotIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='checkbox' name='check1' />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(2, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfElementIsDisabled_ShouldNotContainCheckboxInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='checkbox' name='check1' checked disabled />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(2, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfMultipleCheckboxesWithSameNamePresentAndChecked_ShouldBeIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='checkbox' name='check1' checked />
<input type='text' name='input2' value='value2' />
<input type='checkbox' name='check1' checked />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&check1=on&input2=value2&check1=on", postData.GetPostDataString());
MSAssert.AreEqual(4, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfMultipleCheckboxesWithSameNamePresentAndCheckedWithValue_ShouldValueBeIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='checkbox' name='check1' value='checkvalue1' checked />
<input type='text' name='input2' value='value2' />
<input type='checkbox' name='check1' value='checkvalue2' checked />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&check1=checkvalue1&input2=value2&check1=checkvalue2", postData.GetPostDataString());
MSAssert.AreEqual(4, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfRadioPresentAndChecked_ShouldBeIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='radio' name='check1' checked />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&check1=on&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(3, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfRadioPresentAndUnchecked_ShouldNotIncludeItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='radio' name='check1' />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(2, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfRadioPresentAndChecked_ShouldValueBeIncludItInPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='radio' name='check1' checked='checked' value='radiovalue' />
<input type='text' name='input2' value='value2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&check1=radiovalue&input2=value2", postData.GetPostDataString());
MSAssert.AreEqual(3, postData.Count);
}
[TestMethod]
public void WhenGetPostData_IfMultipleSubmitButtons_ShouldOnlyReturnTheOneThatInitiatedThePost()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
<input type='submit' name='submit2' value='submit2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
var inputElement = (HtmlInputElement)form.ChildElements.Find("submit2");
PostDataCollection postData = form.GetPostDataCollection(inputElement);
// Assert
MSAssert.AreEqual("input1=value1&submit2=submit2", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfMultipleSubmitButtonsWithSameName_ShouldOnlyReturnTheOneThatInitiatedThePost()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submitname' value='submit1' />
<input type='submit' name='submitname' value='submit2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
var inputElement = (HtmlInputElement)form.ChildElements.Find(new { value = "submit2" });
PostDataCollection postData = form.GetPostDataCollection(inputElement);
// Assert
MSAssert.AreEqual("input1=value1&submitname=submit2", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfMultipleSubmitButtonsAndNoSubmitId_ShouldReturnBothSubmitButtonData()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
<input type='submit' name='submit2' value='submit2' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&submit2=submit2", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasNoOptions_ShouldNotAddItToPostada()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1' />
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasNoSelectedOptions_ShouldNotAddItToPostada()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option value='option1value' />
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasSelectedOption_ShouldAddOptionsValueToPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option value='option1value' selected>option1text</option>
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&select1=option1value", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasSelectedOptionWithoutValue_ShouldAddOptionsTextToPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option selected>option1text</option>
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&select1=option1text", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasSelectedOptionWithNonStdSymbols_ShouldEncodeValue()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option selected>option1<text</option>
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&select1=option1%3ctext", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasMultipleSelectedOption_ShouldAddAllOptionsValuesToPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option value='option1value' selected>option1text</option>
<option value='option2value'>option2text</option>
<option value='option3value' selected>option3text</option>
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&select1=option1value&select1=option3value", postData.GetPostDataString());
}
[TestMethod]
public void WhenGetPostData_IfSelectHasMultipleSelectedOptionDifferentSelected_ShouldAddAllOptionsValuesToPostdata()
{
//Arrange
string html = @"
<html>
<form id='form1'>
<div>
<select name='select1'>
<option value='option1value' selected>option1text</option>
<option value='option2value' selected='true'>option2text</option>
<option value='option3value' selected='selected'>option3text</option>
</select>
<input type='text' name='input1' value='value1' />
<input type='submit' name='submit1' value='submit1' />
</div>
</form>
</html>
";
HtmlFormElement form = (HtmlFormElement)HtmlElement.Create(html).ChildElements.Find("form1");
//Act
PostDataCollection postData = form.GetPostDataCollection();
// Assert
MSAssert.AreEqual("input1=value1&submit1=submit1&select1=option1value&select1=option2value&select1=option3value", postData.GetPostDataString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Extensions;
using System.Xml.Schema;
// These classes provide a higher level view on reflection specific to
// Xml serialization, for example:
// - allowing one to talk about types w/o having them compiled yet
// - abstracting collections & arrays
// - abstracting classes, structs, interfaces
// - knowing about XSD primitives
// - dealing with Serializable and xmlelement
// and lots of other little details
internal enum TypeKind
{
Root,
Primitive,
Enum,
Struct,
Class,
Array,
Collection,
Enumerable,
Void,
Node,
Attribute,
Serializable
}
internal enum TypeFlags
{
None = 0x0,
Abstract = 0x1,
Reference = 0x2,
Special = 0x4,
CanBeAttributeValue = 0x8,
CanBeTextValue = 0x10,
CanBeElementValue = 0x20,
HasCustomFormatter = 0x40,
AmbiguousDataType = 0x80,
IgnoreDefault = 0x200,
HasIsEmpty = 0x400,
HasDefaultConstructor = 0x800,
XmlEncodingNotRequired = 0x1000,
UseReflection = 0x4000,
CollapseWhitespace = 0x8000,
OptionalValue = 0x10000,
CtorInaccessible = 0x20000,
UsePrivateImplementation = 0x40000,
GenericInterface = 0x80000,
Unsupported = 0x100000,
}
internal class TypeDesc
{
private string _name;
private string _fullName;
private string _cSharpName;
private TypeDesc _arrayElementTypeDesc;
private TypeDesc _arrayTypeDesc;
private TypeDesc _nullableTypeDesc;
private TypeKind _kind;
private XmlSchemaType _dataType;
private Type _type;
private TypeDesc _baseTypeDesc;
private TypeFlags _flags;
private string _formatterName;
private bool _isXsdType;
private bool _isMixed;
private int _weight;
private Exception _exception;
internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName)
{
_name = name.Replace('+', '.');
_fullName = fullName.Replace('+', '.');
_kind = kind;
_baseTypeDesc = baseTypeDesc;
_flags = flags;
_isXsdType = kind == TypeKind.Primitive;
if (_isXsdType)
_weight = 1;
else if (kind == TypeKind.Enum)
_weight = 2;
else if (_kind == TypeKind.Root)
_weight = -1;
else
_weight = baseTypeDesc == null ? 0 : baseTypeDesc.Weight + 1;
_dataType = dataType;
_formatterName = formatterName;
}
internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags)
: this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null)
{ }
internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags)
: this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName)
{
_isXsdType = isXsdType;
_type = type;
}
internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc)
: this(name, fullName, null, kind, baseTypeDesc, flags, null)
{
_arrayElementTypeDesc = arrayElementTypeDesc;
_type = type;
}
public override string ToString()
{
return _fullName;
}
internal TypeFlags Flags
{
get { return _flags; }
}
internal bool IsXsdType
{
get { return _isXsdType; }
}
internal bool IsMappedType
{
get { return false; }
}
internal string Name
{
get { return _name; }
}
internal string FullName
{
get { return _fullName; }
}
internal string CSharpName
{
get
{
if (_cSharpName == null)
{
_cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
}
return _cSharpName;
}
}
internal XmlSchemaType DataType
{
get { return _dataType; }
}
internal Type Type
{
get { return _type; }
}
internal string FormatterName
{
get { return _formatterName; }
}
internal TypeKind Kind
{
get { return _kind; }
}
internal bool IsValueType
{
get { return (_flags & TypeFlags.Reference) == 0; }
}
internal bool CanBeAttributeValue
{
get { return (_flags & TypeFlags.CanBeAttributeValue) != 0; }
}
internal bool XmlEncodingNotRequired
{
get { return (_flags & TypeFlags.XmlEncodingNotRequired) != 0; }
}
internal bool CanBeElementValue
{
get { return (_flags & TypeFlags.CanBeElementValue) != 0; }
}
internal bool CanBeTextValue
{
get { return (_flags & TypeFlags.CanBeTextValue) != 0; }
}
internal bool IsMixed
{
get { return _isMixed || CanBeTextValue; }
set { _isMixed = value; }
}
internal bool IsSpecial
{
get { return (_flags & TypeFlags.Special) != 0; }
}
internal bool IsAmbiguousDataType
{
get { return (_flags & TypeFlags.AmbiguousDataType) != 0; }
}
internal bool HasCustomFormatter
{
get { return (_flags & TypeFlags.HasCustomFormatter) != 0; }
}
internal bool HasDefaultSupport
{
get { return (_flags & TypeFlags.IgnoreDefault) == 0; }
}
internal bool HasIsEmpty
{
get { return (_flags & TypeFlags.HasIsEmpty) != 0; }
}
internal bool CollapseWhitespace
{
get { return (_flags & TypeFlags.CollapseWhitespace) != 0; }
}
internal bool HasDefaultConstructor
{
get { return (_flags & TypeFlags.HasDefaultConstructor) != 0; }
}
internal bool IsUnsupported
{
get { return (_flags & TypeFlags.Unsupported) != 0; }
}
internal bool IsGenericInterface
{
get { return (_flags & TypeFlags.GenericInterface) != 0; }
}
internal bool IsPrivateImplementation
{
get { return (_flags & TypeFlags.UsePrivateImplementation) != 0; }
}
internal bool CannotNew
{
get { return !HasDefaultConstructor || ConstructorInaccessible; }
}
internal bool IsAbstract
{
get { return (_flags & TypeFlags.Abstract) != 0; }
}
internal bool IsOptionalValue
{
get { return (_flags & TypeFlags.OptionalValue) != 0; }
}
internal bool UseReflection
{
get { return (_flags & TypeFlags.UseReflection) != 0; }
}
internal bool IsVoid
{
get { return _kind == TypeKind.Void; }
}
internal bool IsClass
{
get { return _kind == TypeKind.Class; }
}
internal bool IsStructLike
{
get { return _kind == TypeKind.Struct || _kind == TypeKind.Class; }
}
internal bool IsArrayLike
{
get { return _kind == TypeKind.Array || _kind == TypeKind.Collection || _kind == TypeKind.Enumerable; }
}
internal bool IsCollection
{
get { return _kind == TypeKind.Collection; }
}
internal bool IsEnumerable
{
get { return _kind == TypeKind.Enumerable; }
}
internal bool IsArray
{
get { return _kind == TypeKind.Array; }
}
internal bool IsPrimitive
{
get { return _kind == TypeKind.Primitive; }
}
internal bool IsEnum
{
get { return _kind == TypeKind.Enum; }
}
internal bool IsNullable
{
get { return !IsValueType; }
}
internal bool IsRoot
{
get { return _kind == TypeKind.Root; }
}
internal bool ConstructorInaccessible
{
get { return (_flags & TypeFlags.CtorInaccessible) != 0; }
}
internal Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
internal TypeDesc GetNullableTypeDesc(Type type)
{
if (IsOptionalValue)
return this;
if (_nullableTypeDesc == null)
{
_nullableTypeDesc = new TypeDesc("NullableOf" + _name, "System.Nullable`1[" + _fullName + "]", null, TypeKind.Struct, this, _flags | TypeFlags.OptionalValue, _formatterName);
_nullableTypeDesc._type = type;
}
return _nullableTypeDesc;
}
internal void CheckSupported()
{
if (IsUnsupported)
{
if (Exception != null)
{
throw Exception;
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName));
}
}
if (_baseTypeDesc != null)
_baseTypeDesc.CheckSupported();
if (_arrayElementTypeDesc != null)
_arrayElementTypeDesc.CheckSupported();
}
internal void CheckNeedConstructor()
{
if (!IsValueType && !IsAbstract && !HasDefaultConstructor)
{
_flags |= TypeFlags.Unsupported;
_exception = new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, FullName));
}
}
internal TypeDesc ArrayElementTypeDesc
{
get { return _arrayElementTypeDesc; }
set { _arrayElementTypeDesc = value; }
}
internal int Weight
{
get { return _weight; }
}
internal TypeDesc CreateArrayTypeDesc()
{
if (_arrayTypeDesc == null)
_arrayTypeDesc = new TypeDesc(null, _name + "[]", _fullName + "[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
return _arrayTypeDesc;
}
internal TypeDesc BaseTypeDesc
{
get { return _baseTypeDesc; }
set
{
_baseTypeDesc = value;
_weight = _baseTypeDesc == null ? 0 : _baseTypeDesc.Weight + 1;
}
}
internal bool IsDerivedFrom(TypeDesc baseTypeDesc)
{
TypeDesc typeDesc = this;
while (typeDesc != null)
{
if (typeDesc == baseTypeDesc) return true;
typeDesc = typeDesc.BaseTypeDesc;
}
return baseTypeDesc.IsRoot;
}
internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs)
{
if (typeDescs.Length == 0) return null;
TypeDesc leastDerivedTypeDesc = null;
int leastDerivedLevel = int.MaxValue;
for (int i = 0; i < typeDescs.Length; i++)
{
int derivationLevel = typeDescs[i].Weight;
if (derivationLevel < leastDerivedLevel)
{
leastDerivedLevel = derivationLevel;
leastDerivedTypeDesc = typeDescs[i];
}
}
while (leastDerivedTypeDesc != null)
{
int i;
for (i = 0; i < typeDescs.Length; i++)
{
if (!typeDescs[i].IsDerivedFrom(leastDerivedTypeDesc)) break;
}
if (i == typeDescs.Length) break;
leastDerivedTypeDesc = leastDerivedTypeDesc.BaseTypeDesc;
}
return leastDerivedTypeDesc;
}
}
internal class TypeScope
{
private Hashtable _typeDescs = new Hashtable();
private Hashtable _arrayTypeDescs = new Hashtable();
private ArrayList _typeMappings = new ArrayList();
private static Hashtable s_primitiveTypes = new Hashtable();
private static Hashtable s_primitiveDataTypes = new Hashtable();
private static NameTable s_primitiveNames = new NameTable();
private static string[] s_unsupportedTypes = new string[] {
"anyURI",
"duration",
"ENTITY",
"ENTITIES",
"gDay",
"gMonth",
"gMonthDay",
"gYear",
"gYearMonth",
"ID",
"IDREF",
"IDREFS",
"integer",
"language",
"negativeInteger",
"nonNegativeInteger",
"nonPositiveInteger",
//"normalizedString",
"NOTATION",
"positiveInteger",
"token"
};
static TypeScope()
{
AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(sbyte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(ushort), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(uint), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(ulong), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambiguous)
AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
// NOTE, Micorosft: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we
// can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or
// [XmlArrayItem].
XmlSchemaPatternFacet guidPattern = new XmlSchemaPatternFacet();
guidPattern.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[] { guidPattern }, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), Array.Empty<XmlSchemaFacet>(), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(TimeSpan), "TimeSpan", UrtTypes.Namespace, "TimeSpan", new XmlQualifiedName("duration", XmlSchema.Namespace), Array.Empty<XmlSchemaFacet>(), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedTypes(Soap.Encoding);
// Unsuppoted types that we map to string, if in the future we decide
// to add support for them we would need to create custom formatters for them
// normalizedString is the only one unsupported type that suppose to preserve whitesapce
AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddPrimitive(typeof(string), s_unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
}
internal static bool IsKnownType(Type type)
{
if (type == typeof(object))
return true;
if (type.IsEnum)
return false;
switch (type.GetTypeCode())
{
case TypeCode.String: return true;
case TypeCode.Int32: return true;
case TypeCode.Boolean: return true;
case TypeCode.Int16: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
case TypeCode.Decimal: return true;
case TypeCode.DateTime: return true;
case TypeCode.Byte: return true;
case TypeCode.SByte: return true;
case TypeCode.UInt16: return true;
case TypeCode.UInt32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Char: return true;
default:
if (type == typeof(XmlQualifiedName))
return true;
else if (type == typeof(byte[]))
return true;
else if (type == typeof(Guid))
return true;
else if (type == typeof(TimeSpan))
return true;
else if (type == typeof(XmlNode[]))
return true;
break;
}
return false;
}
private static void AddSoapEncodedTypes(string ns)
{
AddSoapEncodedPrimitive(typeof(string), "normalizedString", ns, "String", new XmlQualifiedName("normalizedString", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddSoapEncodedPrimitive(typeof(string), s_unsupportedTypes[i], ns, "String", new XmlQualifiedName(s_unsupportedTypes[i], XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
AddSoapEncodedPrimitive(typeof(string), "string", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(int), "int", ns, "Int32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(bool), "boolean", ns, "Boolean", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(short), "short", ns, "Int16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(long), "long", ns, "Int64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(float), "float", ns, "Single", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(double), "double", ns, "Double", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(decimal), "decimal", ns, "Decimal", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "dateTime", ns, "DateTime", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(XmlQualifiedName), "QName", ns, "XmlQualifiedName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte), "unsignedByte", ns, "Byte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(sbyte), "byte", ns, "SByte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(ushort), "unsignedShort", ns, "UInt16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(uint), "unsignedInt", ns, "UInt32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(ulong), "unsignedLong", ns, "UInt64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambigous)
AddSoapEncodedPrimitive(typeof(DateTime), "date", ns, "Date", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "time", ns, "Time", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "Name", ns, "XmlName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NCName", ns, "XmlNCName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKEN", ns, "XmlNmToken", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKENS", ns, "XmlNmTokens", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte[]), "base64Binary", ns, "ByteArrayBase64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(byte[]), "hexBinary", ns, "ByteArrayHex", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "arrayCoordinate", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue);
AddSoapEncodedPrimitive(typeof(byte[]), "base64", ns, "ByteArrayBase64", new XmlQualifiedName("base64Binary", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.IgnoreDefault | TypeFlags.Reference);
}
private static void AddPrimitive(Type type, string dataTypeName, string formatterName, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
TypeDesc typeDesc = new TypeDesc(type, true, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, XmlSchema.Namespace, typeDesc);
}
private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = baseTypeName;
foreach (XmlSchemaFacet facet in facets)
{
restriction.Facets.Add(facet);
}
dataType.Content = restriction;
TypeDesc typeDesc = new TypeDesc(type, false, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, ns, typeDesc);
}
private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, TypeFlags flags)
{
AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, Array.Empty<XmlSchemaFacet>(), flags);
}
internal TypeDesc GetTypeDesc(string name, string ns)
{
return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
}
internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags)
{
TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns];
if (typeDesc != null)
{
if ((typeDesc.Flags & flags) != 0)
{
return typeDesc;
}
}
return null;
}
internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType)
{
return (TypeDesc)s_primitiveDataTypes[dataType];
}
internal TypeDesc GetTypeDesc(Type type)
{
return GetTypeDesc(type, null, true, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference)
{
return GetTypeDesc(type, source, directReference, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError)
{
if (type.ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type));
}
TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type];
if (typeDesc == null)
{
typeDesc = (TypeDesc)_typeDescs[type];
if (typeDesc == null)
{
typeDesc = ImportTypeDesc(type, source, directReference);
}
}
if (throwOnError)
typeDesc.CheckSupported();
return typeDesc;
}
internal TypeDesc GetArrayTypeDesc(Type type)
{
TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type];
if (typeDesc == null)
{
typeDesc = GetTypeDesc(type);
if (!typeDesc.IsArrayLike)
typeDesc = ImportTypeDesc(type, null, false);
typeDesc.CheckSupported();
_arrayTypeDescs.Add(type, typeDesc);
}
return typeDesc;
}
#if !FEATURE_SERIALIZATION_UAPAOT
internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc)
{
foreach (TypeMapping typeMapping in TypeMappings)
{
if (typeMapping.TypeDesc == typeDesc)
return typeMapping;
}
return null;
}
internal Type GetTypeFromTypeDesc(TypeDesc typeDesc)
{
if (typeDesc.Type != null)
return typeDesc.Type;
foreach (DictionaryEntry de in _typeDescs)
{
if (de.Value == typeDesc)
return de.Key as Type;
}
return null;
}
#endif
private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
{
TypeDesc typeDesc = null;
TypeKind kind;
Type arrayElementType = null;
Type baseType = null;
TypeFlags flags = 0;
Exception exception = null;
if (!type.IsVisible)
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName));
}
else if (directReference && (type.IsAbstract && type.IsSealed))
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName));
}
if (DynamicAssemblies.IsTypeDynamic(type))
{
flags |= TypeFlags.UseReflection;
}
if (!type.IsValueType)
flags |= TypeFlags.Reference;
if (type == typeof(object))
{
kind = TypeKind.Root;
flags |= TypeFlags.HasDefaultConstructor;
}
else if (type == typeof(ValueType))
{
kind = TypeKind.Enum;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type == typeof(void))
{
kind = TypeKind.Void;
}
else if (typeof(IXmlSerializable).IsAssignableFrom(type))
{
kind = TypeKind.Serializable;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue;
flags |= GetConstructorFlags(type, ref exception);
}
else if (type.IsArray)
{
kind = TypeKind.Array;
if (type.GetArrayRank() > 1)
{
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
}
}
arrayElementType = type.GetElementType();
flags |= TypeFlags.HasDefaultConstructor;
}
else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type))
{
kind = TypeKind.Collection;
arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name);
flags |= GetConstructorFlags(type, ref exception);
}
else if (type == typeof(XmlQualifiedName))
{
kind = TypeKind.Primitive;
}
else if (type.IsPrimitive)
{
kind = TypeKind.Primitive;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type.IsEnum)
{
kind = TypeKind.Enum;
}
else if (type.IsValueType)
{
kind = TypeKind.Struct;
if (IsOptionalValue(type))
{
baseType = type.GetGenericArguments()[0];
flags |= TypeFlags.OptionalValue;
}
else
{
baseType = type.BaseType;
}
if (type.IsAbstract) flags |= TypeFlags.Abstract;
}
else if (type.IsClass)
{
if (type == typeof(XmlAttribute))
{
kind = TypeKind.Attribute;
flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue;
}
else if (typeof(XmlNode).IsAssignableFrom(type))
{
kind = TypeKind.Node;
baseType = type.BaseType;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue;
if (typeof(XmlText).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeElementValue;
else if (typeof(XmlElement).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeTextValue;
else if (type.IsAssignableFrom(typeof(XmlAttribute)))
flags |= TypeFlags.CanBeAttributeValue;
}
else
{
kind = TypeKind.Class;
baseType = type.BaseType;
if (type.IsAbstract)
flags |= TypeFlags.Abstract;
}
}
else if (type.IsInterface)
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
if (memberInfo == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName));
}
else
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName));
}
}
}
else
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
// check to see if the type has public default constructor for classes
if (kind == TypeKind.Class && !type.IsAbstract)
{
flags |= GetConstructorFlags(type, ref exception);
}
// check if a struct-like type is enumerable
if (kind == TypeKind.Struct || kind == TypeKind.Class)
{
if (typeof(IEnumerable).IsAssignableFrom(type) && !IsArraySegment(type))
{
arrayElementType = GetEnumeratorElementType(type, ref flags);
kind = TypeKind.Enumerable;
// GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property,
// we need to check the MoveNext() and ctor methods for the security attribues
flags |= GetConstructorFlags(type, ref exception);
}
}
typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null);
typeDesc.Exception = exception;
if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable))
typeDesc.CheckNeedConstructor();
if (typeDesc.IsUnsupported)
{
// return right away, do not check anything else
return typeDesc;
}
_typeDescs.Add(type, typeDesc);
if (arrayElementType != null)
{
TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false);
// explicitly disallow read-only elements, even if they are collections
if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive)
{
td.CheckNeedConstructor();
}
typeDesc.ArrayElementTypeDesc = td;
}
if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType))
{
typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false);
}
if (type.IsNestedPublic)
{
for (Type t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType)
GetTypeDesc(t, null, false);
}
return typeDesc;
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
internal static bool IsOptionalValue(Type type)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
return true;
}
return false;
}
/*
static string GetHash(string str) {
MD5 md5 = MD5.Create();
string hash = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0, 6).Replace("+", "_P").Replace("/", "_S");
return hash;
}
*/
internal static string TypeName(Type t)
{
if (t.IsArray)
{
return "ArrayOf" + TypeName(t.GetElementType());
}
else if (t.IsGenericType)
{
StringBuilder typeName = new StringBuilder();
StringBuilder ns = new StringBuilder();
string name = t.Name;
int arity = name.IndexOf("`", StringComparison.Ordinal);
if (arity >= 0)
{
name = name.Substring(0, arity);
}
typeName.Append(name);
typeName.Append("Of");
Type[] arguments = t.GetGenericArguments();
for (int i = 0; i < arguments.Length; i++)
{
typeName.Append(TypeName(arguments[i]));
ns.Append(arguments[i].Namespace);
}
/*
if (ns.Length > 0) {
typeName.Append("_");
typeName.Append(GetHash(ns.ToString()));
}
*/
return typeName.ToString();
}
return t.Name;
}
internal static Type GetArrayElementType(Type type, string memberInfo)
{
if (type.IsArray)
return type.GetElementType();
else if (IsArraySegment(type))
return null;
else if (typeof(ICollection).IsAssignableFrom(type))
return GetCollectionElementType(type, memberInfo);
else if (typeof(IEnumerable).IsAssignableFrom(type))
{
TypeFlags flags = TypeFlags.None;
return GetEnumeratorElementType(type, ref flags);
}
else
return null;
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping)
{
if (mapping.BaseMapping == null)
return mapping.Members;
ArrayList list = new ArrayList();
GetAllMembers(mapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
internal static void GetAllMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetAllMembers(mapping.BaseMapping, list);
}
for (int i = 0; i < mapping.Members.Length; i++)
{
list.Add(mapping.Members[i]);
}
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetAllMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
internal static MemberMapping[] GetSettableMembers(StructMapping structMapping)
{
ArrayList list = new ArrayList();
GetSettableMembers(structMapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
private static void GetSettableMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetSettableMembers(mapping.BaseMapping, list);
}
if (mapping.Members != null)
{
foreach (MemberMapping memberMapping in mapping.Members)
{
MemberInfo memberInfo = memberMapping.MemberInfo;
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc))
{
throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name));
}
list.Add(memberMapping);
}
}
}
private static bool CanWriteProperty(PropertyInfo propertyInfo, TypeDesc typeDesc)
{
Debug.Assert(propertyInfo != null);
Debug.Assert(typeDesc != null);
// If the property is a collection, we don't need a setter.
if (typeDesc.Kind == TypeKind.Collection || typeDesc.Kind == TypeKind.Enumerable)
{
return true;
}
// Else the property needs a public setter.
return propertyInfo.SetMethod != null && propertyInfo.SetMethod.IsPublic;
}
internal static MemberMapping[] GetSettableMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetSettableMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
private static void PopulateMemberInfos(StructMapping structMapping, MemberMapping[] mappings, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
memberInfos.Clear();
for (int i = 0; i < mappings.Length; ++i)
{
memberInfos[mappings[i].Name] = mappings[i].MemberInfo;
if (mappings[i].ChoiceIdentifier != null)
memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo;
if (mappings[i].CheckSpecifiedMemberInfo != null)
memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo;
}
// The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B.
// There's one virtual property defined in A and overridden by B. Without the replacing logic below, the code generated will always
// try to access the property defined in A, rather than B.
// The logic here is to:
// 1) Check current members inside memberInfos dictionary and figure out whether there's any override or new properties defined in the derived class.
// If so, replace the one on the base class with the one on the derived class.
// 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced
// by the StructMapping of the baseclass, so updating it directly could lead to other issues.
Dictionary<string, MemberInfo> replaceList = null;
MemberInfo replacedInfo = null;
foreach (KeyValuePair<string, MemberInfo> pair in memberInfos)
{
if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo))
{
if (replaceList == null)
{
replaceList = new Dictionary<string, MemberInfo>();
}
replaceList.Add(pair.Key, replacedInfo);
}
}
if (replaceList != null)
{
foreach (KeyValuePair<string, MemberInfo> pair in replaceList)
{
memberInfos[pair.Key] = pair.Value;
}
for (int i = 0; i < mappings.Length; i++)
{
if (replaceList.TryGetValue(mappings[i].Name, out MemberInfo mi))
{
MemberMapping newMapping = mappings[i].Clone();
newMapping.MemberInfo = mi;
mappings[i] = newMapping;
}
}
}
}
private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type derivedType, out MemberInfo replacedInfo)
{
replacedInfo = memberInfoToBeReplaced;
Type currentType = derivedType;
Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType;
if (typeToBeReplaced.IsAssignableFrom(currentType))
{
while (currentType != typeToBeReplaced)
{
TypeInfo currentInfo = currentType.GetTypeInfo();
foreach (PropertyInfo info in currentInfo.DeclaredProperties)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: property names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
if (!info.GetMethod.IsPublic
&& memberInfoToBeReplaced is PropertyInfo
&& ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic
)
{
break;
}
return true;
}
}
}
foreach (FieldInfo info in currentInfo.DeclaredFields)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: field names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
return true;
}
}
}
// we go one level down and try again
currentType = currentType.BaseType;
}
}
return false;
}
private static TypeFlags GetConstructorFlags(Type type, ref Exception exception)
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
if (ctor != null)
{
TypeFlags flags = TypeFlags.HasDefaultConstructor;
if (!ctor.IsPublic)
flags |= TypeFlags.CtorInaccessible;
else
{
object[] attrs = ctor.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (attrs != null && attrs.Length > 0)
{
ObsoleteAttribute obsolete = (ObsoleteAttribute)attrs[0];
if (obsolete.IsError)
{
flags |= TypeFlags.CtorInaccessible;
}
}
}
return flags;
}
return 0;
}
private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags)
{
if (typeof(IEnumerable).IsAssignableFrom(type))
{
MethodInfo enumerator = type.GetMethod("GetEnumerator", Array.Empty<Type>());
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// try generic implementation
enumerator = null;
foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
enumerator = member as MethodInfo;
if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// use the first one we find
flags |= TypeFlags.GenericInterface;
break;
}
else
{
enumerator = null;
}
}
if (enumerator == null)
{
// and finally private interface implementation
flags |= TypeFlags.UsePrivateImplementation;
enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
}
}
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
return null;
}
XmlAttributes methodAttrs = new XmlAttributes(enumerator);
if (methodAttrs.XmlIgnore) return null;
PropertyInfo p = enumerator.ReturnType.GetProperty("Current");
Type currentType = (p == null ? typeof(object) : p.PropertyType);
MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType });
if (addMethod == null && currentType != typeof(object))
{
currentType = typeof(object);
addMethod = type.GetMethod("Add", new Type[] { currentType });
}
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable"));
}
return currentType;
}
else
{
return null;
}
}
internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo)
{
if (typeof(IDictionary).IsAssignableFrom(type))
{
if (memberInfo == null)
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionary, type.FullName));
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionaryDetails, memberInfo, type.FullName));
}
}
MemberInfo[] defaultMembers = type.GetDefaultMembers();
PropertyInfo indexer = null;
if (defaultMembers != null && defaultMembers.Length > 0)
{
for (Type t = type; t != null; t = t.BaseType)
{
for (int i = 0; i < defaultMembers.Length; i++)
{
if (defaultMembers[i] is PropertyInfo)
{
PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i];
if (defaultProp.DeclaringType != t) continue;
if (!defaultProp.CanRead) continue;
MethodInfo getMethod = defaultProp.GetMethod;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
{
indexer = defaultProp;
break;
}
}
}
if (indexer != null) break;
}
}
if (indexer == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName));
}
MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType });
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection"));
}
return indexer;
}
private static Type GetCollectionElementType(Type type, string memberInfo)
{
return GetDefaultIndexer(type, memberInfo).PropertyType;
}
internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent)
{
string ns;
string name;
int nsLen = type.LastIndexOf(':');
if (nsLen <= 0)
{
ns = "";
}
else
{
ns = type.Substring(0, nsLen);
}
int nameLen = type.IndexOf('[', nsLen + 1);
if (nameLen <= nsLen)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayTypeSyntax, type));
}
name = type.Substring(nsLen + 1, nameLen - nsLen - 1);
dims = type.Substring(nameLen);
// parent is not null only in the case when we used XmlSchema.Read(),
// in which case we need to fixup the wsdl:arayType attribute value
while (parent != null)
{
if (parent.Namespaces != null)
{
if (parent.Namespaces.Namespaces.TryGetValue(ns, out string wsdlNs) && wsdlNs != null)
{
ns = wsdlNs;
break;
}
}
parent = parent.Parent;
}
return new XmlQualifiedName(name, ns);
}
internal ICollection Types
{
get { return _typeDescs.Keys; }
}
internal void AddTypeMapping(TypeMapping typeMapping)
{
_typeMappings.Add(typeMapping);
}
internal ICollection TypeMappings
{
get { return _typeMappings; }
}
internal static Hashtable PrimtiveTypes { get { return s_primitiveTypes; } }
}
internal class Soap
{
private Soap() { }
internal const string Encoding = "http://schemas.xmlsoap.org/soap/encoding/";
internal const string UrType = "anyType";
internal const string Array = "Array";
internal const string ArrayType = "arrayType";
}
internal class Soap12
{
private Soap12() { }
internal const string Encoding = "http://www.w3.org/2003/05/soap-encoding";
internal const string RpcNamespace = "http://www.w3.org/2003/05/soap-rpc";
internal const string RpcResult = "result";
}
internal class Wsdl
{
private Wsdl() { }
internal const string Namespace = "http://schemas.xmlsoap.org/wsdl/";
internal const string ArrayType = "arrayType";
}
internal class UrtTypes
{
private UrtTypes() { }
internal const string Namespace = "http://microsoft.com/wsdl/types/";
}
}
| |
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.PDF417.Internal.EC
{
/// <summary>
/// <see cref="com.google.zxing.common.reedsolomon.GenericGFPoly"/>
/// </summary>
/// <author>Sean Owen</author>
public sealed class ModulusPoly
{
private readonly ModulusGF field;
private readonly int[] coefficients;
public ModulusPoly(ModulusGF field, int[] coefficients)
{
if (coefficients.Length == 0)
{
throw new ArgumentException();
}
this.field = field;
int coefficientsLength = coefficients.Length;
if (coefficientsLength > 1 && coefficients[0] == 0)
{
// Leading term must be non-zero for anything except the constant polynomial "0"
int firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0)
{
firstNonZero++;
}
if (firstNonZero == coefficientsLength)
{
this.coefficients = field.Zero.coefficients;
}
else
{
this.coefficients = new int[coefficientsLength - firstNonZero];
Array.Copy(coefficients,
firstNonZero,
this.coefficients,
0,
this.coefficients.Length);
}
}
else
{
this.coefficients = coefficients;
}
}
/// <summary>
/// Gets the coefficients.
/// </summary>
/// <value>The coefficients.</value>
internal int[] Coefficients
{
get { return coefficients; }
}
/// <summary>
/// degree of this polynomial
/// </summary>
internal int Degree
{
get
{
return coefficients.Length - 1;
}
}
/// <summary>
/// Gets a value indicating whether this instance is zero.
/// </summary>
/// <value>true if this polynomial is the monomial "0"
/// </value>
internal bool isZero
{
get { return coefficients[0] == 0; }
}
/// <summary>
/// coefficient of x^degree term in this polynomial
/// </summary>
/// <param name="degree">The degree.</param>
/// <returns>coefficient of x^degree term in this polynomial</returns>
internal int getCoefficient(int degree)
{
return coefficients[coefficients.Length - 1 - degree];
}
/// <summary>
/// evaluation of this polynomial at a given point
/// </summary>
/// <param name="a">A.</param>
/// <returns>evaluation of this polynomial at a given point</returns>
internal int evaluateAt(int a)
{
if (a == 0)
{
// Just return the x^0 coefficient
return getCoefficient(0);
}
int size = coefficients.Length;
int result = 0;
if (a == 1)
{
// Just the sum of the coefficients
foreach (var coefficient in coefficients)
{
result = field.add(result, coefficient);
}
return result;
}
result = coefficients[0];
for (int i = 1; i < size; i++)
{
result = field.add(field.multiply(a, result), coefficients[i]);
}
return result;
}
/// <summary>
/// Adds another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly add(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero)
{
return other;
}
if (other.isZero)
{
return this;
}
int[] smallerCoefficients = this.coefficients;
int[] largerCoefficients = other.coefficients;
if (smallerCoefficients.Length > largerCoefficients.Length)
{
int[] temp = smallerCoefficients;
smallerCoefficients = largerCoefficients;
largerCoefficients = temp;
}
int[] sumDiff = new int[largerCoefficients.Length];
int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length;
// Copy high-order terms only found in higher-degree polynomial's coefficients
Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
for (int i = lengthDiff; i < largerCoefficients.Length; i++)
{
sumDiff[i] = field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new ModulusPoly(field, sumDiff);
}
/// <summary>
/// Subtract another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly subtract(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
return this;
}
return add(other.getNegative());
}
/// <summary>
/// Multiply by another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly multiply(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero || other.isZero)
{
return field.Zero;
}
int[] aCoefficients = this.coefficients;
int aLength = aCoefficients.Length;
int[] bCoefficients = other.coefficients;
int bLength = bCoefficients.Length;
int[] product = new int[aLength + bLength - 1];
for (int i = 0; i < aLength; i++)
{
int aCoeff = aCoefficients[i];
for (int j = 0; j < bLength; j++)
{
product[i + j] = field.add(product[i + j], field.multiply(aCoeff, bCoefficients[j]));
}
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Returns a Negative version of this instance
/// </summary>
internal ModulusPoly getNegative()
{
int size = coefficients.Length;
int[] negativeCoefficients = new int[size];
for (int i = 0; i < size; i++)
{
negativeCoefficients[i] = field.subtract(0, coefficients[i]);
}
return new ModulusPoly(field, negativeCoefficients);
}
/// <summary>
/// Multiply by a Scalar.
/// </summary>
/// <param name="scalar">Scalar.</param>
internal ModulusPoly multiply(int scalar)
{
if (scalar == 0)
{
return field.Zero;
}
if (scalar == 1)
{
return this;
}
int size = coefficients.Length;
int[] product = new int[size];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], scalar);
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Multiplies by a Monomial
/// </summary>
/// <returns>The by monomial.</returns>
/// <param name="degree">Degree.</param>
/// <param name="coefficient">Coefficient.</param>
internal ModulusPoly multiplyByMonomial(int degree, int coefficient)
{
if (degree < 0)
{
throw new ArgumentException();
}
if (coefficient == 0)
{
return field.Zero;
}
int size = coefficients.Length;
int[] product = new int[size + degree];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], coefficient);
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Divide by another modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly[] divide(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
throw new DivideByZeroException();
}
ModulusPoly quotient = field.Zero;
ModulusPoly remainder = this;
int denominatorLeadingTerm = other.getCoefficient(other.Degree);
int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm);
while (remainder.Degree >= other.Degree && !remainder.isZero)
{
int degreeDifference = remainder.Degree - other.Degree;
int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm);
ModulusPoly term = other.multiplyByMonomial(degreeDifference, scale);
ModulusPoly iterationQuotient = field.buildMonomial(degreeDifference, scale);
quotient = quotient.add(iterationQuotient);
remainder = remainder.subtract(term);
}
return new ModulusPoly[] { quotient, remainder };
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.</returns>
public override String ToString()
{
var result = new StringBuilder(8 * Degree);
for (int degree = Degree; degree >= 0; degree--)
{
int coefficient = getCoefficient(degree);
if (coefficient != 0)
{
if (coefficient < 0)
{
result.Append(" - ");
coefficient = -coefficient;
}
else
{
if (result.Length > 0)
{
result.Append(" + ");
}
}
if (degree == 0 || coefficient != 1)
{
result.Append(coefficient);
}
if (degree != 0)
{
if (degree == 1)
{
result.Append('x');
}
else
{
result.Append("x^");
result.Append(degree);
}
}
}
}
return result.ToString();
}
}
}
| |
using System;
using System.IO;
namespace Ionic.Zlib
{
/// <summary>
/// Represents a Zlib stream for compression or decompression.
/// </summary>
/// <remarks>
///
/// <para>
/// The ZlibStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any
/// stream.
/// </para>
///
/// <para> Using this stream, applications can compress or decompress data via
/// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or
/// decompression can occur through either reading or writing. The compression
/// format used is ZLIB, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed
/// Data Format Specification version 3.3". This implementation of ZLIB always uses
/// DEFLATE as the compression method. (see <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.") </para>
///
/// <para>
/// The ZLIB format allows for varying compression methods, window sizes, and dictionaries.
/// This implementation always uses the DEFLATE compression method, a preset dictionary,
/// and 15 window bits by default.
/// </para>
///
/// <para>
/// This class is similar to <see cref="DeflateStream"/>, except that it adds the
/// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects
/// the RFC1950 header and trailer bytes when decompressing. It is also similar to the
/// <see cref="GZipStream"/>.
/// </para>
/// </remarks>
/// <seealso cref="DeflateStream" />
/// <seealso cref="GZipStream" />
public class ZlibStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
bool _disposed;
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c>
/// will use the default compression level. The "captive" stream will be
/// closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress a file, and writes the
/// compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// The "captive" stream will be closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the
/// compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the captive stream should be left open after
/// Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use
/// the default compression level.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream
/// open.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain
/// open after inflation/deflation.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify
/// whether the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive
/// stream remain open after the deflation or inflation occurs. By
/// default, after <c>Close()</c> is called on the stream, the captive
/// stream is also closed. In some cases this is not desired, for example
/// if the stream is a <see cref="System.IO.MemoryStream"/> that will be
/// re-read after compression. Specify true for the <paramref
/// name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ZlibStream to compress the data from a file,
/// and store the result into another file. The filestream remains open to allow
/// additional data to be written to it.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".zlib")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
///
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
///
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after
/// inflation/deflation.
/// </param>
///
/// <param name="level">
/// A tuning knob to trade speed for effectiveness. This parameter is
/// effective only when mode is <c>CompressionMode.Compress</c>.
/// </param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// Sorry, though, not sure exactly how to describe all the various settings.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get { return this._baseStream._z.TotalBytesIn; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get { return this._baseStream._z.TotalBytesOut; }
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
this._baseStream.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotSupportedException"/>.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotSupportedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut;
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while reading,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// providing an uncompressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data read will be compressed. If you wish to
/// use the <c>ZlibStream</c> to decompress data while reading, you can create
/// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a
/// readable compressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data will be decompressed as it is read.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but
/// not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">
/// The buffer into which the read data should be placed.</param>
///
/// <param name="offset">
/// the offset within that data array to put the first byte read.</param>
///
/// <param name="count">the number of bytes to read.</param>
///
/// <returns>the number of bytes read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
///
/// <returns>nothing. This method always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while writing,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// and a writable output stream. Then call <c>Write()</c> on that
/// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to
/// the output stream will be the compressed form of the data written. If you
/// wish to use the <c>ZlibStream</c> to decompress data while writing, you
/// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that stream,
/// providing previously compressed data. The data sent to the output stream
/// will be the decompressed form of the data written.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
/// <summary>
/// Compress a string into a byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.CompressString(string)"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.CompressString(string)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a single string.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressString(String)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a byte array.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace hawkeye.Core.TPL
{
public static class TaskEx
{
/// <summary>
/// Catch exceptions ONLY of type TException and allow an Action to be performed on it.
/// </summary>
/// <typeparam name="TException"></typeparam>
/// <param name="task"></param>
/// <param name="exceptionHandler"></param>
/// <returns></returns>
public static Task Catch<TException>(this Task task, Action<TException> exceptionHandler)
where TException : Exception
{
if (task == null) throw new ArgumentNullException("task");
if (exceptionHandler == null) throw new ArgumentNullException("exceptionHandler");
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
if (!task.IsFaulted && task.Exception == null)
{
try
{
tcs.TrySetResult(null);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else if (task.IsFaulted)
{
var exception = t.Exception.Flatten().InnerExceptions.FirstOrDefault() ?? t.Exception;
if (exception is TException)
{
exceptionHandler((TException)exception);
}
tcs.TrySetException(exception);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
/// <summary>
/// Catch exceptions ONLY of type TException and allow an Action to be performed on it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TException"></typeparam>
/// <param name="task"></param>
/// <param name="exceptionHandler"></param>
/// <returns></returns>
public static Task<T> Catch<T, TException>(this Task<T> task, Action<TException> exceptionHandler)
where TException : Exception
{
if (task == null) throw new ArgumentNullException("task");
if (exceptionHandler == null) throw new ArgumentNullException("exceptionHandler");
var tcs = new TaskCompletionSource<T>();
task.ContinueWith(t =>
{
if (!task.IsFaulted && task.Exception == null)
{
try
{
tcs.TrySetResult(t.Result);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else if (task.IsFaulted)
{
var exception = t.Exception.Flatten().InnerExceptions.FirstOrDefault() ?? t.Exception;
if (exception is TException)
{
exceptionHandler((TException)exception);
}
tcs.TrySetException(exception);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
/// <summary>
/// Catch ANY exception and allow an Action to be performed on it.
/// Handle all exceptions raised.
/// </summary>
/// <param name="task"></param>
/// <param name="exceptionHandler"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task CatchAndHandle(this Task task, Action<Exception> exceptionHandler, TaskScheduler scheduler)
{
return CatchAndHandle<Exception>(task, exceptionHandler, scheduler);
}
/// <summary>
/// Catch exceptions ONLY of type TException and allow an Action to be performed on it.
/// Handle all exceptions raised.
/// </summary>
/// <typeparam name="TException"></typeparam>
/// <param name="task"></param>
/// <param name="exceptionHandler"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task CatchAndHandle<TException>(this Task task, Action<TException> exceptionHandler, TaskScheduler scheduler)
where TException : Exception
{
if (task == null) throw new ArgumentNullException("task");
if (exceptionHandler == null) throw new ArgumentNullException("exceptionHandler");
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
if (!task.IsFaulted && task.Exception == null)
{
try
{
tcs.TrySetResult(null);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else if (task.IsFaulted)
{
var exception = t.Exception.Flatten().InnerExceptions.FirstOrDefault() ?? t.Exception;
if (exception is TException)
{
exceptionHandler((TException)exception);
}
tcs.TrySetResult(null);
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
public static Task<T1> Do<T1>(this Task<T1> first, Action next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T1>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next();
tcs.TrySetResult(first.Result);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
public static Task<T1> Do<T1>(this Task<T1> first, Action<T1> next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T1>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next(first.Result);
tcs.TrySetResult(first.Result);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
public static Task<T1> Do<T1>(this Task<T1> first, Func<Task> next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T1>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next().Then(() => tcs.TrySetResult(first.Result), scheduler);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
public static Task<T1> Do<T1>(this Task<T1> first, Func<T1, Task> next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T1>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next(first.Result).Then(() => tcs.TrySetResult(first.Result), scheduler);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
/// <summary>
/// ALWAYS execute the action.
/// This should not be composed off of.
/// </summary>
/// <param name="task"></param>
/// <param name="action"></param>
/// <param name="scheduler"></param>
public static Task Finally(this Task task, Action action, TaskScheduler scheduler)
{
if (action == null) throw new ArgumentNullException("action");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
action();
tcs.TrySetResult(null);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
return tcs.Task;
}
/// <summary>
/// Handle all exceptions raised.
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public static Task HandleExceptions(this Task task)
{
if (task == null) throw new ArgumentNullException("task");
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
if (!task.IsFaulted && task.Exception == null)
{
try
{
t.Wait();
tcs.TrySetResult(null);
}
catch (Exception exc)
{
tcs.TrySetResult(null);
}
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else if (task.IsFaulted)
{
// Do this so the exception is handled.
var exception = t.Exception.Flatten();
tcs.TrySetResult(null);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
/// <summary>
/// Returns a task which retries the task returned by the specified task provider.
/// http://gorodinski.com/blog/2012/03/22/retry-with-the-net-task-parallel-library-tpl/
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="task"></param>
/// <param name="taskProvider"></param>
/// <param name="maxAttemps"></param>
/// <param name="shouldRetry"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task<TResult> Retry<TResult>(this Task<TResult> task, Func<Task<TResult>> taskProvider,
int maxAttemps, Func<Exception, bool> shouldRetry,
TaskScheduler scheduler)
{
if (taskProvider == null) throw new ArgumentNullException("taskProvider");
if (scheduler == null) throw new ArgumentNullException("scheduler");
if (maxAttemps < 0) throw new ArgumentNullException("maxAttemps", "maxAttemps is a negative number.");
if (shouldRetry == null)
{
shouldRetry = _ => true;
}
if (!task.IsFaulted)
{
return task;
}
if (maxAttemps > 0 && shouldRetry(task.Exception.InnerException))
{
return taskProvider()
.ContinueWith(retryTask =>
Retry(retryTask, taskProvider, --maxAttemps, shouldRetry, scheduler),
CancellationToken.None, TaskContinuationOptions.None, scheduler)
.Result;
}
// will throw AggregateException
return task;
}
/// <summary>
/// Task that immediately return the value passed in.
/// </summary>
/// <returns></returns>
public static Task<T> Return<T>(T value)
{
var tcs = new TaskCompletionSource<T>();
tcs.TrySetResult(value);
return tcs.Task;
}
public static Task<TResult> Select<TSource, TResult>(this Task<TSource> source, Func<TSource, TResult> selector, TaskScheduler scheduler)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
if (scheduler == null) throw new ArgumentNullException("scheduler");
// Use a continuation to run the selector function
return source.ContinueWith(t => selector(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, scheduler);
}
public static Task<TResult> Select<TResult>(this Task source, Func<TResult> selector, TaskScheduler scheduler)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
if (scheduler == null) throw new ArgumentNullException("scheduler");
// Use a continuation to run the selector function
return source.ContinueWith(t => selector(), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, scheduler);
}
#region Then
/// <summary>
/// When first completes, pass the results to next.
/// next is only called if first completed successfully.
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next, TaskScheduler scheduler)
{
// http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx?Redirected=true
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T2>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
var t = next(first.Result);
if (t == null)
{
tcs.TrySetCanceled();
}
else
{
t.ContinueWith(__ =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(t.Result);
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
}
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// When first completes.
/// next is only called if first completed successfully.
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task<T1> Then<T1>(this Task first, Func<Task<T1>> next, TaskScheduler scheduler)
{
// http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx?Redirected=true
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T1>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
var t = next();
if (t == null)
{
tcs.TrySetCanceled();
}
else
{
t.ContinueWith(__ =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(t.Result);
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
}
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// When first completes, pass the results to next.
/// next is only called if first completed successfully.
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task Then<T1>(this Task<T1> first, Func<T1, Task> next, TaskScheduler scheduler)
{
// http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx?Redirected=true
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<object>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
var t = next(first.Result);
if (t == null)
{
tcs.TrySetCanceled();
}
else
{
t.ContinueWith(__ =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(null);
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
}
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// Execute an Action, Task completes when it is finished.
/// next is only called if first completed successfully.
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, T2> next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<T2>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
var result = next(first.Result);
tcs.TrySetResult(result);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// Execute an Action, Task completes when it is finished.
/// next is only called if first completed successfully.
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task Then<T1>(this Task<T1> first, Action<T1> next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<object>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next(first.Result);
tcs.TrySetResult(null);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// Execute an Action, Task completes when it is finished.
/// </summary>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task Then(this Task first, Action next, TaskScheduler scheduler)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<object>();
first.ContinueWith(_ =>
{
if (first.IsFaulted)
{
tcs.TrySetException(first.Exception.InnerExceptions);
}
else if (first.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
try
{
next();
tcs.TrySetResult(null);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
/// <summary>
/// When first completes, pass the results to next.
/// next is only called if first completed successfully.
/// </summary>
/// <param name="first"></param>
/// <param name="next"></param>
/// <param name="scheduler"></param>
/// <returns></returns>
public static Task Then(this Task first, Func<Task> next, TaskScheduler scheduler)
{
// http://blogs.msdn.com/b/pfxteam/archive/2010/11/21/10094564.aspx?Redirected=true
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
if (scheduler == null) throw new ArgumentNullException("scheduler");
var tcs = new TaskCompletionSource<object>();
first.ContinueWith(_ =>
{
if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);
else if (first.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
var t = next();
if (t == null) tcs.TrySetCanceled();
else
t.ContinueWith(__ =>
{
if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(null);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler);
}
catch (Exception exc)
{
tcs.TrySetException(exc);
}
}
}, scheduler);
return tcs.Task;
}
#endregion
public static Task StartNew(this TaskFactory taskFactory, Action action, TaskScheduler scheduler)
{
if (action == null) throw new ArgumentNullException("action");
if (scheduler == null) throw new ArgumentNullException("scheduler");
return taskFactory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
public static Task<T1> StartNew<T1>(this TaskFactory taskFactory, Func<T1> action, TaskScheduler scheduler)
{
if (action == null) throw new ArgumentNullException("action");
if (scheduler == null) throw new ArgumentNullException("scheduler");
return taskFactory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
public static Task<T1> StartNew<T1>(this TaskFactory taskFactory, Func<object, T1> action, T1 state, TaskScheduler scheduler)
{
if (action == null) throw new ArgumentNullException("action");
if (scheduler == null) throw new ArgumentNullException("scheduler");
return taskFactory.StartNew<T1>(action, state, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#region Timeouts
/// <summary>Creates a new Task that mirrors the supplied task but that will be canceled after the specified timeout.</summary>
/// <typeparam name="TResult">Specifies the type of data contained in the task.</typeparam>
/// <param name="task">The task.</param>
/// <param name="timeout">The timeout.</param>
/// <returns>The new Task that may time out.</returns>
public static Task WithTimeout(this Task task, TimeSpan timeout)
{
var result = new TaskCompletionSource<object>(task.AsyncState);
var timer = new Timer(state => ((TaskCompletionSource<object>)state).TrySetCanceled(), result, timeout, TimeSpan.FromMilliseconds(-1));
task.ContinueWith(t =>
{
timer.Dispose();
result.TrySetFromTask(t);
}, TaskContinuationOptions.ExecuteSynchronously);
return result.Task;
}
/// <summary>Creates a new Task that mirrors the supplied task but that will be canceled after the specified timeout.</summary>
/// <typeparam name="TResult">Specifies the type of data contained in the task.</typeparam>
/// <param name="task">The task.</param>
/// <param name="timeout">The timeout.</param>
/// <returns>The new Task that may time out.</returns>
public static Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
var result = new TaskCompletionSource<TResult>(task.AsyncState);
var timer = new Timer(state => ((TaskCompletionSource<TResult>)state).TrySetCanceled(), result, timeout, TimeSpan.FromMilliseconds(-1));
task.ContinueWith(t =>
{
timer.Dispose();
result.TrySetFromTask(t);
}, TaskContinuationOptions.ExecuteSynchronously);
return result.Task;
}
#endregion
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using PlayFab.PfEditor.Json;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public class PlayFabEditorHelper : UnityEditor.Editor
{
#region EDITOR_STRINGS
public static string EDEX_NAME = "PlayFab_EditorExtensions";
public static string EDEX_VERSION = "0.0.994";
public static string EDEX_ROOT = Application.dataPath + "/PlayFabEditorExtensions/Editor";
public static string DEV_API_ENDPOINT = "https://editor.playfabapi.com";
public static string TITLE_ENDPOINT = ".playfabapi.com";
public static string GAMEMANAGER_URL = "https://developer.playfab.com";
public static string PLAYFAB_SETTINGS_TYPENAME = "PlayFabSettings";
public static string PLAYFAB_EDEX_MAINFILE = "PlayFabEditor.cs";
public static string SDK_DOWNLOAD_PATH = "/Resources/PlayFabUnitySdk.unitypackage";
public static string EDEX_UPGRADE_PATH = "/Resources/PlayFabUnityEditorExtensions.unitypackage";
public static string EDEX_PACKAGES_PATH = "/Resources/MostRecentPackage.unitypackage";
public static string CLOUDSCRIPT_FILENAME = ".CloudScript.js"; //prefixed with a '.' to exclude this code from Unity's compiler
public static string CLOUDSCRIPT_PATH = EDEX_ROOT + "/Resources/" + CLOUDSCRIPT_FILENAME;
public static string ADMIN_API = "ENABLE_PLAYFABADMIN_API";
public static string SERVER_API = "ENABLE_PLAYFABSERVER_API";
public static string CLIENT_API = "DISABLE_PLAYFABCLIENT_API";
public static string DEBUG_REQUEST_TIMING = "PLAYFAB_REQUEST_TIMING";
public static string DISABLE_IDFA = "DISABLE_IDFA";
public static Dictionary<string, string> FLAG_LABELS = new Dictionary<string, string> {
{ CLIENT_API, "ENABLE CLIENT API" },
{ SERVER_API, "ENABLE SERVER API" },
{ ADMIN_API, "ENABLE ADMIN API" },
{ DEBUG_REQUEST_TIMING, "ENABLE REQUEST TIMES" },
{ DISABLE_IDFA, "ENABLE IDFA" },
};
public static Dictionary<string, bool> FLAG_INVERSION = new Dictionary<string, bool> {
{ CLIENT_API, true },
{ SERVER_API, false },
{ ADMIN_API, false },
{ DEBUG_REQUEST_TIMING, false },
{ DISABLE_IDFA, false },
};
public static string DEFAULT_SDK_LOCATION = "Assets/PlayFabSdk";
public static string STUDIO_OVERRIDE = "_OVERRIDE_";
public static string MSG_SPIN_BLOCK = "{\"useSpinner\":true, \"blockUi\":true }";
#endregion
private static GUISkin _uiStyle;
public static GUISkin uiStyle
{
get
{
if (_uiStyle != null)
return _uiStyle;
_uiStyle = GetUiStyle();
return _uiStyle;
}
}
static PlayFabEditorHelper()
{
// scan for changes to the editor folder / structure.
if (uiStyle == null)
{
string[] rootFiles = new string[0];
bool relocatedEdEx = false;
_uiStyle = null;
try
{
if (PlayFabEditorDataService.EnvDetails != null && !string.IsNullOrEmpty(PlayFabEditorDataService.EnvDetails.edexPath))
EDEX_ROOT = PlayFabEditorDataService.EnvDetails.edexPath;
rootFiles = Directory.GetDirectories(EDEX_ROOT);
}
catch
{
if (rootFiles.Length == 0)
{
// this probably means the editor folder was moved.
// see if we can locate the moved root and reload the assets
var movedRootFiles = Directory.GetFiles(Application.dataPath, PLAYFAB_EDEX_MAINFILE, SearchOption.AllDirectories);
if (movedRootFiles.Length > 0)
{
relocatedEdEx = true;
EDEX_ROOT = movedRootFiles[0].Substring(0, movedRootFiles[0].IndexOf(PLAYFAB_EDEX_MAINFILE) - 1);
PlayFabEditorDataService.EnvDetails.edexPath = EDEX_ROOT;
PlayFabEditorDataService.SaveEnvDetails();
}
}
}
finally
{
if (relocatedEdEx && rootFiles.Length == 0)
{
Debug.Log("Found new EdEx root: " + EDEX_ROOT);
}
else if (rootFiles.Length == 0)
{
Debug.Log("Could not relocate the PlayFab Editor Extension");
EDEX_ROOT = string.Empty;
}
}
}
}
private static GUISkin GetUiStyle()
{
var searchRoot = string.IsNullOrEmpty(EDEX_ROOT) ? Application.dataPath : EDEX_ROOT;
var pfGuiPaths = Directory.GetFiles(searchRoot, "PlayFabStyles.guiskin", SearchOption.AllDirectories);
foreach (var eachPath in pfGuiPaths)
{
var loadPath = eachPath.Substring(eachPath.IndexOf("Assets/"));
return (GUISkin)AssetDatabase.LoadAssetAtPath(loadPath, typeof(GUISkin));
}
return null;
}
public static void SharedErrorCallback(EditorModels.PlayFabError error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error.ErrorMessage);
}
public static void SharedErrorCallback(string error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error);
}
protected internal static EditorModels.PlayFabError GeneratePlayFabError(string json, object customData = null)
{
JsonObject errorDict = null;
Dictionary<string, List<string>> errorDetails = null;
try
{
//deserialize the error
errorDict = JsonWrapper.DeserializeObject<JsonObject>(json, PlayFabEditorUtil.ApiSerializerStrategy);
if (errorDict.ContainsKey("errorDetails"))
{
var ed = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString());
errorDetails = ed;
}
}
catch (Exception e)
{
return new EditorModels.PlayFabError()
{
ErrorMessage = e.Message
};
}
//create new error object
return new EditorModels.PlayFabError
{
HttpCode = errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400,
HttpStatus = errorDict.ContainsKey("status")
? (string)errorDict["status"]
: "BadRequest",
Error = errorDict.ContainsKey("errorCode")
? (EditorModels.PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"])
: EditorModels.PlayFabErrorCode.ServiceUnavailable,
ErrorMessage = errorDict.ContainsKey("errorMessage")
? (string)errorDict["errorMessage"]
: string.Empty,
ErrorDetails = errorDetails,
CustomData = customData ?? new object()
};
}
#region unused, but could be useful
/// <summary>
/// Tool to create a color background texture
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="col"></param>
/// <returns>Texture2D</returns>
public static Texture2D MakeTex(int width, int height, Color col)
{
var pix = new Color[width * height];
for (var i = 0; i < pix.Length; i++)
pix[i] = col;
var result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
public static Vector3 GetColorVector(int colorValue)
{
return new Vector3((colorValue / 255f), (colorValue / 255f), (colorValue / 255f));
}
#endregion
}
}
| |
//
// SingleView.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <stephane@delcroix.org>
// Larry Ewing <lewing@src.gnome.org>
//
// Copyright (C) 2005-2010 Novell, Inc.
// Copyright (C) 2008, 2010 Ruben Vermeersch
// Copyright (C) 2006-2010 Stephane Delcroix
// Copyright (C) 2005-2007 Larry Ewing
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Gtk;
using Gdk;
using System;
using System.Collections.Generic;
using Mono.Addins;
using Mono.Unix;
using Hyena;
using FSpot.Extensions;
using FSpot.Utils;
using FSpot.UI.Dialog;
using FSpot.Widgets;
using FSpot.Platform;
using FSpot.Core;
using FSpot.Settings;
using FSpot.Thumbnail;
namespace FSpot {
public class SingleView {
ToolButton rr_button, rl_button;
Sidebar sidebar;
Gtk.ScrolledWindow directory_scrolled;
#pragma warning disable 649
[GtkBeans.Builder.Object] Gtk.HBox toolbar_hbox;
[GtkBeans.Builder.Object] Gtk.VBox info_vbox;
[GtkBeans.Builder.Object] Gtk.ScrolledWindow image_scrolled;
[GtkBeans.Builder.Object] Gtk.CheckMenuItem side_pane_item;
[GtkBeans.Builder.Object] Gtk.CheckMenuItem toolbar_item;
[GtkBeans.Builder.Object] Gtk.CheckMenuItem filenames_item;
[GtkBeans.Builder.Object] Gtk.MenuItem export;
[GtkBeans.Builder.Object] Gtk.Scale zoom_scale;
[GtkBeans.Builder.Object] Label status_label;
[GtkBeans.Builder.Object] ImageMenuItem rotate_left;
[GtkBeans.Builder.Object] ImageMenuItem rotate_right;
[GtkBeans.Builder.Object] Gtk.Window single_view;
#pragma warning restore 649
public Gtk.Window Window {
get {
return single_view;
}
}
PhotoImageView image_view;
SelectionCollectionGridView directory_view;
SafeUri uri;
UriCollection collection;
FullScreenView fsview;
public SingleView (SafeUri [] uris)
{
uri = uris [0];
Log.Debug ("uri: " + uri);
var builder = new GtkBeans.Builder ("single_view.ui");
builder.Autoconnect (this);
LoadPreference (Preferences.ViewerWidth);
LoadPreference (Preferences.ViewerMaximized);
Gtk.Toolbar toolbar = new Gtk.Toolbar ();
toolbar_hbox.PackStart (toolbar);
rl_button = GtkUtil.ToolButtonFromTheme ("object-rotate-left", Catalog.GetString ("Rotate Left"), true);
rl_button.Clicked += HandleRotate270Command;
rl_button.TooltipText = Catalog.GetString ("Rotate photo left");
toolbar.Insert (rl_button, -1);
rr_button = GtkUtil.ToolButtonFromTheme ("object-rotate-right", Catalog.GetString ("Rotate Right"), true);
rr_button.Clicked += HandleRotate90Command;
rr_button.TooltipText = Catalog.GetString ("Rotate photo right");
toolbar.Insert (rr_button, -1);
toolbar.Insert (new SeparatorToolItem (), -1);
ToolButton fs_button = GtkUtil.ToolButtonFromTheme ("view-fullscreen", Catalog.GetString ("Fullscreen"), true);
fs_button.Clicked += HandleViewFullscreen;
fs_button.TooltipText = Catalog.GetString ("View photos fullscreen");
toolbar.Insert (fs_button, -1);
ToolButton ss_button = GtkUtil.ToolButtonFromTheme ("media-playback-start", Catalog.GetString ("Slideshow"), true);
ss_button.Clicked += HandleViewSlideshow;
ss_button.TooltipText = Catalog.GetString ("View photos in a slideshow");
toolbar.Insert (ss_button, -1);
collection = new UriCollection (uris);
TargetList targetList = new TargetList();
targetList.AddTextTargets((uint)DragDropTargets.TargetType.PlainText);
targetList.AddUriTargets((uint)DragDropTargets.TargetType.UriList);
directory_view = new SelectionCollectionGridView (collection);
directory_view.Selection.Changed += HandleSelectionChanged;
directory_view.DragDataReceived += HandleDragDataReceived;
Gtk.Drag.DestSet (directory_view, DestDefaults.All, (TargetEntry[])targetList,
DragAction.Copy | DragAction.Move);
directory_view.DisplayTags = false;
directory_view.DisplayDates = false;
directory_view.DisplayRatings = false;
directory_scrolled = new ScrolledWindow();
directory_scrolled.Add (directory_view);
sidebar = new Sidebar ();
info_vbox.Add (sidebar);
sidebar.AppendPage (directory_scrolled, Catalog.GetString ("Folder"), "gtk-directory");
AddinManager.AddExtensionNodeHandler ("/FSpot/Sidebar", OnSidebarExtensionChanged);
sidebar.Context = ViewContext.Single;
sidebar.CloseRequested += HandleHideSidePane;
sidebar.Show ();
App.Instance.Container.Resolve<IThumbnailLoader> ().OnPixbufLoaded += delegate { directory_view.QueueDraw (); };
image_view = new PhotoImageView (collection);
GtkUtil.ModifyColors (image_view);
GtkUtil.ModifyColors (image_scrolled);
image_view.ZoomChanged += HandleZoomChanged;
image_view.Item.Changed += HandleItemChanged;
image_view.ButtonPressEvent += HandleImageViewButtonPressEvent;
image_view.DragDataReceived += HandleDragDataReceived;
Gtk.Drag.DestSet (image_view, DestDefaults.All, (TargetEntry[])targetList,
DragAction.Copy | DragAction.Move);
image_scrolled.Add (image_view);
Window.ShowAll ();
zoom_scale.ValueChanged += HandleZoomScaleValueChanged;
LoadPreference (Preferences.ViewerShowToolbar);
LoadPreference (Preferences.ViewerInterpolation);
LoadPreference (Preferences.ViewerTransparency);
LoadPreference (Preferences.ViewerTransColor);
ShowSidebar = collection.Count > 1;
LoadPreference (Preferences.ViewerShawFilenames);
Preferences.SettingChanged += OnPreferencesChanged;
Window.DeleteEvent += HandleDeleteEvent;
collection.Changed += HandleCollectionChanged;
// wrap the methods to fit to the delegate
image_view.Item.Changed += delegate (object sender, BrowsablePointerChangedEventArgs old) {
BrowsablePointer pointer = sender as BrowsablePointer;
if (pointer == null)
return;
IPhoto [] item = {pointer.Current};
sidebar.HandleSelectionChanged (new PhotoList (item));
};
image_view.Item.Collection.ItemsChanged += sidebar.HandleSelectionItemsChanged;
UpdateStatusLabel ();
if (collection.Count > 0)
directory_view.Selection.Add (0);
export.Submenu = (Mono.Addins.AddinManager.GetExtensionNode ("/FSpot/Menus/Exports") as FSpot.Extensions.SubmenuNode).GetMenuItem (this).Submenu;
export.Submenu.ShowAll ();
export.Activated += HandleExportActivated ;
}
void OnSidebarExtensionChanged (object s, ExtensionNodeEventArgs args) {
// FIXME: No sidebar page removal yet!
if (args.Change == ExtensionChange.Add)
sidebar.AppendPage ((args.ExtensionNode as SidebarPageNode).GetPage ());
}
void HandleExportActivated (object o, EventArgs e)
{
FSpot.Extensions.ExportMenuItemNode.SelectedImages = () => new PhotoList(directory_view.Selection.Items);
}
public void HandleCollectionChanged (IBrowsableCollection collection)
{
if (collection.Count > 0 && directory_view.Selection.Count == 0) {
Log.Debug ("Added selection");
directory_view.Selection.Add (0);
}
if (collection.Count > 1)
ShowSidebar = true;
rotate_left.Sensitive = rotate_right.Sensitive = rr_button.Sensitive = rl_button.Sensitive = collection.Count != 0;
UpdateStatusLabel ();
}
public bool ShowSidebar {
get {
return info_vbox.Visible;
}
set {
info_vbox.Visible = value;
if (side_pane_item.Active != value)
side_pane_item.Active = value;
}
}
public bool ShowToolbar {
get {
return toolbar_hbox.Visible;
}
set {
toolbar_hbox.Visible = value;
if (toolbar_item.Active != value)
toolbar_item.Active = value;
}
}
SafeUri CurrentUri
{
get {
return uri;
}
set {
uri = value;
collection.Clear ();
collection.LoadItems (new SafeUri[] { uri });
}
}
void HandleRotate90Command (object sender, EventArgs args)
{
RotateCommand command = new RotateCommand (this.Window);
if (command.Execute (RotateDirection.Clockwise, new IPhoto [] { image_view.Item.Current }))
collection.MarkChanged (image_view.Item.Index, FullInvalidate.Instance);
}
void HandleRotate270Command (object sender, EventArgs args)
{
RotateCommand command = new RotateCommand (Window);
if (command.Execute (RotateDirection.Counterclockwise, new IPhoto [] { image_view.Item.Current }))
collection.MarkChanged (image_view.Item.Index, FullInvalidate.Instance);
}
void HandleSelectionChanged (IBrowsableCollection selection)
{
if (selection.Count > 0) {
image_view.Item.Index = ((FSpot.Widgets.SelectionCollection)selection).Ids[0];
zoom_scale.Value = image_view.NormalizedZoom;
}
UpdateStatusLabel ();
}
void HandleItemChanged (object sender, BrowsablePointerChangedEventArgs old)
{
BrowsablePointer pointer = sender as BrowsablePointer;
if (pointer == null)
return;
directory_view.FocusCell = pointer.Index;
directory_view.Selection.Clear ();
if (collection.Count > 0) {
directory_view.Selection.Add (directory_view.FocusCell);
directory_view.ScrollTo (directory_view.FocusCell);
}
}
void HandleSetAsBackgroundCommand (object sender, EventArgs args)
{
IPhoto current = image_view.Item.Current;
if (current == null)
return;
throw new NotImplementedException ("HandlSetAsBackgroundCommand");
}
void HandleViewToolbar(object sender, EventArgs args)
{
ShowToolbar = toolbar_item.Active;
}
void HandleHideSidePane (object sender, EventArgs args)
{
ShowSidebar = false;
}
void HandleViewSidePane(object sender, EventArgs args)
{
ShowSidebar = side_pane_item.Active;
}
void HandleViewSlideshow (object sender, EventArgs args)
{
HandleViewFullscreen (sender, args);
fsview.PlayPause ();
}
void HandleViewFilenames(object sender, EventArgs args)
{
directory_view.DisplayFilenames = filenames_item.Active;
UpdateStatusLabel ();
}
void HandleAbout(object sender, EventArgs args)
{
FSpot.UI.Dialog.AboutDialog.ShowUp ();
}
void HandleNewWindow(object sender, EventArgs args)
{
/* FIXME this needs to register witth the core */
new SingleView (new SafeUri[] {uri});
}
void HandlePreferences(object sender, EventArgs args)
{
SingleView.PreferenceDialog.Show ();
}
void HandleOpenFolder(object sender, EventArgs args)
{
Open (FileChooserAction.SelectFolder);
}
void HandleOpen(object sender, EventArgs args)
{
Open (FileChooserAction.Open);
}
void Open (FileChooserAction action)
{
string title = Catalog.GetString ("Open");
if (action == FileChooserAction.SelectFolder)
title = Catalog.GetString ("Select Folder");
FileChooserDialog chooser = new FileChooserDialog (title,
Window,
action);
chooser.AddButton (Stock.Cancel, ResponseType.Cancel);
chooser.AddButton (Stock.Open, ResponseType.Ok);
chooser.SetUri (uri.ToString ());
int response = chooser.Run ();
if ((ResponseType) response == ResponseType.Ok)
CurrentUri = new SafeUri (chooser.Uri, true);
chooser.Destroy ();
}
void HandleViewFullscreen (object sender, System.EventArgs args)
{
if (fsview != null)
fsview.Destroy ();
fsview = new FSpot.FullScreenView (collection, Window);
fsview.Destroyed += HandleFullScreenViewDestroy;
fsview.View.Item.Index = image_view.Item.Index;
fsview.Show ();
}
void HandleFullScreenViewDestroy (object sender, EventArgs args)
{
directory_view.Selection.Clear ();
if (fsview.View.Item.IsValid)
directory_view.Selection.Add (fsview.View.Item.Index);
fsview = null;
}
public void HandleZoomOut (object sender, EventArgs args)
{
image_view.ZoomOut ();
}
public void HandleZoomOut (object sender, Gtk.ButtonPressEventArgs args)
{
image_view.ZoomOut ();
}
public void HandleZoomIn (object sender, Gtk.ButtonPressEventArgs args)
{
image_view.ZoomIn ();
}
public void HandleZoomIn (object sender, EventArgs args)
{
image_view.ZoomIn ();
}
void HandleZoomScaleValueChanged (object sender, EventArgs args)
{
image_view.NormalizedZoom = zoom_scale.Value;
}
void HandleZoomChanged (object sender, EventArgs args)
{
zoom_scale.Value = image_view.NormalizedZoom;
// FIXME something is broken here
//zoom_in.Sensitive = (zoom_scale.Value != 1.0);
//zoom_out.Sensitive = (zoom_scale.Value != 0.0);
}
void HandleImageViewButtonPressEvent (object sender, ButtonPressEventArgs args)
{
if (args.Event.Type != EventType.ButtonPress || args.Event.Button != 3)
return;
var popup_menu = new Gtk.Menu ();
bool has_item = image_view.Item.Current != null;
GtkUtil.MakeMenuItem (popup_menu, Catalog.GetString ("Rotate _Left"), "object-rotate-left", delegate { HandleRotate270Command(Window, null); }, has_item);
GtkUtil.MakeMenuItem (popup_menu, Catalog.GetString ("Rotate _Right"), "object-rotate-right", delegate { HandleRotate90Command (Window, null); }, has_item);
GtkUtil.MakeMenuSeparator (popup_menu);
GtkUtil.MakeMenuItem (popup_menu, Catalog.GetString ("Set as Background"), HandleSetAsBackgroundCommand, has_item);
popup_menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
}
void HandleDeleteEvent (object sender, DeleteEventArgs args)
{
SavePreferences ();
Window.Destroy ();
args.RetVal = true;
}
void HandleDragDataReceived (object sender, DragDataReceivedArgs args)
{
if (args.Info == (uint)FSpot.DragDropTargets.TargetType.UriList
|| args.Info == (uint)FSpot.DragDropTargets.TargetType.PlainText) {
/*
* If the drop is coming from inside f-spot then we don't want to import
*/
if (Gtk.Drag.GetSourceWidget (args.Context) != null)
return;
UriList list = args.SelectionData.GetUriListData ();
collection.LoadItems (list.ToArray());
Gtk.Drag.Finish (args.Context, true, false, args.Time);
}
}
void UpdateStatusLabel ()
{
IPhoto item = image_view.Item.Current;
var sb = new System.Text.StringBuilder();
if (filenames_item.Active && item != null)
sb.Append (System.IO.Path.GetFileName (item.DefaultVersion.Uri.LocalPath) + " - ");
sb.AppendFormat (Catalog.GetPluralString ("{0} Photo", "{0} Photos", collection.Count), collection.Count);
status_label.Text = sb.ToString ();
}
void HandleFileClose (object sender, EventArgs args)
{
SavePreferences ();
Window.Destroy ();
}
void SavePreferences ()
{
int width, height;
Window.GetSize (out width, out height);
bool maximized = ((Window.GdkWindow.State & Gdk.WindowState.Maximized) > 0);
Preferences.Set (Preferences.ViewerMaximized, maximized);
if (!maximized) {
Preferences.Set (Preferences.ViewerWidth, width);
Preferences.Set (Preferences.ViewerHeight, height);
}
Preferences.Set (Preferences.ViewerShowToolbar, toolbar_hbox.Visible);
Preferences.Set (Preferences.ViewerShawFilenames, filenames_item.Active);
}
void HandleFileOpen(object sender, EventArgs args)
{
var file_selector = new FileChooserDialog ("Open", Window, FileChooserAction.Open);
file_selector.SetUri (uri.ToString ());
int response = file_selector.Run ();
if ((Gtk.ResponseType) response == Gtk.ResponseType.Ok) {
var l = new List<SafeUri> ();
foreach (var s in file_selector.Uris)
l.Add (new SafeUri (s));
new FSpot.SingleView (l.ToArray ());
}
file_selector.Destroy ();
}
void OnPreferencesChanged (object sender, NotifyEventArgs args)
{
LoadPreference (args.Key);
}
void LoadPreference (string key)
{
switch (key) {
case Preferences.ViewerMaximized:
if (Preferences.Get<bool> (key))
Window.Maximize ();
else
Window.Unmaximize ();
break;
case Preferences.ViewerWidth:
case Preferences.ViewerHeight:
int width, height;
width = Preferences.Get<int> (Preferences.ViewerWidth);
height = Preferences.Get<int> (Preferences.ViewerHeight);
if( width == 0 || height == 0 )
break;
Window.SetDefaultSize(width, height);
Window.ReshowWithInitialSize();
break;
case Preferences.ViewerShowToolbar:
if (toolbar_item.Active != Preferences.Get<bool> (key))
toolbar_item.Active = Preferences.Get<bool> (key);
toolbar_hbox.Visible = Preferences.Get<bool> (key);
break;
case Preferences.ViewerInterpolation:
if (Preferences.Get<bool> (key))
image_view.Interpolation = Gdk.InterpType.Bilinear;
else
image_view.Interpolation = Gdk.InterpType.Nearest;
break;
case Preferences.ViewerShawFilenames:
if (filenames_item.Active != Preferences.Get<bool> (key))
filenames_item.Active = Preferences.Get<bool> (key);
break;
case Preferences.ViewerTransparency:
if (Preferences.Get<string> (key) == "CHECK_PATTERN")
image_view.CheckPattern = CheckPattern.Dark;
else if (Preferences.Get<string> (key) == "COLOR")
image_view.CheckPattern = new CheckPattern (Preferences.Get<string> (Preferences.ViewerTransColor));
else // NONE
image_view.CheckPattern = new CheckPattern (image_view.Style.BaseColors [(int)Gtk.StateType.Normal]);
break;
case Preferences.ViewerTransColor:
if (Preferences.Get<string> (Preferences.ViewerTransparency) == "COLOR")
image_view.CheckPattern = new CheckPattern (Preferences.Get<string> (key));
break;
}
}
public class PreferenceDialog : BuilderDialog
{
#pragma warning disable 649
[GtkBeans.Builder.Object] CheckButton interpolation_check;
[GtkBeans.Builder.Object] ColorButton color_button;
[GtkBeans.Builder.Object] RadioButton as_background_radio;
[GtkBeans.Builder.Object] RadioButton as_check_radio;
[GtkBeans.Builder.Object] RadioButton as_color_radio;
#pragma warning restore 649
public PreferenceDialog () : base ("viewer_preferences.ui", "viewer_preferences")
{
LoadPreference (Preferences.ViewerInterpolation);
LoadPreference (Preferences.ViewerTransparency);
LoadPreference (Preferences.ViewerTransColor);
Preferences.SettingChanged += OnPreferencesChanged;
Destroyed += HandleDestroyed;
}
void InterpolationToggled(object sender, EventArgs args)
{
Preferences.Set (Preferences.ViewerInterpolation, interpolation_check.Active);
}
void HandleTransparentColorSet(object sender, EventArgs args)
{
Preferences.Set (Preferences.ViewerTransColor,
"#" +
(color_button.Color.Red / 256 ).ToString("x").PadLeft (2, '0') +
(color_button.Color.Green / 256 ).ToString("x").PadLeft (2, '0') +
(color_button.Color.Blue / 256 ).ToString("x").PadLeft (2, '0'));
}
void HandleTransparencyToggled(object sender, EventArgs args)
{
if (as_background_radio.Active)
Preferences.Set (Preferences.ViewerTransparency, "NONE");
else if (as_check_radio.Active)
Preferences.Set (Preferences.ViewerTransparency, "CHECK_PATTERN");
else if (as_color_radio.Active)
Preferences.Set (Preferences.ViewerTransparency, "COLOR");
}
static PreferenceDialog prefs;
public static new void Show ()
{
if (prefs == null)
prefs = new PreferenceDialog ();
prefs.Present ();
}
void OnPreferencesChanged (object sender, NotifyEventArgs args)
{
LoadPreference (args.Key);
}
void HandleClose(object sender, EventArgs args)
{
Destroy ();
}
void HandleDestroyed (object sender, EventArgs args)
{
prefs = null;
}
void LoadPreference (string key)
{
switch (key) {
case Preferences.ViewerInterpolation:
interpolation_check.Active = Preferences.Get<bool> (key);
break;
case Preferences.ViewerTransparency:
switch (Preferences.Get<string> (key)) {
case "COLOR":
as_color_radio.Active = true;
break;
case "CHECK_PATTERN":
as_check_radio.Active = true;
break;
default: //NONE
as_background_radio.Active = true;
break;
}
break;
case Preferences.ViewerTransColor:
color_button.Color = new Gdk.Color (
Byte.Parse (Preferences.Get<string> (key).Substring (1,2), System.Globalization.NumberStyles.AllowHexSpecifier),
Byte.Parse (Preferences.Get<string> (key).Substring (3,2), System.Globalization.NumberStyles.AllowHexSpecifier),
Byte.Parse (Preferences.Get<string> (key).Substring (5,2), System.Globalization.NumberStyles.AllowHexSpecifier));
break;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Globalization
{
/// <summary>
/// This class defines behaviors specific to a writing system.
/// A writing system is the collection of scripts and orthographic rules
/// required to represent a language as text.
/// </summary>
public class StringInfo
{
private string _str = null!; // initialized in helper called by ctors
private int[]? _indexes;
public StringInfo() : this(string.Empty)
{
}
public StringInfo(string value)
{
this.String = value;
}
public override bool Equals(object? value)
{
return value is StringInfo otherStringInfo
&& _str.Equals(otherStringInfo._str);
}
public override int GetHashCode() => _str.GetHashCode();
/// <summary>
/// Our zero-based array of index values into the string. Initialize if
/// our private array is not yet, in fact, initialized.
/// </summary>
private int[]? Indexes
{
get
{
if (_indexes == null && String.Length > 0)
{
_indexes = StringInfo.ParseCombiningCharacters(String);
}
return _indexes;
}
}
public string String
{
get => _str;
set
{
_str = value ?? throw new ArgumentNullException(nameof(value));
_indexes = null;
}
}
public int LengthInTextElements => Indexes?.Length ?? 0;
public string SubstringByTextElements(int startingTextElement)
{
// If the string is empty, no sense going further.
if (Indexes == null)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
else
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
}
return SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement);
}
public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
if (String.Length == 0 || startingTextElement >= Indexes!.Length)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
if (lengthInTextElements < 0)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.ArgumentOutOfRange_NeedPosNum);
}
if (startingTextElement > Indexes.Length - lengthInTextElements)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.Arg_ArgumentOutOfRangeException);
}
int start = Indexes[startingTextElement];
if (startingTextElement + lengthInTextElements == Indexes.Length)
{
// We are at the last text element in the string and because of that
// must handle the call differently.
return String.Substring(start);
}
else
{
return String[start..Indexes[lengthInTextElements + startingTextElement]];
}
}
public static string GetNextTextElement(string str) => GetNextTextElement(str, 0);
/// <summary>
/// Get the code point count of the current text element.
///
/// A combining class is defined as:
/// A character/surrogate that has the following Unicode category:
/// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
/// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
/// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
///
/// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
/// 1. If a character/surrogate is in the following category, it is a text element.
/// It can NOT further combine with characters in the combinging class to form a text element.
/// * one of the Unicode category in the combinging class
/// * UnicodeCategory.Format
/// * UnicodeCateogry.Control
/// * UnicodeCategory.OtherNotAssigned
/// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
/// </summary>
/// <returns>The length of the current text element</returns>
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return currentCharCount;
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
// Remember the current index.
int startIndex = index;
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return index - startIndex;
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return ret;
}
/// <summary>
/// Returns the str containing the next text element in str starting at
/// index index. If index is not supplied, then it will start at the beginning
/// of str. It recognizes a base character plus one or more combining
/// characters or a properly formed surrogate pair as a text element.
/// See also the ParseCombiningCharacters() and the ParseSurrogates() methods.
/// </summary>
public static string GetNextTextElement(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return string.Empty;
}
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen));
}
public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return GetTextElementEnumerator(str, 0);
}
public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index > len)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
return new TextElementEnumerator(str, index, len);
}
/// <summary>
/// Returns the indices of each base character or properly formed surrogate
/// pair within the str. It recognizes a base character plus one or more
/// combining characters or a properly formed surrogate pair as a text
/// element and returns the index of the base character or high surrogate.
/// Each index is the beginning of a text element within a str. The length
/// of each element is easily computed as the difference between successive
/// indices. The length of the array will always be less than or equal to
/// the length of the str. For example, given the str
/// \u4f00\u302a\ud800\udc00\u4f01, this method would return the indices:
/// 0, 2, 4.
/// </summary>
public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return result;
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, 0, returnArray, 0, resultCount);
return returnArray;
}
return result;
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
using System.Numerics;
using static NodaTime.NodaConstants;
using System.Linq;
namespace NodaTime.Test
{
partial class DurationTest
{
// Test cases for factory methods. In general, we want to check the limits, very small, very large
// and medium values, with a mixture of positive and negative, "on and off" day boundaries.
private static readonly int[] DayCases = {
Duration.MinDays, -3000 * 365, -100, -1, 0, 1, 100, 3000 * 365, Duration.MaxDays
};
private static readonly int[] HourCases = {
Duration.MinDays * HoursPerDay, -3000 * 365 * HoursPerDay, -100, -48, -1, 0,
1, 48, 100, 3000 * 365 * HoursPerDay, ((Duration.MaxDays + 1) * HoursPerDay) - 1
};
private static readonly long[] MinuteCases = GenerateCases(MinutesPerDay);
private static readonly long[] SecondCases = GenerateCases(SecondsPerDay);
private static readonly long[] MillisecondCases = GenerateCases(MillisecondsPerDay);
// No boundary versions as Int64 doesn't have enough ticks to exceed our limits.
private static readonly long[] TickCases = GenerateCases(TicksPerDay).Skip(1).Reverse().Skip(1).Reverse().ToArray();
private static long[] GenerateCases(long unitsPerDay) =>
unchecked (new[] {
Duration.MinDays * unitsPerDay,
-3000L * 365 * unitsPerDay - 1,
-3000L * 365 * unitsPerDay,
-5 * unitsPerDay / 2,
-2 * unitsPerDay
-1,
0,
1,
2 * unitsPerDay,
5 * unitsPerDay / 2,
3000L * 365 * unitsPerDay,
3000L * 365 * unitsPerDay + 1,
((Duration.MaxDays + 1) * unitsPerDay) - 1,
});
[Test]
public void Zero()
{
Duration test = Duration.Zero;
Assert.AreEqual(0, test.BclCompatibleTicks);
Assert.AreEqual(0, test.NanosecondOfFloorDay);
Assert.AreEqual(0, test.FloorDays);
}
private static void TestFactoryMethod(Func<long, Duration> method, long value, long nanosecondsPerUnit)
{
Duration duration = method(value);
BigInteger expectedNanoseconds = (BigInteger)value * nanosecondsPerUnit;
Assert.AreEqual(duration.ToBigIntegerNanoseconds(), expectedNanoseconds);
}
private static void TestFactoryMethod(Func<int, Duration> method, int value, long nanosecondsPerUnit)
{
Duration duration = method(value);
BigInteger expectedNanoseconds = (BigInteger) value * nanosecondsPerUnit;
Assert.AreEqual(duration.ToBigIntegerNanoseconds(), expectedNanoseconds);
}
[Test]
[TestCaseSource(nameof(DayCases))]
public void FromDays_Int32(int days)
{
TestFactoryMethod(Duration.FromDays, days, NanosecondsPerDay);
}
[Test]
[TestCaseSource(nameof(HourCases))]
public void FromHours_Int32(int hours)
{
TestFactoryMethod(Duration.FromHours, hours, NanosecondsPerHour);
}
[Test]
[TestCaseSource(nameof(MinuteCases))]
public void FromMinutes_Int64(long minutes)
{
TestFactoryMethod(Duration.FromMinutes, minutes, NanosecondsPerMinute);
}
[Test]
[TestCaseSource(nameof(SecondCases))]
public void FromSeconds_Int64(long seconds)
{
TestFactoryMethod(Duration.FromSeconds, seconds, NanosecondsPerSecond);
}
[Test]
[TestCaseSource(nameof(MillisecondCases))]
public void FromMilliseconds_Int64(long milliseconds)
{
TestFactoryMethod(Duration.FromMilliseconds, milliseconds, NanosecondsPerMillisecond);
}
[Test]
[TestCaseSource(nameof(TickCases))]
public void FromTicks(long ticks)
{
var nanoseconds = Duration.FromTicks(ticks);
Assert.AreEqual(ticks * (BigInteger)NodaConstants.NanosecondsPerTick, nanoseconds.ToBigIntegerNanoseconds());
// Just another sanity check, although Ticks is covered in more detail later.
Assert.AreEqual(ticks, nanoseconds.BclCompatibleTicks);
}
[Test]
[TestCase(1.5, 1, NanosecondsPerDay / 2)]
[TestCase(-0.25, -1, 3 * NanosecondsPerDay / 4)]
[TestCase(100000.5, 100000, NanosecondsPerDay / 2)]
[TestCase(-5000, -5000, 0)]
public void FromDays_Double(double days, int expectedDays, long expectedNanoOfDay)
{
var actual = Duration.FromDays(days);
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(36.5, 1, NanosecondsPerDay / 2 + NanosecondsPerHour / 2)]
[TestCase(-0.25, -1, NanosecondsPerDay - NanosecondsPerHour / 4)]
[TestCase(24000.5, 1000, NanosecondsPerHour / 2)]
public void FromHours_Double(double hours, int expectedDays, long expectedNanoOfDay)
{
var actual = Duration.FromHours(hours);
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(MinutesPerDay + MinutesPerDay / 2, 1, NanosecondsPerDay / 2)]
[TestCase(1.5, 0, NanosecondsPerSecond * 90)]
[TestCase(-MinutesPerDay + 1.5, -1, NanosecondsPerSecond * 90)]
public void FromMinutes_Double(double minutes, int expectedDays, long expectedNanoOfDay)
{
var actual = Duration.FromMinutes(minutes);
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(SecondsPerDay + SecondsPerDay / 2, 1, NanosecondsPerDay / 2)]
[TestCase(1.5, 0, NanosecondsPerMillisecond * 1500)]
[TestCase(-SecondsPerDay + 1.5, -1, NanosecondsPerMillisecond * 1500)]
public void FromSeconds_Double(double seconds, int expectedDays, long expectedNanoOfDay)
{
var actual = Duration.FromSeconds(seconds);
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(MillisecondsPerDay + MillisecondsPerDay / 2, 1, NanosecondsPerDay / 2)]
[TestCase(1.5, 0, 1500000)]
[TestCase(-MillisecondsPerDay + 1.5, -1, 1500000)]
public void FromMilliseconds_Double(double milliseconds, int expectedDays, long expectedNanoOfDay)
{
var actual = Duration.FromMilliseconds(milliseconds);
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
public void FromAndToTimeSpan()
{
TimeSpan timeSpan = TimeSpan.FromHours(3) + TimeSpan.FromSeconds(2) + TimeSpan.FromTicks(1);
Duration duration = Duration.FromHours(3) + Duration.FromSeconds(2) + Duration.FromTicks(1);
Assert.AreEqual(duration, Duration.FromTimeSpan(timeSpan));
Assert.AreEqual(timeSpan, duration.ToTimeSpan());
Duration maxDuration = Duration.FromTicks(Int64.MaxValue);
Assert.AreEqual(maxDuration, Duration.FromTimeSpan(TimeSpan.MaxValue));
Assert.AreEqual(TimeSpan.MaxValue, maxDuration.ToTimeSpan());
Duration minDuration = Duration.FromTicks(Int64.MinValue);
Assert.AreEqual(minDuration, Duration.FromTimeSpan(TimeSpan.MinValue));
Assert.AreEqual(TimeSpan.MinValue, minDuration.ToTimeSpan());
}
[Test]
public void FromNanoseconds_Int64()
{
Assert.AreEqual(Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay - 1L));
Assert.AreEqual(Duration.OneDay, Duration.FromNanoseconds(NanosecondsPerDay));
Assert.AreEqual(Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay + 1L));
Assert.AreEqual(-Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay - 1L));
Assert.AreEqual(-Duration.OneDay, Duration.FromNanoseconds(-NanosecondsPerDay));
Assert.AreEqual(-Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay + 1L));
}
[Test]
public void FromNanosecondsDecimal_Limits()
{
Assert.AreEqual(Duration.MinValue, Duration.FromNanoseconds(Duration.MinDecimalNanoseconds));
Assert.AreEqual(Duration.MaxValue, Duration.FromNanoseconds(Duration.MaxDecimalNanoseconds));
Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(Duration.MinDecimalNanoseconds - 1m));
Assert.Throws<ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(Duration.MaxDecimalNanoseconds + 1m));
}
[Test]
public void FromNanoseconds_BigInteger()
{
Assert.AreEqual(Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay - BigInteger.One));
Assert.AreEqual(Duration.OneDay, Duration.FromNanoseconds(NanosecondsPerDay + BigInteger.Zero));
Assert.AreEqual(Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay + BigInteger.One));
Assert.AreEqual(-Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay - BigInteger.One));
Assert.AreEqual(-Duration.OneDay, Duration.FromNanoseconds(-NanosecondsPerDay + BigInteger.Zero));
Assert.AreEqual(-Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay + BigInteger.One));
}
[Test]
public void FromNanoseconds_Double()
{
Assert.AreEqual(Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay - 1d));
Assert.AreEqual(Duration.OneDay, Duration.FromNanoseconds(NanosecondsPerDay + 0d));
Assert.AreEqual(Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(NanosecondsPerDay + 1d));
Assert.AreEqual(-Duration.OneDay - Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay - 1d));
Assert.AreEqual(-Duration.OneDay, Duration.FromNanoseconds(-NanosecondsPerDay + 0d));
Assert.AreEqual(-Duration.OneDay + Duration.Epsilon, Duration.FromNanoseconds(-NanosecondsPerDay + 1d));
// Checks for values outside the range of long...
// Find a value which is pretty big, but will definitely still convert back to a positive long.
double largeDoubleValue = (long.MaxValue / 16) * 15;
long largeInt64Value = (long) largeDoubleValue; // This won't be exactly long.MaxValue
Assert.AreEqual(Duration.FromNanoseconds(largeInt64Value) * 8, Duration.FromNanoseconds(largeDoubleValue * 8d));
}
[Test]
public void FactoryMethods_OutOfRange()
{
// Each set of cases starts with the minimum and ends with the maximum, so we can test just beyond the limits easily.
AssertLimitsInt32(Duration.FromDays, DayCases);
AssertLimitsInt32(Duration.FromHours, HourCases);
AssertLimitsInt64(Duration.FromMinutes, MinuteCases);
AssertLimitsInt64(Duration.FromSeconds, SecondCases);
AssertLimitsInt64(Duration.FromMilliseconds, MillisecondCases);
// FromTicks(long) never throws.
double[] bigBadDoubles = { double.NegativeInfinity, double.MinValue, double.MaxValue, double.PositiveInfinity, double.NaN };
AssertOutOfRange(Duration.FromDays, bigBadDoubles);
AssertOutOfRange(Duration.FromHours, bigBadDoubles);
AssertOutOfRange(Duration.FromMinutes, bigBadDoubles);
AssertOutOfRange(Duration.FromSeconds, bigBadDoubles);
AssertOutOfRange(Duration.FromMilliseconds, bigBadDoubles);
AssertOutOfRange(Duration.FromTicks, bigBadDoubles);
AssertOutOfRange(Duration.FromNanoseconds, bigBadDoubles);
// No such concept as BigInteger.Min/MaxValue, so use the values we know to be just outside valid bounds.
AssertOutOfRange(Duration.FromNanoseconds, Duration.MinNanoseconds - 1, Duration.MaxNanoseconds + 1);
void AssertLimitsInt32(Func<int, Duration> factoryMethod, int[] allCases) =>
AssertOutOfRange(factoryMethod, allCases.First() - 1, allCases.Last() + 1);
void AssertLimitsInt64(Func<long, Duration> factoryMethod, long[] allCases) =>
AssertOutOfRange(factoryMethod, allCases.First() - 1, allCases.Last() + 1);
void AssertOutOfRange<T>(Func<T, Duration> factoryMethod, params T[] values)
{
foreach (var value in values)
{
Assert.Throws<ArgumentOutOfRangeException>(() => factoryMethod(value));
}
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Networking.IPsecPolicyBinding", Namespace="urn:iControl")]
public partial class NetworkingIPsecPolicy : iControlInterface {
public NetworkingIPsecPolicy() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void create(
string [] policies
) {
this.Invoke("create", new object [] {
policies});
}
public System.IAsyncResult Begincreate(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
policies}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_policies
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void delete_all_policies(
) {
this.Invoke("delete_all_policies", new object [0]);
}
public System.IAsyncResult Begindelete_all_policies(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_policies", new object[0], callback, asyncState);
}
public void Enddelete_all_policies(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void delete_policy(
string [] policies
) {
this.Invoke("delete_policy", new object [] {
policies});
}
public System.IAsyncResult Begindelete_policy(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_policy", new object[] {
policies}, callback, asyncState);
}
public void Enddelete_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_auth_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecSaAuthAlgorithm [] get_auth_algorithm(
string [] policies
) {
object [] results = this.Invoke("get_auth_algorithm", new object [] {
policies});
return ((NetworkingIPsecSaAuthAlgorithm [])(results[0]));
}
public System.IAsyncResult Beginget_auth_algorithm(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auth_algorithm", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPsecSaAuthAlgorithm [] Endget_auth_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecSaAuthAlgorithm [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] policies
) {
object [] results = this.Invoke("get_description", new object [] {
policies});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
policies}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_encrypt_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecDynSaEncryptAlgorithm [] get_encrypt_algorithm(
string [] policies
) {
object [] results = this.Invoke("get_encrypt_algorithm", new object [] {
policies});
return ((NetworkingIPsecDynSaEncryptAlgorithm [])(results[0]));
}
public System.IAsyncResult Beginget_encrypt_algorithm(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_encrypt_algorithm", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPsecDynSaEncryptAlgorithm [] Endget_encrypt_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecDynSaEncryptAlgorithm [])(results[0]));
}
//-----------------------------------------------------------------------
// get_forward_secrecy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecDiffieHellmanGroup [] get_forward_secrecy(
string [] policies
) {
object [] results = this.Invoke("get_forward_secrecy", new object [] {
policies});
return ((NetworkingIPsecDiffieHellmanGroup [])(results[0]));
}
public System.IAsyncResult Beginget_forward_secrecy(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_forward_secrecy", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPsecDiffieHellmanGroup [] Endget_forward_secrecy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecDiffieHellmanGroup [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ipcomp_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPCompAlgorithm [] get_ipcomp_algorithm(
string [] policies
) {
object [] results = this.Invoke("get_ipcomp_algorithm", new object [] {
policies});
return ((NetworkingIPCompAlgorithm [])(results[0]));
}
public System.IAsyncResult Beginget_ipcomp_algorithm(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ipcomp_algorithm", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPCompAlgorithm [] Endget_ipcomp_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPCompAlgorithm [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ipcomp_deflate_level
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public short [] get_ipcomp_deflate_level(
string [] policies
) {
object [] results = this.Invoke("get_ipcomp_deflate_level", new object [] {
policies});
return ((short [])(results[0]));
}
public System.IAsyncResult Beginget_ipcomp_deflate_level(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ipcomp_deflate_level", new object[] {
policies}, callback, asyncState);
}
public short [] Endget_ipcomp_deflate_level(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((short [])(results[0]));
}
//-----------------------------------------------------------------------
// get_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_lifetime(
string [] policies
) {
object [] results = this.Invoke("get_lifetime", new object [] {
policies});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_lifetime(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_lifetime", new object[] {
policies}, callback, asyncState);
}
public long [] Endget_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_lifetime_kilobytes
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_lifetime_kilobytes(
string [] policies
) {
object [] results = this.Invoke("get_lifetime_kilobytes", new object [] {
policies});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_lifetime_kilobytes(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_lifetime_kilobytes", new object[] {
policies}, callback, asyncState);
}
public long [] Endget_lifetime_kilobytes(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_local_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_local_address(
string [] policies
) {
object [] results = this.Invoke("get_local_address", new object [] {
policies});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_local_address(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_local_address", new object[] {
policies}, callback, asyncState);
}
public string [] Endget_local_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecMode [] get_mode(
string [] policies
) {
object [] results = this.Invoke("get_mode", new object [] {
policies});
return ((NetworkingIPsecMode [])(results[0]));
}
public System.IAsyncResult Beginget_mode(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mode", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPsecMode [] Endget_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecMode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecProtocol [] get_protocol(
string [] policies
) {
object [] results = this.Invoke("get_protocol", new object [] {
policies});
return ((NetworkingIPsecProtocol [])(results[0]));
}
public System.IAsyncResult Beginget_protocol(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_protocol", new object[] {
policies}, callback, asyncState);
}
public NetworkingIPsecProtocol [] Endget_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecProtocol [])(results[0]));
}
//-----------------------------------------------------------------------
// get_remote_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_remote_address(
string [] policies
) {
object [] results = this.Invoke("get_remote_address", new object [] {
policies});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_remote_address(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_remote_address", new object[] {
policies}, callback, asyncState);
}
public string [] Endget_remote_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_auth_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_auth_algorithm(
string [] policies,
NetworkingIPsecSaAuthAlgorithm [] algorithms
) {
this.Invoke("set_auth_algorithm", new object [] {
policies,
algorithms});
}
public System.IAsyncResult Beginset_auth_algorithm(string [] policies,NetworkingIPsecSaAuthAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auth_algorithm", new object[] {
policies,
algorithms}, callback, asyncState);
}
public void Endset_auth_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_description(
string [] policies,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
policies,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] policies,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
policies,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_encrypt_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_encrypt_algorithm(
string [] policies,
NetworkingIPsecDynSaEncryptAlgorithm [] algorithms
) {
this.Invoke("set_encrypt_algorithm", new object [] {
policies,
algorithms});
}
public System.IAsyncResult Beginset_encrypt_algorithm(string [] policies,NetworkingIPsecDynSaEncryptAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_encrypt_algorithm", new object[] {
policies,
algorithms}, callback, asyncState);
}
public void Endset_encrypt_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_forward_secrecy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_forward_secrecy(
string [] policies,
NetworkingIPsecDiffieHellmanGroup [] secrecies
) {
this.Invoke("set_forward_secrecy", new object [] {
policies,
secrecies});
}
public System.IAsyncResult Beginset_forward_secrecy(string [] policies,NetworkingIPsecDiffieHellmanGroup [] secrecies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_forward_secrecy", new object[] {
policies,
secrecies}, callback, asyncState);
}
public void Endset_forward_secrecy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ipcomp_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_ipcomp_algorithm(
string [] policies,
NetworkingIPCompAlgorithm [] algorithms
) {
this.Invoke("set_ipcomp_algorithm", new object [] {
policies,
algorithms});
}
public System.IAsyncResult Beginset_ipcomp_algorithm(string [] policies,NetworkingIPCompAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ipcomp_algorithm", new object[] {
policies,
algorithms}, callback, asyncState);
}
public void Endset_ipcomp_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ipcomp_deflate_level
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_ipcomp_deflate_level(
string [] policies,
short [] levels
) {
this.Invoke("set_ipcomp_deflate_level", new object [] {
policies,
levels});
}
public System.IAsyncResult Beginset_ipcomp_deflate_level(string [] policies,short [] levels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ipcomp_deflate_level", new object[] {
policies,
levels}, callback, asyncState);
}
public void Endset_ipcomp_deflate_level(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_lifetime(
string [] policies,
long [] lifetimes
) {
this.Invoke("set_lifetime", new object [] {
policies,
lifetimes});
}
public System.IAsyncResult Beginset_lifetime(string [] policies,long [] lifetimes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_lifetime", new object[] {
policies,
lifetimes}, callback, asyncState);
}
public void Endset_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_lifetime_kilobytes
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_lifetime_kilobytes(
string [] policies,
long [] lifetimes
) {
this.Invoke("set_lifetime_kilobytes", new object [] {
policies,
lifetimes});
}
public System.IAsyncResult Beginset_lifetime_kilobytes(string [] policies,long [] lifetimes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_lifetime_kilobytes", new object[] {
policies,
lifetimes}, callback, asyncState);
}
public void Endset_lifetime_kilobytes(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_local_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_local_address(
string [] policies,
string [] addresses
) {
this.Invoke("set_local_address", new object [] {
policies,
addresses});
}
public System.IAsyncResult Beginset_local_address(string [] policies,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_local_address", new object[] {
policies,
addresses}, callback, asyncState);
}
public void Endset_local_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_mode(
string [] policies,
NetworkingIPsecMode [] modes
) {
this.Invoke("set_mode", new object [] {
policies,
modes});
}
public System.IAsyncResult Beginset_mode(string [] policies,NetworkingIPsecMode [] modes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mode", new object[] {
policies,
modes}, callback, asyncState);
}
public void Endset_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_protocol(
string [] policies,
NetworkingIPsecProtocol [] protocols
) {
this.Invoke("set_protocol", new object [] {
policies,
protocols});
}
public System.IAsyncResult Beginset_protocol(string [] policies,NetworkingIPsecProtocol [] protocols, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_protocol", new object[] {
policies,
protocols}, callback, asyncState);
}
public void Endset_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_remote_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecPolicy",
RequestNamespace="urn:iControl:Networking/IPsecPolicy", ResponseNamespace="urn:iControl:Networking/IPsecPolicy")]
public void set_remote_address(
string [] policies,
string [] addresses
) {
this.Invoke("set_remote_address", new object [] {
policies,
addresses});
}
public System.IAsyncResult Beginset_remote_address(string [] policies,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_remote_address", new object[] {
policies,
addresses}, callback, asyncState);
}
public void Endset_remote_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestListWithPdxTests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
var props = Properties<string, string>.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
void RegisterKeysPdx()
{
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTests.PdxTypes1.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterAllKeys();
}
void StepThreePdx()
{
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTests.PdxTypes1.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region[1] = new PdxTests.PdxTypes8();
}
void StepFourPdx()
{
Thread.Sleep(2000);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> regionLocal = region.GetLocalView();
object ret = regionLocal[1];
Assert.IsNotNull(ret);
Assert.IsTrue(ret is IPdxSerializable);
}
[Test]
public void InterestListWithPdx()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client2.Call(RegisterKeysPdx);
m_client1.Call(StepThreePdx);
Util.Log("StepThreePdx complete.");
m_client2.Call(StepFourPdx);
Util.Log("StepFourPdx complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
| |
#nullable disable
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WWT;
/* Jonathan Fay wrote this, except for the bits polluted by Dinoj, which are between <dinoj>...</dinoj> tags
* The header information in the .plate files is being upgraded.
* The original versiof plate files (such as those for the DSS tiles, which are of the form N177.plate etc
* have their first eight bytes free but empty. One had to know the number of levels they had (7 for DSS)
* in order to use them. This code will always have to be able to read those files for legacy purposes.
* The current version of .plate files has the first eight bytes used - the first four contain a magic number
* that says that they are this version of plate files and the next four bytes contain the number of levels.
* If you request a nonexistent L-X-Y tile, null is returned. Note that this sometimes happens on a level
* where tiles are present, since the overall images contained in the .plate file may have side length
* a power of 2.
*
* Example of the first eight bytes (in Hex) : 43AD697E03000000
*
* The 43AD697E is the magic number (really 7E69AD43) and the number of levels (00000003) is three.
* Yes, we stored them least significant byte first.
*/
namespace WWT.PlateFiles
{
public class PlateTilePyramid : IDisposable
{
private bool _disposed = false;
public int Levels { get; }
uint currentOffset = 0;
LevelInfo[] levelMap;
// <dinoj>
const uint dotPlateFileTypeNumber = 2120854851; // 7E69AD43 in hex
/// magic number is ceil(0.9876 * 2^31) = 0111 1110 0110 1001 1010 1101 0100 0011 in binary
/// this identifies that this plate file has useful header information
public PlateTilePyramid(Stream stream)
{
if (GetLevelCount(stream, out var L))
{
fileStream = stream;
Levels = L;
}
else
{
throw new InvalidOperationException();
}
}
Stream fileStream = null;
public PlateTilePyramid(Stream stream, int L)
{
fileStream = stream;
Levels = L;
levelMap = new LevelInfo[Levels];
for (int i = 0; i < Levels; i++)
{
levelMap[i] = new LevelInfo(i);
}
WriteHeaders();
currentOffset = HeaderSize;
fileStream.Seek(currentOffset, SeekOrigin.Begin);
}
public int Count { get; private set; }
public async Task AddStreamAsync(Stream inputStream, int level, int x, int y, CancellationToken token)
{
Count++;
long start = fileStream.Seek(0, SeekOrigin.End);
await inputStream.CopyToAsync(fileStream, token).ConfigureAwait(false);
levelMap[level].fileMap[x, y].start = (uint)start;
levelMap[level].fileMap[x, y].size = (uint)inputStream.Length;
}
public void UpdateHeaderAndClose()
{
if (fileStream != null)
{
WriteHeaders();
fileStream.Close();
fileStream = null;
}
}
public static int GetImageCountOneAxis(int level) => (int)Math.Pow(2, level);
public static bool GetLevelCount(string plateFileName, out int L)
{
if (File.Exists(plateFileName))
{
using (var fs = new FileStream(plateFileName, FileMode.Open, FileAccess.Read))
{
return GetLevelCount(fs, out L);
}
}
L = 10;
return false;
}
public static bool GetLevelCount(Stream stream, out int L)
{
// Returns true if plateFileName has the magic number identifying this as a .plate file
// Also returns the number of levels in the .plate file.
if (stream != null)
{
uint FirstFourBytes = GetNodeInfo(stream, 0, out var SecondFourBytes);
if (FirstFourBytes == dotPlateFileTypeNumber)
{
L = (int)SecondFourBytes;
return true;
}
}
// This is 10 by default i.e. if no headers are found.
L = 10;
return false;
}
private void WriteHeaders()
{
// <dinoj>
uint L = (uint)Levels;
byte[] buffer = new byte[8];
buffer[0] = (byte)(dotPlateFileTypeNumber % 256);
buffer[1] = (byte)((dotPlateFileTypeNumber >> 8) % 256);
buffer[2] = (byte)((dotPlateFileTypeNumber >> 16) % 256);
buffer[3] = (byte)((dotPlateFileTypeNumber >> 24) % 256);
buffer[4] = (byte)L;
buffer[5] = (byte)(L >> 8);
buffer[6] = (byte)(L >> 16);
buffer[7] = (byte)(L >> 24);
fileStream.Write(buffer, 0, 8);
// </dinoj>
uint currentSeek = 8;
foreach (LevelInfo li in levelMap)
{
int count = (int)Math.Pow(2, li.level);
for (int y = 0; y < count; y++)
{
for (int x = 0; x < count; x++)
{
SetNodeInfo(fileStream, currentSeek, li.fileMap[x, y].start, li.fileMap[x, y].size);
currentSeek += 8;
}
}
}
}
uint HeaderSize
{
get
{
return GetFileIndexOffset(Levels, 0, 0);
}
}
static public uint GetFileIndexOffset(int level, int x, int y)
{
uint offset = 8;
for (uint i = 0; i < level; i++)
{
offset += (uint)(Math.Pow(2, i * 2) * 8);
}
offset += (uint)(y * Math.Pow(2, level) + x) * 8;
return offset;
}
public static async Task<Stream> GetImageStreamAsync(Stream f, int level, int x, int y, CancellationToken token)
{
var offset = GetFileIndexOffset(level, x, y);
f.Seek(offset, SeekOrigin.Begin);
var (start, length) = await GetNodeInfoAsync(f, offset, token).ConfigureAwait(false);
return StreamSlice.Create(f, start, length);
}
public static Stream GetFileStream(string filename, int level, int x, int y)
{
uint offset = GetFileIndexOffset(level, x, y);
uint start;
MemoryStream ms = null;
using (FileStream f = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
f.Seek(offset, SeekOrigin.Begin);
start = GetNodeInfo(f, offset, out var length);
byte[] buffer = new byte[length];
f.Seek(start, SeekOrigin.Begin);
f.Read(buffer, 0, (int)length);
ms = new MemoryStream(buffer);
f.Close();
}
return ms;
}
private static async ValueTask<(uint start, uint length)> GetNodeInfoAsync(Stream fs, uint offset, CancellationToken token)
{
Byte[] buf = new Byte[8];
fs.Seek(offset, SeekOrigin.Begin);
await fs.ReadAsync(buf, 0, 8, token).ConfigureAwait(false);
var length = (uint)(buf[4] + (buf[5] << 8) + (buf[6] << 16) + (buf[7] << 24));
var start = (uint)((buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24)));
return (start, length);
}
private static uint GetNodeInfo(Stream fs, uint offset, out uint length)
{
Byte[] buf = new Byte[8];
fs.Seek(offset, SeekOrigin.Begin);
fs.Read(buf, 0, 8);
length = (uint)(buf[4] + (buf[5] << 8) + (buf[6] << 16) + (buf[7] << 24));
return (uint)((buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24)));
}
private static void SetNodeInfo(Stream fs, uint offset, uint start, uint length)
{
Byte[] buf = new Byte[8];
buf[0] = (byte)start;
buf[1] = (byte)(start >> 8);
buf[2] = (byte)(start >> 16);
buf[3] = (byte)(start >> 24);
buf[4] = (byte)length;
buf[5] = (byte)(length >> 8);
buf[6] = (byte)(length >> 16);
buf[7] = (byte)(length >> 24);
fs.Seek(offset, SeekOrigin.Begin);
fs.Write(buf, 0, 8);
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
public void Dispose(bool disposing)
{
if (!this._disposed)
{
// If disposing equals true, dispose all managed and unmanaged resources.
if (disposing)
{
}
this._disposed = true;
}
}
}
public class LevelInfo
{
public int level;
public NodeInfo[,] fileMap;
public LevelInfo(int level)
{
this.level = level;
fileMap = new NodeInfo[(int)Math.Pow(2, level), (int)Math.Pow(2, level)];
}
}
public struct NodeInfo
{
public uint start;
public uint size;
public string filename;
}
}
| |
using System;
/// <summary>
/// System.IConvertible.ToSingle(System.IFormatProvider)
/// </summary>
public class DoubleIConvertibleToSingle
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
// retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random positive Double to single");
try
{
Single s = TestLibrary.Generator.GetSingle(-55);
Double i1 = (Double)s;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != s)
{
TestLibrary.TestFramework.LogError("001.1", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert a random negtive Double to single");
try
{
Single s = -TestLibrary.Generator.GetSingle(-55);
Double i1 = (Double)s;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != s)
{
TestLibrary.TestFramework.LogError("002.1", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert zero to single ");
try
{
Double i1 = 0;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != 0)
{
TestLibrary.TestFramework.LogError("003.1", "The result is not zero as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert (double)Single.MaxValue to single.");
try
{
Double i1 = (Double)Single.MaxValue;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != Single.MaxValue)
{
TestLibrary.TestFramework.LogError("004.1", "The result is not expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert (double)Single.MinValue to single.");
try
{
Double i1 = (Double)Single.MinValue;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != Single.MinValue)
{
TestLibrary.TestFramework.LogError("005.1", "The result is not expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
//public bool NegTest1()
//{
// bool retVal = true;
// TestLibrary.TestFramework.BeginScenario("NegTest1: ");
// try
// {
// //
// // Add your test logic here
// //
// }
// catch (Exception e)
// {
// TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
// TestLibrary.TestFramework.LogInformation(e.StackTrace);
// retVal = false;
// }
// return retVal;
//}
#endregion
#endregion
public static int Main()
{
DoubleIConvertibleToSingle test = new DoubleIConvertibleToSingle();
TestLibrary.TestFramework.BeginTestCase("DoubleIConvertibleToSingle");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NationalInstruments.DAQmx;
using RRLab.Utilities;
using RRLab.PhysiologyWorkbench.Devices;
using RRLab.PhysiologyWorkbench.Data;
namespace RRLab.PhysiologyWorkbench.Daq
{
public class TestPulseProtocol : DaqProtocol
{
protected double[] _CellCapacitance;
protected double[] _Gain;
protected double[] _Current;
public override string ProtocolName
{
get { return "Test Pulse"; }
}
public override string ProtocolDescription
{
get { return "Outputs a short voltage shift while recording the current."; }
}
[field: NonSerialized]
public event EventHandler ResistanceChanged;
private float _Resistance = 0;
public float Resistance
{
get { return _Resistance; }
protected set
{
_Resistance = value;
if (ResistanceChanged != null) ResistanceChanged(this, EventArgs.Empty);
}
}
[field: NonSerialized]
public event EventHandler AmplifierChanged;
private Amplifier _Amplifier;
public Amplifier Amplifier
{
get { return _Amplifier; }
set {
if (Amplifier == value) return;
_Amplifier = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
if (AmplifierChanged != null) AmplifierChanged(this, EventArgs.Empty);
}
}
public virtual int AcquisitionLength
{
get
{
return (2*RestingLength+PulseLength);
}
}
[field:NonSerialized]
public event EventHandler RestingPotentialChanged;
private int _RestingPotential = 0;
public int RestingPotential
{
get { return _RestingPotential; }
set
{
if (RestingPotential == value) return;
_RestingPotential = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
if (RestingPotentialChanged != null) RestingPotentialChanged(this, EventArgs.Empty);
}
}
[field: NonSerialized]
public event EventHandler RestingLengthChanged;
private int _RestingLength = 50;
public int RestingLength
{
get { return _RestingLength; }
set
{
if (RestingLength == value) return;
_RestingLength = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
if (RestingLengthChanged != null) RestingLengthChanged(this, EventArgs.Empty);
}
}
[field: NonSerialized]
public event EventHandler PulsePotentialChanged;
private int _PulsePotential = 10;
public int PulsePotential
{
get { return _PulsePotential; }
set
{
if (PulsePotential == value) return;
_PulsePotential = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
if (PulsePotentialChanged != null) PulsePotentialChanged(this, EventArgs.Empty);
}
}
[field: NonSerialized]
public event EventHandler PulseLengthChanged;
private int _PulseLength = 100;
public int PulseLength
{
get { return _PulseLength; }
set
{
if (PulseLength == value) return;
_PulseLength = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
if (PulseLengthChanged != null) PulseLengthChanged(this, EventArgs.Empty);
}
}
public override bool IsContinuousRecordingSupported
{
get
{
return true;
}
}
private bool _TriggerRegenerationOfOutputWaveform;
protected bool TriggerRegenerationOfOutputWaveform
{
get { return _TriggerRegenerationOfOutputWaveform; }
set { _TriggerRegenerationOfOutputWaveform = value; }
}
private bool _TriggerNewData;
public bool TriggerNewData
{
get { return _TriggerNewData; }
set { _TriggerNewData = value; }
}
protected bool IsNewDataSet = true;
public TestPulseProtocol()
{
}
private Task _AITask;
protected Task AITask
{
get { return _AITask; }
set { _AITask = value; }
}
private Task _AOTask;
public Task AOTask
{
get { return _AOTask; }
set { _AOTask = value; }
}
public event EventHandler SampleClockChanged;
private string _SampleClock = "";
public string SampleClock
{
get { return _SampleClock; }
set {
if (SampleClock == value) return;
_SampleClock = value;
if (SampleClockChanged != null) SampleClockChanged(this, EventArgs.Empty);
}
}
public event EventHandler SampleRateChanged;
private int _SampleRate = 2500;
public int SampleRate
{
get { return _SampleRate; }
set {
if (SampleRate == value) return;
_SampleRate = value;
if (SampleRateChanged != null) SampleRateChanged(this, EventArgs.Empty);
}
}
private SampleClockActiveEdge _ClockEdge = SampleClockActiveEdge.Rising;
public SampleClockActiveEdge ClockEdge
{
get { return _ClockEdge; }
set { _ClockEdge = value; }
}
private string _TriggerLine = "/Dev1/ai/StartTrigger";
public string TriggerLine
{
get { return _TriggerLine; }
set { _TriggerLine = value; }
}
private DigitalEdgeStartTriggerEdge _TriggerEdge = DigitalEdgeStartTriggerEdge.Rising;
public DigitalEdgeStartTriggerEdge TriggerEdge
{
get { return _TriggerEdge; }
set { _TriggerEdge = value; }
}
private List<string> _ChannelNames = new List<string>();
protected List<string> ChannelNames
{
get { return _ChannelNames; }
set
{
_ChannelNames = value;
}
}
private SortedList<string,string> _ChannelUnits = new SortedList<string,string>();
protected SortedList<string,string> ChannelUnits
{
get { return _ChannelUnits; }
}
protected AnalogMultiChannelReader AIReader = null;
protected float[] CachedTime;
protected override void Initialize()
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Initializing");
Data = null;
CachedTime = null;
_ChannelNames.Clear();
_ChannelUnits.Clear();
if ((AOTask != null) || (AITask != null)) FinalizeProtocol();
if (Amplifier == null) return;
try
{
Amplifier.ForwardAbsoluteVHoldSettingChange += new ForwardAbsoluteVHoldSettingChange(ReceiveForwardedVHoldChange);
AOTask = new Task("AO");
AITask = new Task("AI");
ConfigureChannels(); // Configure channels
// Configure timing
AOTask.Timing.ConfigureSampleClock(SampleClock, SampleRate, ClockEdge, SampleQuantityMode.FiniteSamples, AcquisitionLength * SampleRate / 1000);
AITask.Timing.ConfigureSampleClock(SampleClock, SampleRate, ClockEdge, SampleQuantityMode.FiniteSamples, AcquisitionLength * SampleRate / 1000);
// Configure triggers
AOTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(TriggerLine, TriggerEdge);
AOTask.Control(TaskAction.Verify);
AITask.Control(TaskAction.Verify);
FireStartingEvent(this, EventArgs.Empty);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error during initialization: " + e.Message);
FinalizeProtocol();
}
}
protected override void Execute()
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Execute.");
try
{
WriteToAOChannels();
ConfigureChannelReaders();
AOTask.Start();
AITask.Start();
AsyncRecordFromAIChannels();
AITask.WaitUntilDone();
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error during execution: " + e.Message);
FinalizeProtocol();
}
}
public override void StartContinuousExecute()
{
if (!IsContinuousRecordingSupported) throw new ApplicationException("Continuous execution is not supported.");
StopContinuousExecutionTrigger = false;
IsProtocolRunning = true;
Initialize();
System.Threading.ThreadStart exec = new System.Threading.ThreadStart(ContinuousExecute);
ContinuouslyExecutingThread = new System.Threading.Thread(exec);
ContinuouslyExecutingThread.Start();
}
protected virtual void ContinuousExecute()
{
WriteToAOChannels();
ConfigureChannelReaders();
while (!StopContinuousExecutionTrigger)
{
DateTime start = DateTime.Now;
try
{
IsOkToStartNextExecution = false;
if (TriggerRegenerationOfOutputWaveform)
{
GenerateTestPulseWaveform();
WriteToAOChannels();
TriggerRegenerationOfOutputWaveform = false;
}
AOTask.Start();
AITask.Start();
AsyncRecordFromAIChannels();
// Have to check for null because sometimes the protocol gets finalized before this is finished
if(AITask != null) AITask.WaitUntilDone();
if(AITask != null) AITask.Stop();
if(AOTask != null) AOTask.Stop();
}
catch (Exception e)
{
StopContinuousExecutionTrigger = true;
System.Windows.Forms.MessageBox.Show("Error during execution: " + e.Message);
FinalizeProtocol();
}
TimeSpan time = DateTime.Now - start;
System.Diagnostics.Debug.WriteLine("Test pulse took " + time.ToString());
}
}
public override void StopContinuousExecute()
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Stopping continuous execution.");
StopContinuousExecutionTrigger = true;
try
{
ContinuouslyExecutingThread.Join(AcquisitionLength * 2);
}
finally
{
ContinuouslyExecutingThread = null;
FinalizeProtocol();
IsProtocolRunning = false;
}
}
protected virtual void ConfigureChannelReaders()
{
System.Diagnostics.Debug.Assert(AITask != null, "TestPulseProtocol: No AITask at ConfigureChannelReaders.");
AIReader = new AnalogMultiChannelReader(AITask.Stream);
}
protected virtual void AsyncRecordFromAIChannels()
{
System.Diagnostics.Debug.Assert(AcquisitionLength * SampleRate / 1000 > 0);
IAsyncResult asyncRead = AIReader.BeginReadMultiSample(AcquisitionLength * SampleRate / 1000, new AsyncCallback(OnAIReadCompleted), null);
asyncRead.AsyncWaitHandle.WaitOne();
}
protected override void FinalizeProtocol()
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Finalizing protocol.");
try
{
if (AOTask != null)
{
AOTask.Dispose();
AOTask = null;
}
if (AITask != null)
{
AITask.Dispose();
AITask = null;
}
if (Amplifier != null && !Disposing)
{
Amplifier.ForwardAbsoluteVHoldSettingChange -= new ForwardAbsoluteVHoldSettingChange(ReceiveForwardedVHoldChange);
// Make sure the amplifier really got set to the holding potential
Amplifier.SetHoldingPotential(Amplifier.AbsoluteVHold);
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error during finalization: " + e.Message);
}
FireFinishedEvent(this, EventArgs.Empty);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (AITask != null) AITask.Dispose();
if (AOTask != null) AOTask.Dispose();
}
base.Dispose(disposing);
}
protected virtual void OnAIReadCompleted(IAsyncResult ar)
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: AI Read completed.");
if (AITask == null || Disposing) return; // Stop if the protocol was finalized before the read happened
double[,] data = AIReader.EndReadMultiSample(ar);
if (CachedTime == null)
{
CachedTime = new float[((int)AcquisitionLength) * SampleRate / 1000];
for (int i = 0; i < (SampleRate * AcquisitionLength / 1000); i++)
{
CachedTime[i] = ((float)i) * 1000 / ((float)SampleRate);
}
}
string[] channelNames = new string[ChannelNames.Count];
ChannelNames.CopyTo(channelNames, 0);
string[] units = new string[ChannelUnits.Count];
for (int i = 0; i < channelNames.Length; i++)
if (ChannelUnits.ContainsKey(channelNames[i]))
units[i] = ChannelUnits[channelNames[i]];
else units[i] = "Unknown";
DateTime start = DateTime.Now;
ContinuousExecutionSyncEvent.WaitOne();
TimeSpan span = DateTime.Now - start;
System.Diagnostics.Debug.WriteLine("Sync event wait took " + span.ToString());
StoreCollectedData(CachedTime, channelNames, data, units);
}
protected virtual void StoreCollectedData(float[] time, string[] channelNames, double[,] data, string[] units)
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Storing data.");
IsNewDataSet = false;
if (TriggerNewData && Data != null)
{
lock (DataSet)
{
Data = CreateNewRecording();
}
TriggerNewData = false;
IsNewDataSet = true;
}
else if (Data == null)
{
Data = CreateNewRecording();
TriggerNewData = false;
IsNewDataSet = true;
}
if (!IsNewDataSet)
{
Data.ClearData("Current");
Data.ClearEquipmentSettings();
Data.ClearMetaData();
Data.ClearProtocolSettings();
}
lock (DataSet)
{
int singleLength = data.Length / channelNames.Length;
for (int i = 0; i < channelNames.Length; i++)
{
double[] singleData = new double[singleLength];
for (int j = 0; j < singleLength; j++)
singleData[j] = data[i, j];
if (channelNames[i] == "Gain")
_Gain = singleData;
else if (channelNames[i] == "CellCapacitance")
_CellCapacitance = singleData;
else if (channelNames[i] == "Current")
_Current = singleData;
else if (IsNewDataSet)
Data.AddData(channelNames[i], units[i], time, singleData);
else Data.ReplaceData(channelNames[i], singleData);
}
}
ProcessData();
}
protected virtual void ConfigureChannels()
{
AOTask.AOChannels.CreateVoltageChannel(Amplifier.VHoldAO, "VHold", Amplifier.VHoldMin, Amplifier.VHoldMax, AOVoltageUnits.Volts);
AOTask.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;
AITask.AIChannels.CreateVoltageChannel(Amplifier.CurrentAI, "Current", AITerminalConfiguration.Rse, Amplifier.CurrentMin, Amplifier.CurrentMax, AIVoltageUnits.Volts);
ChannelNames.Add("Current");
ChannelUnits.Add("Current", "pA");
AITask.AIChannels.CreateVoltageChannel(Amplifier.GainAI, "Gain", AITerminalConfiguration.Rse, Amplifier.GainMin, Amplifier.GainMax, AIVoltageUnits.Volts);
ChannelNames.Add("Gain");
ChannelUnits.Add("Gain", "V");
AITask.AIChannels.CreateVoltageChannel(Amplifier.CapacAI, "CellCapacitance", AITerminalConfiguration.Rse, Amplifier.CapacMin, Amplifier.CapacMax, AIVoltageUnits.Volts);
ChannelNames.Add("CellCapacitance");
ChannelUnits.Add("CellCapacitance", "V");
}
protected virtual void WriteToAOChannels()
{
try
{
AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(AOTask.Stream);
double[] output = GenerateTestPulseWaveform();
writer.WriteMultiSample(false, output);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error: " + e.Message);
FinalizeProtocol();
}
}
protected virtual double[] GenerateTestPulseWaveform()
{
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Generating waveform.");
double[] output = new double[AcquisitionLength * SampleRate / 1000];
int nRestingSamples = RestingLength * SampleRate / 1000;
int nPulseSamples = PulseLength * SampleRate / 1000;
double restingVoltage =
(RestingPotential + Amplifier.AbsoluteVHold) * Amplifier.VoltageOutScalingFactor;
double pulseVoltage =
(PulsePotential + Amplifier.AbsoluteVHold) * Amplifier.VoltageOutScalingFactor;
for (int i = 0; i < nRestingSamples; i++)
output[i] = restingVoltage;
for (int i = nRestingSamples; i < (nRestingSamples + nPulseSamples); i++)
output[i] = pulseVoltage;
for (int i = (nRestingSamples + nPulseSamples); i < output.Length; i++)
output[i] = restingVoltage;
return output;
}
protected virtual bool ReceiveForwardedVHoldChange(double vhold)
{
TriggerRegenerationOfOutputWaveform = true;
return true;
}
protected override void ProcessData()
{
DateTime start = DateTime.Now;
lock (DataSet)
{
DateTime start2 = DateTime.Now;
// Get mean gain from Gain dataName
double gain = MathHelper.CalculateMean(_Gain);
// Convert current using amplifier gain information
double currentScalingFactor = Amplifier.CalculateVtoIFactorFromTTL(gain);
Data.AddEquipmentSetting("AmplifierGain", currentScalingFactor.ToString());
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Calculating gain took {0}.", DateTime.Now - start2));
start2 = DateTime.Now;
for(int i=0; i < _Current.Length; i++)
_Current[i] *= 1000 / currentScalingFactor; // *1000 b/c we want pA/V
Data.AddData("Current", "pA", CachedTime, _Current);
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Scaling current took {0}.", DateTime.Now - start2));
start2 = DateTime.Now;
// Determine capacitance correction value
// TODO: *** Make the beta switch part of the amplifier settings
double capac = MathHelper.CalculateMean(_CellCapacitance);
Data.AddEquipmentSetting("AmplifierCapacitanceCorrection", Amplifier.CalculateCellCapacitanceFromTTL(capac).ToString());
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Calculating cell capacitance took {0}.", DateTime.Now - start2));
}
DateTime start3 = DateTime.Now;
CalculateResistance();
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Calculating resistance took {0}.", DateTime.Now - start3));
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Processing data took {0}.", DateTime.Now - start));
base.ProcessData(); // Will call AnnotateData()
}
protected virtual void CalculateResistance()
{
double dV = PulsePotential - RestingPotential;
TimeResolvedData currentData = Data.GetData("Current");
float[] time = currentData.Time;
double[] current = currentData.Values;
double restI = MathHelper.CalculateMeanOverTimeRange(time, current, ((float)RestingLength) / 4, 3 * ((float)RestingLength) / 4); // pA
double pulseI = MathHelper.CalculateMeanOverTimeRange(time, current, ((float) RestingLength) + ((float)PulseLength) / 4, ((float)RestingLength) + 3 * ((float)PulseLength) / 4); // pA
double noise = MathHelper.CalculateStDevOverTimeRange(time, current, ((float)RestingLength) / 4, 3 * ((float)RestingLength) / 4); // pA
lock (DataSet)
{
Data.AddMetaData("BaselineCurrent", restI.ToString("f0"));
Data.AddMetaData("PeakCurrent", pulseI.ToString("f0"));
Data.AddMetaData("CurrentNoise", noise.ToString("f2"));
}
// Calculate resistance from Ohm's law (Rseal=dV/I)
// If the current is equal to the noise, return infinity
if (dV > 0 && (pulseI - restI) < 0) Resistance = Single.PositiveInfinity;
// Otherwise calculate proper resistance
else
{
double Rseal = dV * 1E-3 / (Math.Abs(pulseI - restI) * 1E-12);
Resistance = Convert.ToSingle(Rseal / 1E9); // Convert to Gigaohms
}
if (ResistanceChanged != null && !Disposing) ResistanceChanged(this, new EventArgs());
}
protected override void AnnotateData()
{
base.AnnotateData();
System.Diagnostics.Debug.Assert(Data != null, "TestPulseProtocol: Data null at annotating data.");
if (Data == null) return;
System.Diagnostics.Debug.WriteLine("TestPulseProtocol: Annotating data.");
DateTime start = DateTime.Now;
lock (DataSet)
{
Data.Title = "Test Pulse";
Data.AddProtocolSetting("RestingPotential", RestingPotential.ToString());
Data.AddProtocolSetting("RestingLength", RestingLength.ToString());
Data.AddProtocolSetting("PulsePotential", PulsePotential.ToString());
Data.AddProtocolSetting("PulseLength", PulseLength.ToString());
Data.AddEquipmentSetting("SampleRate", SampleRate.ToString());
Data.AddMetaData("Resistance", Resistance.ToString());
}
Amplifier.AnnotateEquipmentData(Data);
System.Diagnostics.Debug.WriteLine(String.Format("TestPulseProtocol: Annotating data took {0}.", DateTime.Now - start));
}
public override System.Windows.Forms.Control GetConfigurationControl()
{
RRLab.PhysiologyWorkbench.TestPulseSettingsBox control = new TestPulseSettingsBox();
control.TestPulseProtocol = this;
return control;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
#if !NET_NATIVE
namespace System.Xml.Serialization
{
internal class SourceInfo
{
//a[ia]
//((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0])
private static Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?");
//((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true);
private static Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]");
public string Source;
public readonly string Arg;
public readonly MemberInfo MemberInfo;
public readonly Type Type;
public readonly CodeGenerator ILG;
public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg)
{
this.Source = source;
this.Arg = arg ?? source;
this.MemberInfo = memberInfo;
this.Type = type;
this.ILG = ilg;
}
public SourceInfo CastTo(TypeDesc td)
{
return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG);
}
public void LoadAddress(Type elementType)
{
InternalLoad(elementType, asAddress: true);
}
public void Load(Type elementType)
{
InternalLoad(elementType);
}
private void InternalLoad(Type elementType, bool asAddress = false)
{
Match match = s_regex.Match(Arg);
if (match.Success)
{
object varA = ILG.GetVariable(match.Groups["a"].Value);
Type varType = ILG.GetVariableType(varA);
object varIA = ILG.GetVariable(match.Groups["ia"].Value);
if (varType.IsArray)
{
ILG.Load(varA);
ILG.Load(varIA);
Type eType = varType.GetElementType();
if (CodeGenerator.IsNullableGenericType(eType))
{
ILG.Ldelema(eType);
ConvertNullableValue(eType, elementType);
}
else
{
if (eType.GetTypeInfo().IsValueType)
{
ILG.Ldelema(eType);
if (!asAddress)
{
ILG.Ldobj(eType);
}
}
else
ILG.Ldelem(eType);
if (elementType != null)
ILG.ConvertValue(eType, elementType);
}
}
else
{
ILG.Load(varA);
ILG.Load(varIA);
MethodInfo get_Item = varType.GetMethod(
"get_Item",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Int32) }
);
Debug.Assert(get_Item != null);
ILG.Call(get_Item);
Type eType = get_Item.ReturnType;
if (CodeGenerator.IsNullableGenericType(eType))
{
LocalBuilder localTmp = ILG.GetTempLocal(eType);
ILG.Stloc(localTmp);
ILG.Ldloca(localTmp);
ConvertNullableValue(eType, elementType);
}
else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType)))
{
throw new InvalidOperationException(SR.Format(SR.IsNotAssignableFrom, eType.GetTypeInfo().AssemblyQualifiedName, elementType.GetTypeInfo().AssemblyQualifiedName));
}
else
{
Convert(eType, elementType, asAddress);
}
}
}
else if (Source == "null")
{
ILG.Load(null);
}
else
{
object var;
Type varType;
if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null)
{
var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg);
varType = ILG.GetVariableType(var);
if (varType.GetTypeInfo().IsValueType)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
else
{
var = ILG.GetVariable(Arg);
varType = ILG.GetVariableType(var);
if (CodeGenerator.IsNullableGenericType(varType) &&
varType.GetGenericArguments()[0] == elementType)
{
ILG.LoadAddress(var);
ConvertNullableValue(varType, elementType);
}
else
{
if (asAddress)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
}
if (MemberInfo != null)
{
Type memberType = (MemberInfo is FieldInfo) ?
((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType;
if (CodeGenerator.IsNullableGenericType(memberType))
{
ILG.LoadMemberAddress(MemberInfo);
ConvertNullableValue(memberType, elementType);
}
else
{
ILG.LoadMember(MemberInfo);
Convert(memberType, elementType, asAddress);
}
}
else
{
match = s_regex2.Match(Source);
if (match.Success)
{
Debug.Assert(match.Groups["arg"].Value == Arg);
Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type));
if (asAddress)
ILG.ConvertAddress(varType, Type);
else
ILG.ConvertValue(varType, Type);
varType = Type;
}
Convert(varType, elementType, asAddress);
}
}
}
private void Convert(Type sourceType, Type targetType, bool asAddress)
{
if (targetType != null)
{
if (asAddress)
ILG.ConvertAddress(sourceType, targetType);
else
ILG.ConvertValue(sourceType, targetType);
}
}
private void ConvertNullableValue(Type nullableType, Type targetType)
{
System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0]));
if (targetType != nullableType)
{
MethodInfo Nullable_get_Value = nullableType.GetMethod(
"get_Value",
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ILG.Call(Nullable_get_Value);
if (targetType != null)
{
ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType);
}
}
}
public static implicit operator string (SourceInfo source)
{
return source.Source;
}
public static bool operator !=(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return !a.Equals(b);
return (object)b != null;
}
public static bool operator ==(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return a.Equals(b);
return (object)b == null;
}
public override bool Equals(object obj)
{
if (obj == null)
return Source == null;
SourceInfo info = obj as SourceInfo;
if (info != null)
return Source == info.Source;
return false;
}
public override int GetHashCode()
{
return (Source == null) ? 0 : Source.GetHashCode();
}
}
}
#endif
| |
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using umbraco.editorControls.tinymce;
using umbraco.editorControls.tinyMCE3.webcontrol;
using umbraco.editorControls.wysiwyg;
using umbraco.interfaces;
using Umbraco.Core.IO;
using umbraco.presentation;
using umbraco.uicontrols;
namespace umbraco.editorControls.tinyMCE3
{
[Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
public class TinyMCE : TinyMCEWebControl, IDataEditor, IMenuElement
{
private readonly string _activateButtons = "";
private readonly string _advancedUsers = "";
private readonly SortedList _buttons = new SortedList();
private readonly IData _data;
private readonly string _disableButtons = "help,visualaid,";
private readonly string _editorButtons = "";
private readonly bool _enableContextMenu;
private readonly bool _fullWidth;
private readonly int _height;
private readonly SortedList _mceButtons = new SortedList();
private readonly ArrayList _menuIcons = new ArrayList();
private readonly bool _showLabel;
private readonly ArrayList _stylesheets = new ArrayList();
private readonly int _width;
private readonly int m_maxImageWidth = 500;
private bool _isInitialized;
private string _plugins = "";
public TinyMCE(IData Data, string Configuration)
{
_data = Data;
try
{
string[] configSettings = Configuration.Split("|".ToCharArray());
if (configSettings.Length > 0)
{
_editorButtons = configSettings[0];
if (configSettings.Length > 1)
if (configSettings[1] == "1")
_enableContextMenu = true;
if (configSettings.Length > 2)
_advancedUsers = configSettings[2];
if (configSettings.Length > 3)
{
if (configSettings[3] == "1")
_fullWidth = true;
else if (configSettings[4].Split(',').Length > 1)
{
_width = int.Parse(configSettings[4].Split(',')[0]);
_height = int.Parse(configSettings[4].Split(',')[1]);
}
}
// default width/height
if (_width < 1)
_width = 500;
if (_height < 1)
_height = 400;
// add stylesheets
if (configSettings.Length > 4)
{
foreach (string s in configSettings[5].Split(",".ToCharArray()))
_stylesheets.Add(s);
}
if (configSettings.Length > 6 && configSettings[6] != "")
_showLabel = bool.Parse(configSettings[6]);
if (configSettings.Length > 7 && configSettings[7] != "")
m_maxImageWidth = int.Parse(configSettings[7]);
// sizing
if (!_fullWidth)
{
config.Add("width", _width.ToString());
config.Add("height", _height.ToString());
}
if (_enableContextMenu)
_plugins += ",contextmenu";
// If the editor is used in umbraco, use umbraco's own toolbar
bool onFront = false;
if (GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current))
{
config.Add("theme_umbraco_toolbar_location", "external");
config.Add("skin", "umbraco");
config.Add("inlinepopups_skin ", "umbraco");
}
else
{
onFront = true;
config.Add("theme_umbraco_toolbar_location", "top");
}
// load plugins
IDictionaryEnumerator pluginEnum = tinyMCEConfiguration.Plugins.GetEnumerator();
while (pluginEnum.MoveNext())
{
var plugin = (tinyMCEPlugin)pluginEnum.Value;
if (plugin.UseOnFrontend || (!onFront && !plugin.UseOnFrontend))
_plugins += "," + plugin.Name;
}
// add the umbraco overrides to the end
// NB: It is !!REALLY IMPORTANT!! that these plugins are added at the end
// as they make runtime modifications to default plugins, so require
// those plugins to be loaded first.
_plugins += ",umbracopaste,umbracolink,umbracocontextmenu";
if (_plugins.StartsWith(","))
_plugins = _plugins.Substring(1, _plugins.Length - 1);
if (_plugins.EndsWith(","))
_plugins = _plugins.Substring(0, _plugins.Length - 1);
config.Add("plugins", _plugins);
// Check advanced settings
if (UmbracoEnsuredPage.CurrentUser != null && ("," + _advancedUsers + ",").IndexOf("," + UmbracoEnsuredPage.CurrentUser.UserType.Id + ",") >
-1)
config.Add("umbraco_advancedMode", "true");
else
config.Add("umbraco_advancedMode", "false");
// Check maximum image width
config.Add("umbraco_maximumDefaultImageWidth", m_maxImageWidth.ToString());
// Styles
string cssFiles = String.Empty;
string styles = string.Empty;
foreach (string styleSheetId in _stylesheets)
{
if (styleSheetId.Trim() != "")
try
{
//TODO: Fix this, it will no longer work!
var s = StyleSheet.GetStyleSheet(int.Parse(styleSheetId), false, false);
if (s.nodeObjectType == StyleSheet.ModuleObjectType)
{
cssFiles += IOHelper.ResolveUrl(SystemDirectories.Css + "/" + s.Text + ".css");
foreach (StylesheetProperty p in s.Properties)
{
if (styles != string.Empty)
{
styles += ";";
}
if (p.Alias.StartsWith("."))
styles += p.Text + "=" + p.Alias;
else
styles += p.Text + "=" + p.Alias;
}
cssFiles += ",";
}
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>("Error adding stylesheet to tinymce Id:" + styleSheetId, ee);
}
}
// remove any ending comma (,)
if (!string.IsNullOrEmpty(cssFiles))
{
cssFiles = cssFiles.TrimEnd(',');
}
// language
string userLang = (UmbracoEnsuredPage.CurrentUser != null) ?
(User.GetCurrent().Language.Contains("-") ?
User.GetCurrent().Language.Substring(0, User.GetCurrent().Language.IndexOf("-")) : User.GetCurrent().Language)
: "en";
config.Add("language", userLang);
config.Add("content_css", cssFiles);
config.Add("theme_umbraco_styles", styles);
// Add buttons
IDictionaryEnumerator ide = tinyMCEConfiguration.Commands.GetEnumerator();
while (ide.MoveNext())
{
var cmd = (tinyMCECommand)ide.Value;
if (_editorButtons.IndexOf("," + cmd.Alias + ",") > -1)
_activateButtons += cmd.Alias + ",";
else
_disableButtons += cmd.Alias + ",";
}
if (_activateButtons.Length > 0)
_activateButtons = _activateButtons.Substring(0, _activateButtons.Length - 1);
if (_disableButtons.Length > 0)
_disableButtons = _disableButtons.Substring(0, _disableButtons.Length - 1);
// Add buttons
initButtons();
_activateButtons = "";
int separatorPriority = 0;
ide = _mceButtons.GetEnumerator();
while (ide.MoveNext())
{
string mceCommand = ide.Value.ToString();
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_activateButtons += "separator,";
_activateButtons += mceCommand + ",";
separatorPriority = curPriority;
}
config.Add("theme_umbraco_buttons1", _activateButtons);
config.Add("theme_umbraco_buttons2", "");
config.Add("theme_umbraco_buttons3", "");
config.Add("theme_umbraco_toolbar_align", "left");
config.Add("theme_umbraco_disable", _disableButtons);
config.Add("theme_umbraco_path ", "true");
config.Add("extended_valid_elements", "div[*]");
config.Add("document_base_url", "/");
config.Add("relative_urls", "false");
config.Add("remove_script_host", "true");
config.Add("event_elements", "div");
config.Add("paste_auto_cleanup_on_paste", "true");
config.Add("valid_elements",
tinyMCEConfiguration.ValidElements.Substring(1,
tinyMCEConfiguration.ValidElements.Length -
2));
config.Add("invalid_elements", tinyMCEConfiguration.InvalidElements);
// custom commands
if (tinyMCEConfiguration.ConfigOptions.Count > 0)
{
ide = tinyMCEConfiguration.ConfigOptions.GetEnumerator();
while (ide.MoveNext())
{
config.Add(ide.Key.ToString(), ide.Value.ToString());
}
}
//if (HttpContext.Current.Request.Path.IndexOf(Umbraco.Core.IO.SystemDirectories.Umbraco) > -1)
// config.Add("language", User.GetUser(BasePage.GetUserId(BasePage.umbracoUserContextID)).Language);
//else
// config.Add("language", System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);
if (_fullWidth)
{
config.Add("auto_resize", "true");
base.Columns = 30;
base.Rows = 30;
}
else
{
base.Columns = 0;
base.Rows = 0;
}
EnableViewState = false;
}
}
catch (Exception ex)
{
throw new ArgumentException("Incorrect TinyMCE configuration.", "Configuration", ex);
}
}
#region TreatAsRichTextEditor
public virtual bool TreatAsRichTextEditor
{
get { return false; }
}
#endregion
#region ShowLabel
public virtual bool ShowLabel
{
get { return _showLabel; }
}
#endregion
#region Editor
public Control Editor
{
get { return this; }
}
#endregion
#region Save()
public virtual void Save()
{
string parsedString = base.Text.Trim();
string parsedStringForTinyMce = parsedString;
if (parsedString != string.Empty)
{
parsedString = replaceMacroTags(parsedString).Trim();
// tidy html - refactored, see #30534
if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent)
{
// always wrap in a <div> - using <p> was a bad idea
parsedString = "<div>" + parsedString + "</div>";
string tidyTxt = library.Tidy(parsedString, false);
if (tidyTxt != "[error]")
{
parsedString = tidyTxt;
// remove pesky \r\n, and other empty chars
parsedString = parsedString.Trim(new char[] { '\r', '\n', '\t', ' ' });
// compensate for breaking macro tags by tidy (?)
parsedString = parsedString.Replace("/?>", "/>");
// remove the wrapping <div> - safer to check that it is still here
if (parsedString.StartsWith("<div>") && parsedString.EndsWith("</div>"))
parsedString = parsedString.Substring("<div>".Length, parsedString.Length - "<div></div>".Length);
}
}
// rescue umbraco tags
parsedString = parsedString.Replace("|||?", "<?").Replace("/|||", "/>").Replace("|*|", "\"");
// fix images
parsedString = tinyMCEImageHelper.cleanImages(parsedString);
// parse current domain and instances of slash before anchor (to fix anchor bug)
// NH 31-08-2007
if (HttpContext.Current.Request.ServerVariables != null)
{
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current) + "/#", "#");
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current), "");
}
// if a paragraph is empty, remove it
if (parsedString.ToLower() == "<p></p>")
parsedString = "";
// save string after all parsing is done, but before CDATA replacement - to put back into TinyMCE
parsedStringForTinyMce = parsedString;
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
parsedString = parsedString.Replace("<![CDATA[", "<!--CDATAOPENTAG-->").Replace("]]>", "<!--CDATACLOSETAG-->");
}
_data.Value = parsedString;
// update internal webcontrol value with parsed result
base.Text = parsedStringForTinyMce;
}
#endregion
public virtual string Plugins
{
get { return _plugins; }
set { _plugins = value; }
}
public object[] MenuIcons
{
get
{
initButtons();
var tempIcons = new object[_menuIcons.Count];
for (int i = 0; i < _menuIcons.Count; i++)
tempIcons[i] = _menuIcons[i];
return tempIcons;
}
}
#region IMenuElement Members
public string ElementName
{
get { return "div"; }
}
public string ElementIdPreFix
{
get { return "umbTinymceMenu"; }
}
public string ElementClass
{
get { return "tinymceMenuBar"; }
}
public int ExtraMenuWidth
{
get
{
initButtons();
return _buttons.Count * 40 + 300;
}
}
#endregion
protected override void OnLoad(EventArgs e)
{
try
{
// add current page info
base.NodeId = ((cms.businesslogic.datatype.DefaultData)_data).NodeId;
if (NodeId != 0)
{
base.VersionId = ((cms.businesslogic.datatype.DefaultData)_data).Version;
config.Add("theme_umbraco_pageId", base.NodeId.ToString());
config.Add("theme_umbraco_versionId", base.VersionId.ToString());
// we'll need to make an extra check for the liveediting as that value is set after the constructor have initialized
config.Add("umbraco_toolbar_id",
ElementIdPreFix +
((cms.businesslogic.datatype.DefaultData)_data).PropertyId);
}
else
{
// this is for use when tinymce is used for non default Umbraco pages
config.Add("umbraco_toolbar_id",
ElementIdPreFix + "_" + this.ClientID);
}
}
catch
{
// Empty catch as this is caused by the document doesn't exists yet,
// like when using this on an autoform, partly replaced by the if/else check on nodeId above though
}
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
if (_data != null && _data.Value != null)
base.Text = _data.Value.ToString().Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>");
}
private string replaceMacroTags(string text)
{
while (findStartTag(text) > -1)
{
string result = text.Substring(findStartTag(text), findEndTag(text) - findStartTag(text));
text = text.Replace(result, generateMacroTag(result));
}
return text;
}
private string generateMacroTag(string macroContent)
{
string macroAttr = macroContent.Substring(5, macroContent.IndexOf(">") - 5);
string macroTag = "|||?UMBRACO_MACRO ";
Hashtable attributes = ReturnAttributes(macroAttr);
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
{
if (ide.Key.ToString().IndexOf("umb_") != -1)
{
// Hack to compensate for Firefox adding all attributes as lowercase
string orgKey = ide.Key.ToString();
if (orgKey == "umb_macroalias")
orgKey = "umb_macroAlias";
macroTag += orgKey.Substring(4, orgKey.Length - 4) + "=|*|" +
ide.Value.ToString().Replace("\\r\\n", Environment.NewLine) + "|*| ";
}
}
macroTag += "/|||";
return macroTag;
}
[Obsolete("Has been superceded by Umbraco.Core.XmlHelper.GetAttributesFromElement")]
public static Hashtable ReturnAttributes(String tag)
{
var h = new Hashtable();
foreach (var i in Umbraco.Core.XmlHelper.GetAttributesFromElement(tag))
{
h.Add(i.Key, i.Value);
}
return h;
}
private int findStartTag(string text)
{
string temp = "";
text = text.ToLower();
if (text.IndexOf("ismacro=\"true\"") > -1)
{
temp = text.Substring(0, text.IndexOf("ismacro=\"true\""));
return temp.LastIndexOf("<");
}
return -1;
}
private int findEndTag(string text)
{
string find = "<!-- endumbmacro -->";
int endMacroIndex = text.ToLower().IndexOf(find);
string tempText = text.ToLower().Substring(endMacroIndex + find.Length,
text.Length - endMacroIndex - find.Length);
int finalEndPos = 0;
while (tempText.Length > 5)
if (tempText.Substring(finalEndPos, 6) == "</div>")
break;
else
finalEndPos++;
return endMacroIndex + find.Length + finalEndPos + 6;
}
private void initButtons()
{
if (!_isInitialized)
{
_isInitialized = true;
// Add icons for the editor control:
// Html
// Preview
// Style picker, showstyles
// Bold, italic, Text Gen
// Align: left, center, right
// Lists: Bullet, Ordered, indent, undo indent
// Link, Anchor
// Insert: Image, macro, table, formular
foreach (string button in _activateButtons.Split(','))
{
if (button.Trim() != "")
{
try
{
var cmd = (tinyMCECommand)tinyMCEConfiguration.Commands[button];
string appendValue = "";
if (cmd.Value != "")
appendValue = ", '" + cmd.Value + "'";
_mceButtons.Add(cmd.Priority, cmd.Command);
_buttons.Add(cmd.Priority,
new editorButton(cmd.Alias, ui.Text("buttons", cmd.Alias), cmd.Icon,
"tinyMCE.execInstanceCommand('" + ClientID + "', '" +
cmd.Command + "', " + cmd.UserInterface + appendValue + ")"));
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>(string.Format("TinyMCE: Error initializing button '{0}'", button), ee);
}
}
}
// add save icon
int separatorPriority = 0;
IDictionaryEnumerator ide = _buttons.GetEnumerator();
while (ide.MoveNext())
{
object buttonObj = ide.Value;
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_menuIcons.Add("|");
try
{
var e = (editorButton)buttonObj;
MenuIconI menuItem = new MenuIconClass();
menuItem.OnClickCommand = e.onClickCommand;
menuItem.ImageURL = e.imageUrl;
menuItem.AltText = e.alttag;
menuItem.ID = e.id;
_menuIcons.Add(menuItem);
}
catch
{
}
separatorPriority = curPriority;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: A representation of a 32 bit 2's complement
** integer.
**
**
===========================================================*/
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Int32 : IComparable, IConvertible, IFormattable, IComparable<Int32>, IEquatable<Int32>
{
private int m_value; // Do not rename (binary serialization)
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns :
// 0 if the values are equal
// Negative number if _value is less than value
// Positive number if _value is more than value
// null is considered to be less than any instance, hence returns positive number
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int32)
{
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt32);
}
public int CompareTo(int value)
{
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int32))
{
return false;
}
return m_value == ((Int32)obj).m_value;
}
[NonVersionable]
public bool Equals(Int32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return m_value;
}
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public static int Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s.AsSpan(), style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider));
}
public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, out Int32 result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseInt32(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out int result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return m_value;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public abstract class HttpContent : IDisposable
{
private HttpContentHeaders _headers;
private MemoryStream _bufferedContent;
private bool _disposed;
private Stream _contentReadStream;
private bool _canCalculateLength;
internal const long MaxBufferSize = Int32.MaxValue;
internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8;
// These encodings have Byte-Order-Markers that we will use to detect the encoding.
private static Encoding[] s_encodingsWithBom =
{
Encoding.UTF8, // EF BB BF
#if NETNative
// Not supported on Phone
#else
// UTF32 Must be before Unicode because its BOM is similar but longer.
Encoding.UTF32, // FF FE 00 00
#endif
Encoding.Unicode, // FF FE
Encoding.BigEndianUnicode, // FE FF
};
public HttpContentHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpContentHeaders(GetComputedOrBufferLength);
}
return _headers;
}
}
private bool IsBuffered
{
get { return _bufferedContent != null; }
}
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
if (Logging.On) Logging.Enter(Logging.Http, this, ".ctor", null);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
if (Logging.On) Logging.Exit(Logging.Http, this, ".ctor", null);
}
public Task<string> ReadAsStringAsync()
{
CheckDisposed();
var tcs = new TaskCompletionSource<string>(this);
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<string>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
return;
}
if (innerThis._bufferedContent.Length == 0)
{
innerTcs.TrySetResult(string.Empty);
return;
}
// We don't validate the Content-Encoding header: If the content was encoded, it's the caller's
// responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the
// Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a
// decoded response stream.
Encoding encoding = null;
int bomLength = -1;
byte[] data = innerThis.GetDataBuffer(innerThis._bufferedContent);
int dataLength = (int)innerThis._bufferedContent.Length; // Data is the raw buffer, it may not be full.
// If we do have encoding information in the 'Content-Type' header, use that information to convert
// the content to a string.
if ((innerThis.Headers.ContentType != null) && (innerThis.Headers.ContentType.CharSet != null))
{
try
{
encoding = Encoding.GetEncoding(innerThis.Headers.ContentType.CharSet);
}
catch (ArgumentException e)
{
innerTcs.TrySetException(new InvalidOperationException(SR.net_http_content_invalid_charset, e));
return;
}
}
// If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present,
// then check for a byte-order-mark (BOM) in the data to figure out the encoding.
if (encoding == null)
{
byte[] preamble;
foreach (Encoding testEncoding in s_encodingsWithBom)
{
preamble = testEncoding.GetPreamble();
if (ByteArrayHasPrefix(data, dataLength, preamble))
{
encoding = testEncoding;
bomLength = preamble.Length;
break;
}
}
}
// Use the default encoding if we couldn't detect one.
encoding = encoding ?? DefaultStringEncoding;
// BOM characters may be present even if a charset was specified.
if (bomLength == -1)
{
byte[] preamble = encoding.GetPreamble();
if (ByteArrayHasPrefix(data, dataLength, preamble))
bomLength = preamble.Length;
else
bomLength = 0;
}
try
{
// Drop the BOM when decoding the data.
string result = encoding.GetString(data, bomLength, dataLength - bomLength);
innerTcs.TrySetResult(result);
}
catch (Exception ex)
{
innerTcs.TrySetException(ex);
}
});
return tcs.Task;
}
public Task<byte[]> ReadAsByteArrayAsync()
{
CheckDisposed();
var tcs = new TaskCompletionSource<byte[]>(this);
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<byte[]>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerTcs.TrySetResult(innerThis._bufferedContent.ToArray());
}
});
return tcs.Task;
}
public Task<Stream> ReadAsStreamAsync()
{
CheckDisposed();
TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>(this);
if (_contentReadStream == null && IsBuffered)
{
byte[] data = this.GetDataBuffer(_bufferedContent);
// We can cast bufferedContent.Length to 'int' since the length will always be in the 'int' range
// The .NET Framework doesn't support array lengths > int.MaxValue.
Debug.Assert(_bufferedContent.Length <= (long)int.MaxValue);
_contentReadStream = new MemoryStream(data, 0,
(int)_bufferedContent.Length, false);
}
if (_contentReadStream != null)
{
tcs.TrySetResult(_contentReadStream);
return tcs.Task;
}
CreateContentReadStreamAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<Stream>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerThis._contentReadStream = task.Result;
innerTcs.TrySetResult(innerThis._contentReadStream);
}
});
return tcs.Task;
}
protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context);
public Task CopyToAsync(Stream stream, TransportContext context)
{
CheckDisposed();
if (stream == null)
{
throw new ArgumentNullException("stream");
}
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
try
{
Task task = null;
if (IsBuffered)
{
byte[] data = this.GetDataBuffer(_bufferedContent);
task = stream.WriteAsync(data, 0, (int)_bufferedContent.Length);
}
else
{
task = SerializeToStreamAsync(stream, context);
CheckTaskNotNull(task);
}
// If the copy operation fails, wrap the exception in an HttpRequestException() if appropriate.
task.ContinueWithStandard(tcs, (copyTask, state) =>
{
var innerTcs = (TaskCompletionSource<object>)state;
if (copyTask.IsFaulted)
{
innerTcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException()));
}
else if (copyTask.IsCanceled)
{
innerTcs.TrySetCanceled();
}
else
{
innerTcs.TrySetResult(null);
}
});
}
catch (IOException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
catch (ObjectDisposedException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
return tcs.Task;
}
public Task CopyToAsync(Stream stream)
{
return CopyToAsync(stream, null);
}
public Task LoadIntoBufferAsync()
{
return LoadIntoBufferAsync(MaxBufferSize);
}
// No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting
// in an exception being thrown while we're buffering.
// If buffering is used without a connection, it is supposed to be fast, thus no cancellation required.
public Task LoadIntoBufferAsync(long maxBufferSize)
{
CheckDisposed();
if (maxBufferSize > HttpContent.MaxBufferSize)
{
// This should only be hit when called directly; HttpClient/HttpClientHandler
// will not exceed this limit.
throw new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
if (IsBuffered)
{
// If we already buffered the content, just return a completed task.
return CreateCompletedTask();
}
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Exception error = null;
MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error);
if (tempBuffer == null)
{
// We don't throw in LoadIntoBufferAsync(): set the task as faulted and return the task.
Debug.Assert(error != null);
tcs.TrySetException(error);
}
else
{
try
{
Task task = SerializeToStreamAsync(tempBuffer, null);
CheckTaskNotNull(task);
task.ContinueWithStandard(copyTask =>
{
try
{
if (copyTask.IsFaulted)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
tcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException()));
return;
}
if (copyTask.IsCanceled)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
tcs.TrySetCanceled();
return;
}
tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data.
_bufferedContent = tempBuffer;
tcs.TrySetResult(null);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
tcs.TrySetException(e);
if (Logging.On) Logging.Exception(Logging.Http, this, "LoadIntoBufferAsync", e);
}
});
}
catch (IOException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
catch (ObjectDisposedException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
}
return tcs.Task;
}
protected virtual Task<Stream> CreateContentReadStreamAsync()
{
var tcs = new TaskCompletionSource<Stream>(this);
// By default just buffer the content to a memory stream. Derived classes can override this behavior
// if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient
// way, like wrapping a read-only MemoryStream around the bytes/string)
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<Stream>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerTcs.TrySetResult(innerThis._bufferedContent);
}
});
return tcs.Task;
}
// Derived types return true if they're able to compute the length. It's OK if derived types return false to
// indicate that they're not able to compute the length. The transport channel needs to decide what to do in
// that case (send chunked, buffer first, etc.).
protected internal abstract bool TryComputeLength(out long length);
private long? GetComputedOrBufferLength()
{
CheckDisposed();
if (IsBuffered)
{
return _bufferedContent.Length;
}
// If we already tried to calculate the length, but the derived class returned 'false', then don't try
// again; just return null.
if (_canCalculateLength)
{
long length = 0;
if (TryComputeLength(out length))
{
return length;
}
// Set flag to make sure next time we don't try to compute the length, since we know that we're unable
// to do so.
_canCalculateLength = false;
}
return null;
}
private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
Contract.Ensures((Contract.Result<MemoryStream>() != null) ||
(Contract.ValueAtReturn<Exception>(out error) != null));
error = null;
// If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
// content length exceeds the max. buffer size.
long? contentLength = Headers.ContentLength;
if (contentLength != null)
{
Debug.Assert(contentLength >= 0);
if (contentLength > maxBufferSize)
{
error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
return null;
}
// We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize.
return new LimitMemoryStream((int)maxBufferSize, (int)contentLength);
}
// We couldn't determine the length of the buffer. Create a memory stream with an empty buffer.
return new LimitMemoryStream((int)maxBufferSize, 0);
}
private byte[] GetDataBuffer(MemoryStream stream)
{
// TODO: Use TryGetBuffer() instead of ToArray().
return stream.ToArray();
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
if (_contentReadStream != null)
{
_contentReadStream.Dispose();
}
if (IsBuffered)
{
_bufferedContent.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Helpers
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private void CheckTaskNotNull(Task task)
{
if (task == null)
{
if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString()));
throw new InvalidOperationException(SR.net_http_content_no_task_returned);
}
}
private static Task CreateCompletedTask()
{
TaskCompletionSource<object> completed = new TaskCompletionSource<object>();
bool resultSet = completed.TrySetResult(null);
Debug.Assert(resultSet, "Can't set Task as completed.");
return completed.Task;
}
private static Exception GetStreamCopyException(Exception originalException)
{
// HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
// provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
// types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
// exceptions (depending on the underlying transport), but just HttpRequestExceptions
// Custom stream should throw either IOException or HttpRequestException.
// We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
// don't want to hide such "usage error" exceptions in HttpRequestException.
// ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
// the response stream being closed.
Exception result = originalException;
if ((result is IOException) || (result is ObjectDisposedException))
{
result = new HttpRequestException(SR.net_http_content_stream_copy_error, result);
}
return result;
}
private static bool ByteArrayHasPrefix(byte[] byteArray, int dataLength, byte[] prefix)
{
if (prefix == null || byteArray == null || prefix.Length > dataLength || prefix.Length == 0)
return false;
for (int i = 0; i < prefix.Length; i++)
{
if (prefix[i] != byteArray[i])
return false;
}
return true;
}
#endregion Helpers
private class LimitMemoryStream : MemoryStream
{
private int _maxSize;
public LimitMemoryStream(int maxSize, int capacity)
: base(capacity)
{
_maxSize = maxSize;
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckSize(count);
base.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
CheckSize(1);
base.WriteByte(value);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckSize(count);
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
private void CheckSize(int countToAdd)
{
if (_maxSize - Length < countToAdd)
{
throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, _maxSize));
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataLake.Store;
using Microsoft.Azure.Management.DataLake.Store.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataLake.Store
{
/// <summary>
/// Creates a Data Lake Store account management client.
/// </summary>
public partial class DataLakeStoreManagementClient : ServiceClient<DataLakeStoreManagementClient>, IDataLakeStoreManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _userAgentSuffix;
/// <summary>
/// Gets or sets the additional UserAgent text to be added to the user
/// agent header. This is used to further differentiate where requests
/// are coming from internally.
/// </summary>
public string UserAgentSuffix
{
get { return this._userAgentSuffix; }
set { this._userAgentSuffix = value; }
}
private IDataLakeStoreAccountOperations _dataLakeStoreAccount;
/// <summary>
/// Operations for managing Data Lake Store accounts
/// </summary>
public virtual IDataLakeStoreAccountOperations DataLakeStoreAccount
{
get { return this._dataLakeStoreAccount; }
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
public DataLakeStoreManagementClient()
: base()
{
this._dataLakeStoreAccount = new DataLakeStoreAccountOperations(this);
this._userAgentSuffix = "";
this._apiVersion = "2015-10-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataLakeStoreManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._dataLakeStoreAccount = new DataLakeStoreAccountOperations(this);
this._userAgentSuffix = "";
this._apiVersion = "2015-10-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public DataLakeStoreManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// DataLakeStoreManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of DataLakeStoreManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<DataLakeStoreManagementClient> client)
{
base.Clone(client);
if (client is DataLakeStoreManagementClient)
{
DataLakeStoreManagementClient clonedClient = ((DataLakeStoreManagementClient)client);
clonedClient._userAgentSuffix = this._userAgentSuffix;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type DataLakeStoreAccountState.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static DataLakeStoreAccountState ParseDataLakeStoreAccountState(string value)
{
if ("active".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountState.Active;
}
if ("suspended".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountState.Suspended;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type DataLakeStoreAccountState to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string DataLakeStoreAccountStateToString(DataLakeStoreAccountState value)
{
if (value == DataLakeStoreAccountState.Active)
{
return "active";
}
if (value == DataLakeStoreAccountState.Suspended)
{
return "suspended";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type DataLakeStoreAccountStatus.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static DataLakeStoreAccountStatus ParseDataLakeStoreAccountStatus(string value)
{
if ("Failed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Failed;
}
if ("Creating".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Creating;
}
if ("Running".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Running;
}
if ("Succeeded".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Succeeded;
}
if ("Patching".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Patching;
}
if ("Suspending".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Suspending;
}
if ("Resuming".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Resuming;
}
if ("Deleting".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Deleting;
}
if ("Deleted".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return DataLakeStoreAccountStatus.Deleted;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type DataLakeStoreAccountStatus to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string DataLakeStoreAccountStatusToString(DataLakeStoreAccountStatus value)
{
if (value == DataLakeStoreAccountStatus.Failed)
{
return "Failed";
}
if (value == DataLakeStoreAccountStatus.Creating)
{
return "Creating";
}
if (value == DataLakeStoreAccountStatus.Running)
{
return "Running";
}
if (value == DataLakeStoreAccountStatus.Succeeded)
{
return "Succeeded";
}
if (value == DataLakeStoreAccountStatus.Patching)
{
return "Patching";
}
if (value == DataLakeStoreAccountStatus.Suspending)
{
return "Suspending";
}
if (value == DataLakeStoreAccountStatus.Resuming)
{
return "Resuming";
}
if (value == DataLakeStoreAccountStatus.Deleting)
{
return "Deleting";
}
if (value == DataLakeStoreAccountStatus.Deleted)
{
return "Deleted";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='azureAsyncOperation'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken)
{
// Validate
if (azureAsyncOperation == null)
{
throw new ArgumentNullException("azureAsyncOperation");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("azureAsyncOperation", azureAsyncOperation);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + azureAsyncOperation;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-10-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureAsyncOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AzureAsyncOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
result.Status = statusInstance;
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
Error errorInstance = new Error();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = errorValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JToken detailsArray = errorValue["details"];
if (detailsArray != null && detailsArray.Type != JTokenType.Null)
{
foreach (JToken detailsValue in ((JArray)detailsArray))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
errorInstance.Details.Add(errorDetailsInstance);
JToken codeValue2 = detailsValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorDetailsInstance.Code = codeInstance2;
}
JToken messageValue2 = detailsValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorDetailsInstance.Message = messageInstance2;
}
JToken targetValue2 = detailsValue["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorDetailsInstance.Target = targetInstance2;
}
}
}
JToken innerErrorValue = errorValue["innerError"];
if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
{
InnerError innerErrorInstance = new InnerError();
errorInstance.InnerError = innerErrorInstance;
JToken traceValue = innerErrorValue["trace"];
if (traceValue != null && traceValue.Type != JTokenType.Null)
{
string traceInstance = ((string)traceValue);
innerErrorInstance.Trace = traceInstance;
}
JToken contextValue = innerErrorValue["context"];
if (contextValue != null && contextValue.Type != JTokenType.Null)
{
string contextInstance = ((string)contextValue);
innerErrorInstance.Context = contextInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using GraphQL.Types;
using OrchardCore.ContentManagement.GraphQL.Settings;
using OrchardCore.ContentManagement.Metadata.Models;
namespace OrchardCore.ContentManagement.GraphQL.Options
{
public class GraphQLContentOptions
{
public IEnumerable<GraphQLContentTypeOption> ContentTypeOptions { get; set; }
= Enumerable.Empty<GraphQLContentTypeOption>();
public IEnumerable<GraphQLContentPartOption> PartOptions { get; set; }
= Enumerable.Empty<GraphQLContentPartOption>();
public IEnumerable<GraphQLField> HiddenFields { get; set; }
= Enumerable.Empty<GraphQLField>();
public GraphQLContentOptions ConfigureContentType(string contentType, Action<GraphQLContentTypeOption> action)
{
var option = new GraphQLContentTypeOption(contentType);
action(option);
ContentTypeOptions = ContentTypeOptions.Union(new[] { option });
return this;
}
public GraphQLContentOptions ConfigurePart<TContentPart>(Action<GraphQLContentPartOption> action)
where TContentPart : ContentPart
{
var option = new GraphQLContentPartOption<TContentPart>();
action(option);
PartOptions = PartOptions.Union(new[] { option });
return this;
}
public GraphQLContentOptions ConfigurePart(string partName, Action<GraphQLContentPartOption> action)
{
var option = new GraphQLContentPartOption(partName);
action(option);
PartOptions = PartOptions.Union(new[] { option });
return this;
}
public GraphQLContentOptions IgnoreField<TGraphType>(string fieldName) where TGraphType : IObjectGraphType
{
HiddenFields = HiddenFields.Union(new[] {
new GraphQLField<TGraphType>(fieldName),
});
return this;
}
public GraphQLContentOptions IgnoreField(Type fieldType, string fieldName)
{
HiddenFields = HiddenFields.Union(new[] {
new GraphQLField(fieldType, fieldName),
});
return this;
}
/// <summary>
/// Collapsing works at a hierarchy
///
/// If the Content Type is marked at collapsed, then all parts are collapsed.
/// If the Content Type is not marked collapsed, then it falls down to the content type under it.
/// If the Content Part at a top level is marked collapsed, then it will trump above.
/// </summary>
/// <param name="definition"></param>
/// <returns></returns>
internal bool ShouldCollapse(ContentTypePartDefinition definition)
{
if (IsCollapsedByDefault(definition))
{
return true;
}
var settings = definition.GetSettings<GraphQLContentTypePartSettings>();
if (settings.Collapse)
{
return true;
}
return false;
}
public bool IsCollapsedByDefault(ContentTypePartDefinition definition)
{
var contentType = definition.ContentTypeDefinition.Name;
var partName = definition.PartDefinition.Name;
if (contentType == partName)
{
return true;
}
var contentTypeOption = ContentTypeOptions.FirstOrDefault(ctp => ctp.ContentType == contentType);
if (contentTypeOption != null)
{
if (contentTypeOption.Collapse)
{
return true;
}
var contentTypePartOption = contentTypeOption.PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentTypePartOption != null)
{
if (contentTypePartOption.Collapse)
{
return true;
}
}
}
var contentPartOption = PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentPartOption != null)
{
if (contentPartOption.Collapse)
{
return true;
}
}
return false;
}
internal bool ShouldSkip(ContentTypePartDefinition definition)
{
if (IsHiddenByDefault(definition))
{
return true;
}
var settings = definition.GetSettings<GraphQLContentTypePartSettings>();
if (settings.Hidden)
{
return true;
}
return false;
}
internal bool ShouldSkip(Type fieldType, string fieldName)
{
return HiddenFields
.Any(x => x.FieldType == fieldType && x.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase));
}
public bool IsHiddenByDefault(ContentTypePartDefinition definition)
{
var contentType = definition.ContentTypeDefinition.Name;
var partName = definition.PartDefinition.Name;
var contentTypeOption = ContentTypeOptions.FirstOrDefault(ctp => ctp.ContentType == contentType);
if (contentTypeOption != null)
{
if (contentTypeOption.Hidden)
{
return true;
}
var contentTypePartOption = contentTypeOption.PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentTypePartOption != null)
{
if (contentTypePartOption.Hidden)
{
return true;
}
}
}
var contentPartOption = PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentPartOption != null)
{
if (contentPartOption.Hidden)
{
return true;
}
}
return false;
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
using MsgPack.Serialization.AbstractSerializers;
namespace MsgPack.Serialization.EmittingSerializers
{
/// <summary>
/// Implements common features for IL emitter based serializer builders.
/// </summary>
/// <typeparam name="TContext">The type of the code generation context.</typeparam>
/// <typeparam name="TObject">The type of the serialization target object.</typeparam>
internal abstract class ILEmittingSerializerBuilder<TContext, TObject> : SerializerBuilder<TContext, ILConstruct, TObject>
where TContext : ILEmittingContext
{
/// <summary>
/// Initializes a new instance of the <see cref="ILEmittingSerializerBuilder{TContext, TObject}"/> class.
/// </summary>
protected ILEmittingSerializerBuilder() { }
protected override void EmitMethodPrologue( TContext context, SerializerMethod method )
{
switch ( method )
{
case SerializerMethod.PackToCore:
{
context.IL = context.Emitter.GetPackToMethodILGenerator();
break;
}
case SerializerMethod.UnpackFromCore:
{
context.IL = context.Emitter.GetUnpackFromMethodILGenerator();
break;
}
case SerializerMethod.UnpackToCore:
{
context.IL = context.Emitter.GetUnpackToMethodILGenerator();
break;
}
default:
{
throw new ArgumentOutOfRangeException( "method", method.ToString() );
}
}
}
protected override void EmitMethodPrologue( TContext context, EnumSerializerMethod method )
{
switch ( method )
{
case EnumSerializerMethod.PackUnderlyingValueTo:
{
context.IL = context.EnumEmitter.GetPackUnderyingValueToMethodILGenerator();
break;
}
case EnumSerializerMethod.UnpackFromUnderlyingValue:
{
context.IL = context.EnumEmitter.GetUnpackFromUnderlyingValueMethodILGenerator();
break;
}
default:
{
throw new ArgumentOutOfRangeException( "method", method.ToString() );
}
}
}
protected override void EmitMethodEpilogue( TContext context, SerializerMethod method, ILConstruct construct )
{
EmitMethodEpilogue( context, construct );
}
protected override void EmitMethodEpilogue( TContext context, EnumSerializerMethod enumSerializerMethod, ILConstruct construct )
{
EmitMethodEpilogue( context, construct );
}
private static void EmitMethodEpilogue( TContext context, ILConstruct construct )
{
try
{
if ( construct != null )
{
construct.Evaluate( context.IL );
}
context.IL.EmitRet();
}
finally
{
context.IL.FlushTrace();
}
}
protected override ILConstruct EmitSequentialStatements( TContext context, Type contextType, IEnumerable<ILConstruct> statements )
{
return ILConstruct.Sequence( contextType, statements );
}
protected override ILConstruct MakeNullLiteral( TContext context, Type contextType )
{
return ILConstruct.Literal( contextType, default( object ), il => il.EmitLdnull() );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Many case switch" )]
protected override ILConstruct MakeInt32Literal( TContext context, int constant )
{
switch ( constant )
{
case 0:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_0() );
}
case 1:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_1() );
}
case 2:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_2() );
}
case 3:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_3() );
}
case 4:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_4() );
}
case 5:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_5() );
}
case 6:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_6() );
}
case 7:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_7() );
}
case 8:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_8() );
}
case -1:
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_M1() );
}
default:
{
if ( 0 <= constant && constant <= 255 )
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4_S( unchecked( ( byte )constant ) ) );
}
else
{
return ILConstruct.Literal( typeof( int ), constant, il => il.EmitLdc_I4( constant ) );
}
}
}
}
protected override ILConstruct MakeInt64Literal( TContext context, long constant )
{
return ILConstruct.Literal( typeof( long ), constant, il => il.EmitLdc_I8( constant ) );
}
protected override ILConstruct MakeStringLiteral( TContext context, string constant )
{
return ILConstruct.Literal( typeof( string ), constant, il => il.EmitLdstr( constant ) );
}
protected override ILConstruct MakeEnumLiteral( TContext context, Type type, object constant )
{
var underyingType = Enum.GetUnderlyingType( type );
switch ( Type.GetTypeCode( underyingType ) )
{
case TypeCode.Byte:
{
// tiny integrals are represented as int32 in IL operands.
return this.MakeInt32Literal( context, ( byte )constant );
}
case TypeCode.SByte:
{
// tiny integrals are represented as int32 in IL operands.
return this.MakeInt32Literal( context, ( sbyte )constant );
}
case TypeCode.Int16:
{
// tiny integrals are represented as int32 in IL operands.
return this.MakeInt32Literal( context, ( short )constant );
}
case TypeCode.UInt16:
{
// tiny integrals are represented as int32 in IL operands.
return this.MakeInt32Literal( context, ( ushort )constant );
}
case TypeCode.Int32:
{
return this.MakeInt32Literal( context, ( int )constant );
}
case TypeCode.UInt32:
{
// signeds and unsigneds are identical in IL operands.
return this.MakeInt32Literal( context, unchecked( ( int )( uint )constant ) );
}
case TypeCode.Int64:
{
return this.MakeInt64Literal( context, ( long )constant );
}
case TypeCode.UInt64:
{
// signeds and unsigneds are identical in IL operands.
return this.MakeInt64Literal( context, unchecked( ( long )( ulong )constant ) );
}
default:
{
// bool and char are not supported.
// Of course these are very rare, and bool is not supported in ExpressionTree (it hurts portability),
// and char is not supported by MsgPack protocol itself.
throw new NotSupportedException(
String.Format(
CultureInfo.CurrentCulture,
"Underying type '{0}' is not supported.",
underyingType
)
);
}
}
}
protected override ILConstruct EmitThisReferenceExpression( TContext context )
{
return ILConstruct.Literal( context.GetSerializerType( typeof( TObject ) ), "(this)", il => il.EmitLdarg_0() );
}
protected override ILConstruct EmitBoxExpression( TContext context, Type valueType, ILConstruct value )
{
return
ILConstruct.UnaryOperator(
"box",
value,
( il, val ) =>
{
val.LoadValue( il, false );
il.EmitBox( valueType );
}
);
}
protected override ILConstruct EmitUnboxAnyExpression( TContext context, Type targetType, ILConstruct value )
{
return
ILConstruct.UnaryOperator(
"unbox.any",
value,
( il, val ) =>
{
val.LoadValue( il, false );
il.EmitUnbox_Any( targetType );
}
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitNotExpression( TContext context, ILConstruct booleanExpression )
{
if ( booleanExpression.ContextType != typeof( bool ) )
{
throw new ArgumentException(
String.Format( CultureInfo.CurrentCulture, "Not expression must be Boolean elementType, but actual is '{0}'.", booleanExpression.ContextType ),
"booleanExpression"
);
}
return
ILConstruct.UnaryOperator(
"!",
booleanExpression,
( il, val ) =>
{
val.LoadValue( il, false );
il.EmitLdc_I4_0();
il.EmitCeq();
},
( il, val, @else ) =>
{
val.LoadValue( il, false );
il.EmitBrtrue( @else );
}
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitEqualsExpression( TContext context, ILConstruct left, ILConstruct right )
{
var equality = left.ContextType.GetMethod( "op_Equality" );
return
ILConstruct.BinaryOperator(
"==",
typeof( bool ),
left,
right,
( il, l, r ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( equality == null )
{
il.EmitCeq();
}
else
{
il.EmitAnyCall( equality );
}
},
( il, l, r, @else ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( equality == null )
{
il.EmitCeq();
}
else
{
il.EmitAnyCall( equality );
}
il.EmitBrfalse( @else );
}
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitGreaterThanExpression( TContext context, ILConstruct left, ILConstruct right )
{
#if DEBUG
Contract.Assert( left.ContextType.IsPrimitive && left.ContextType != typeof( string ) );
#endif
var greaterThan = left.ContextType.GetMethod( "op_GreaterThan" );
return
ILConstruct.BinaryOperator(
">",
typeof( bool ),
left,
right,
( il, l, r ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( greaterThan == null )
{
il.EmitCgt();
}
else
{
il.EmitAnyCall( greaterThan );
}
},
( il, l, r, @else ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( greaterThan == null )
{
il.EmitCgt();
}
else
{
il.EmitAnyCall( greaterThan );
}
il.EmitBrfalse( @else );
}
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitLessThanExpression( TContext context, ILConstruct left, ILConstruct right )
{
#if DEBUG
Contract.Assert( left.ContextType.IsPrimitive && left.ContextType != typeof( string ) );
#endif
var lessThan = left.ContextType.GetMethod( "op_LessThan" );
return
ILConstruct.BinaryOperator(
"<",
typeof( bool ),
left,
right,
( il, l, r ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( lessThan == null )
{
il.EmitClt();
}
else
{
il.EmitAnyCall( lessThan );
}
},
( il, l, r, @else ) =>
{
l.LoadValue( il, false );
r.LoadValue( il, false );
if ( lessThan == null )
{
il.EmitClt();
}
else
{
il.EmitAnyCall( lessThan );
}
il.EmitBrfalse( @else );
}
);
}
protected override ILConstruct EmitIncrement( TContext context, ILConstruct int32Value )
{
return
ILConstruct.UnaryOperator(
"++",
int32Value,
( il, variable ) =>
{
variable.LoadValue( il, false );
il.EmitLdc_I4_1();
il.EmitAdd();
variable.StoreValue( il );
}
);
}
protected override ILConstruct EmitTypeOfExpression( TContext context, Type type )
{
return
ILConstruct.Literal(
typeof( Type ),
type,
il => il.EmitTypeOf( type )
);
}
protected override ILConstruct EmitMethodOfExpression( TContext context, MethodBase method )
{
return
ILConstruct.Literal(
typeof( MethodInfo ),
method,
il =>
{
il.EmitLdtoken( method );
il.EmitCall( Metadata._MethodBase.GetMethodFromHandle );
}
);
}
protected override ILConstruct EmitFieldOfExpression( TContext context, FieldInfo field )
{
return
ILConstruct.Literal(
typeof( MethodInfo ),
field,
il =>
{
il.EmitLdtoken( field );
il.EmitCall( Metadata._FieldInfo.GetFieldFromHandle );
}
);
}
protected override ILConstruct DeclareLocal( TContext context, Type type, string name )
{
return
ILConstruct.Variable(
type,
name
);
}
protected override ILConstruct ReferArgument( TContext context, Type type, string name, int index )
{
return ILConstruct.Argument( index, type, name );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )]
protected override ILConstruct EmitInvokeVoidMethod( TContext context, ILConstruct instance, MethodInfo method, params ILConstruct[] arguments )
{
return
method.ReturnType == typeof( void )
? ILConstruct.Invoke( instance, method, arguments )
: ILConstruct.Sequence(
typeof( void ),
new[]
{
ILConstruct.Invoke( instance, method, arguments ),
ILConstruct.Instruction( "pop", typeof( void ), false, il => il.EmitPop() )
}
);
}
protected override ILConstruct EmitCreateNewObjectExpression( TContext context, ILConstruct variable, ConstructorInfo constructor, params ILConstruct[] arguments )
{
return ILConstruct.NewObject( variable, constructor, arguments );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Asserted internally" )]
protected override ILConstruct EmitCreateNewArrayExpression( TContext context, Type elementType, int length, IEnumerable<ILConstruct> initialElements )
{
var array =
ILConstruct.Variable(
elementType.MakeArrayType(),
"array"
);
return
ILConstruct.Composite(
ILConstruct.Sequence(
array.ContextType,
new[]
{
array,
ILConstruct.Instruction(
"CreateArray",
array.ContextType,
false,
il =>
{
il.EmitNewarr( elementType, length );
array.StoreValue( il );
var index = 0;
foreach ( var initialElement in initialElements )
{
array.LoadValue( il, false );
this.MakeInt32Literal( context, index ).LoadValue( il, false );
initialElement.LoadValue( il, false );
il.EmitStelem( elementType );
index++;
}
}
)
}
),
array
);
}
protected override ILConstruct EmitInvokeMethodExpression( TContext context, ILConstruct instance, MethodInfo method, IEnumerable<ILConstruct> arguments )
{
return ILConstruct.Invoke( instance, method, arguments );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )]
protected override ILConstruct EmitGetPropretyExpression( TContext context, ILConstruct instance, PropertyInfo property )
{
return ILConstruct.Invoke( instance, property.GetGetMethod( true ), ILConstruct.NoArguments );
}
protected override ILConstruct EmitGetFieldExpression( TContext context, ILConstruct instance, FieldInfo field )
{
return ILConstruct.LoadField( instance, field );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally" )]
protected override ILConstruct EmitSetProprety( TContext context, ILConstruct instance, PropertyInfo property, ILConstruct value )
{
#if DEBUG
// ReSharper disable PossibleNullReferenceException
Contract.Assert(
property.GetSetMethod( true ) != null,
property.DeclaringType.FullName + "::" + property.Name + ".set != null"
);
// ReSharper restore PossibleNullReferenceException
#endif
return ILConstruct.Invoke( instance, property.GetSetMethod( true ), new[] { value } );
}
protected override ILConstruct EmitSetField( TContext context, ILConstruct instance, FieldInfo field, ILConstruct value )
{
return ILConstruct.StoreField( instance, field, value );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitLoadVariableExpression( TContext context, ILConstruct variable )
{
return ILConstruct.Instruction( "load", variable.ContextType, false, il => variable.LoadValue( il, false ) );
}
protected override ILConstruct EmitStoreVariableStatement( TContext context, ILConstruct variable, ILConstruct value )
{
return ILConstruct.StoreLocal( variable, value );
}
protected override ILConstruct EmitThrowExpression( TContext context, Type expressionType, ILConstruct exceptionExpression )
{
return
ILConstruct.Instruction(
"throw",
expressionType,
true,
il =>
{
exceptionExpression.LoadValue( il, false );
il.EmitThrow();
}
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Asserted internally" )]
protected override ILConstruct EmitTryFinally( TContext context, ILConstruct tryStatement, ILConstruct finallyStatement )
{
return
ILConstruct.Instruction(
"try-finally",
tryStatement.ContextType,
false,
il =>
{
il.BeginExceptionBlock();
tryStatement.Evaluate( il );
il.BeginFinallyBlock();
finallyStatement.Evaluate( il );
il.EndExceptionBlock();
}
);
}
protected override ILConstruct EmitConditionalExpression( TContext context, ILConstruct conditionExpression, ILConstruct thenExpression, ILConstruct elseExpression )
{
return
ILConstruct.IfThenElse(
conditionExpression,
thenExpression,
elseExpression
);
}
protected override ILConstruct EmitAndConditionalExpression( TContext context, IList<ILConstruct> conditionExpressions, ILConstruct thenExpression, ILConstruct elseExpression )
{
return
ILConstruct.IfThenElse(
ILConstruct.AndCondition( conditionExpressions ),
thenExpression,
elseExpression
);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Asserted internally")]
protected override ILConstruct EmitStringSwitchStatement ( TContext context, ILConstruct target, IDictionary<string, ILConstruct> cases, ILConstruct defaultCase ) {
// Simple if statements
ILConstruct @else = defaultCase;
foreach (var @case in cases) {
@else =
this.EmitConditionalExpression(
context,
this.EmitInvokeMethodExpression(
context,
null,
Metadata._String.op_Equality,
target,
this.MakeStringLiteral(context, @case.Key)
),
@case.Value,
@else
);
}
return @else;
}
protected override ILConstruct EmitForLoop( TContext context, ILConstruct count, Func<ForLoopContext, ILConstruct> loopBodyEmitter )
{
var i =
this.DeclareLocal(
context,
typeof( int ),
"i"
);
var loopContext = new ForLoopContext( i );
return
this.EmitSequentialStatements(
context,
i.ContextType,
i,
ILConstruct.Instruction(
"for",
typeof( void ),
false,
il =>
{
var forCond = il.DefineLabel( "FOR_COND" );
il.EmitBr( forCond );
var body = il.DefineLabel( "BODY" );
il.MarkLabel( body );
loopBodyEmitter( loopContext ).Evaluate( il );
// increment
i.LoadValue( il, false );
il.EmitLdc_I4_1();
il.EmitAdd();
i.StoreValue( il );
// cond
il.MarkLabel( forCond );
i.LoadValue( il, false );
count.LoadValue( il, false );
il.EmitBlt( body );
}
)
);
}
protected override ILConstruct EmitForEachLoop( TContext context, CollectionTraits traits, ILConstruct collection, Func<ILConstruct, ILConstruct> loopBodyEmitter )
{
return
ILConstruct.Instruction(
"foreach",
typeof( void ),
false,
il =>
{
var enumerator = il.DeclareLocal( traits.GetEnumeratorMethod.ReturnType, "enumerator" );
var currentItem =
this.DeclareLocal(
context,
traits.ElementType,
"item"
);
// gets enumerator
collection.LoadValue( il, true );
il.EmitAnyCall( traits.GetEnumeratorMethod );
il.EmitAnyStloc( enumerator );
if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) )
{
il.BeginExceptionBlock();
}
var startLoop = il.DefineLabel( "START_LOOP" );
il.MarkLabel( startLoop );
currentItem.Evaluate( il );
var endLoop = il.DefineLabel( "END_LOOP" );
var enumeratorType = traits.GetEnumeratorMethod.ReturnType;
var moveNextMethod = Metadata._IEnumerator.FindEnumeratorMoveNextMethod( enumeratorType );
var currentProperty = Metadata._IEnumerator.FindEnumeratorCurrentProperty( enumeratorType, traits );
Contract.Assert( currentProperty != null, enumeratorType.ToString() );
// iterates
if ( traits.GetEnumeratorMethod.ReturnType.IsValueType )
{
il.EmitAnyLdloca( enumerator );
}
else
{
il.EmitAnyLdloc( enumerator );
}
il.EmitAnyCall( moveNextMethod );
il.EmitBrfalse( endLoop );
// get current item
if ( traits.GetEnumeratorMethod.ReturnType.IsValueType )
{
il.EmitAnyLdloca( enumerator );
}
else
{
il.EmitAnyLdloc( enumerator );
}
il.EmitGetProperty( currentProperty );
currentItem.StoreValue( il );
// body
loopBodyEmitter( currentItem ).Evaluate( il );
// end loop
il.EmitBr( startLoop );
il.MarkLabel( endLoop );
// Dispose
if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) )
{
il.BeginFinallyBlock();
if ( traits.GetEnumeratorMethod.ReturnType.IsValueType )
{
var disposeMethod = traits.GetEnumeratorMethod.ReturnType.GetMethod( "Dispose" );
if ( disposeMethod != null && disposeMethod.GetParameters().Length == 0 && disposeMethod.ReturnType == typeof( void ) )
{
il.EmitAnyLdloca( enumerator );
il.EmitAnyCall( disposeMethod );
}
else
{
il.EmitAnyLdloc( enumerator );
il.EmitBox( traits.GetEnumeratorMethod.ReturnType );
il.EmitAnyCall( Metadata._IDisposable.Dispose );
}
}
else
{
il.EmitAnyLdloc( enumerator );
il.EmitAnyCall( Metadata._IDisposable.Dispose );
}
il.EndExceptionBlock();
}
}
);
}
protected override ILConstruct EmitEnumFromUnderlyingCastExpression( TContext context, Type enumType, ILConstruct underlyingValue )
{
// No operations are needed in IL level.
return underlyingValue;
}
protected override ILConstruct EmitEnumToUnderlyingCastExpression( TContext context, Type underlyingType, ILConstruct enumValue )
{
// No operations are needed in IL level.
return enumValue;
}
protected override Func<SerializationContext, MessagePackSerializer<TObject>> CreateSerializerConstructor( TContext codeGenerationContext )
{
return context => codeGenerationContext.Emitter.CreateInstance<TObject>( context );
}
protected override Func<SerializationContext, MessagePackSerializer<TObject>> CreateEnumSerializerConstructor( TContext codeGenerationContext )
{
return context =>
codeGenerationContext.EnumEmitter.CreateInstance<TObject>(
context,
EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod( context, typeof( TObject ), EnumMemberSerializationMethod.Default )
);
}
}
}
| |
////////////////////////////////////////////////////
// WrapFactory.cs
// Author: Andrey Shchurov, shchurov@gmail.com, 2005
////////////////////////////////////////////////////
#region using
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Data;
using System.Data.Common;
using System.Collections;
#endregion
namespace Content.API.Data
{
/// <summary>
/// This class contains a static method <see cref="Create"/>
/// which generates class implementation from class
/// derived from <see cref="ISqlWrapperBase"/> imterface.
/// </summary>
public sealed class WrapFactory
{
/// <summary>
/// ModuleBuilder object.
/// </summary>
private static ModuleBuilder m_modBuilder = null;
/// <summary>
/// AssemblyBuilder object.
/// </summary>
private static AssemblyBuilder m_asmBuilder = null;
/// <summary>
/// A static constructor.
/// </summary>
static WrapFactory()
{
AssemblyName asmName = new AssemblyName();
asmName.Name = "SqlWrapperDynamicAsm";
m_asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
m_modBuilder = m_asmBuilder.DefineDynamicModule("SqlWrapperDynamicModule");
}
/// <summary>
/// A private constructor designed in order that no one could create
/// an instance of this class.
/// </summary>
private WrapFactory()
{
}
/// <summary>
/// Create the class implementation of a class
/// derived from <see cref="ISqlWrapperBase"/> imterface.
/// </summary>
/// <param name="typeToWrap">A class type</param>
/// <returns></returns>
public static SqlWrapperBase Create(Type typeToWrap)
{
// Verifying base interface
Type baseInterfaceType = typeof(ISqlWrapperBase);
Type baseitf = typeToWrap.GetInterface(baseInterfaceType.FullName);
// if(!typeToWrap.IsSubclassOf(typeof(SqlWrapperBase))){}
if (baseitf != baseInterfaceType)
{
string msg = string.Format ("interface {0} must inherit from base interface {1}", typeToWrap.FullName, baseInterfaceType.FullName);
throw new SqlWrapperException(msg);
}
Type typeCreated = null;
lock(typeof(WrapFactory))
{
// get a generated class name
string strTypeName = "_$Impl" + typeToWrap.FullName;
// try to find the class among already generated classes
typeCreated = m_modBuilder.GetType(strTypeName);
if(typeCreated == null)
{
TypeBuilder tb = null;
if(IsInterface(typeToWrap))
{
// if the original type is an interface then create a new type derived from SqlWrapperBase class
tb = m_modBuilder.DefineType(strTypeName, TypeAttributes.Class | TypeAttributes.Public, typeof(SqlWrapperBase));
}
else
{
// else create a new type derived from original type
tb = m_modBuilder.DefineType(strTypeName, TypeAttributes.Class | TypeAttributes.Public, typeToWrap);
}
// add created type implementation
AddTypeImplementation(tb, typeToWrap);
// get created type
typeCreated = tb.CreateType();
}
}
// creat an instance of the created type
SqlWrapperBase target = (SqlWrapperBase)Activator.CreateInstance(typeCreated);
return target;
}
/// <summary>
/// Adds an implementation to the created type.
/// </summary>
/// <param name="tb">Type builder object.</param>
/// <param name="typeToWrap">Created class.</param>
private static void AddTypeImplementation(TypeBuilder tb, Type typeToWrap)
{
// add implementation for the interface
if(IsInterface(typeToWrap))
{
tb.AddInterfaceImplementation(typeToWrap);
}
// create implementation for each type abstract method
MethodInfo[] parentMethodInfo = typeToWrap.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Instance /* | BindingFlags.DeclaredOnly */);
for(int i = 0; i < parentMethodInfo.Length; ++i)
{
if(IsAbstractMethod(parentMethodInfo[i]))
{
AddMethodImplementation(parentMethodInfo[i], tb);
}
}
}
/// <summary>
/// Adds attributes and an implementation to a method of the created class.
/// </summary>
/// <param name="method">MethodInfo object.</param>
/// <param name="tb">Type builder object.</param>
private static void AddMethodImplementation(MethodInfo method, TypeBuilder tb)
{
// get method return type
Type RetType = method.ReturnType;
// get method paramete information
ParameterInfo [] prms = method.GetParameters();
int paramCount = prms.Length;
// get method parameter types and names
Type [] paramTypes = new Type [paramCount];
string[] paramNames = new string[paramCount];
ParameterAttributes[] paramAttrs = new ParameterAttributes[paramCount];
for(int i = 0; i < paramCount; ++i)
{
paramTypes[i] = prms[i].ParameterType;
paramNames[i] = prms[i].Name;
paramAttrs[i] = prms[i].Attributes;
}
// define method body
MethodBuilder methodBody = tb.DefineMethod(method.Name, MethodAttributes.Public | MethodAttributes.Virtual, method.ReturnType, paramTypes);
// define method attribute if exists
SWCommandAttribute CommandMethodAttr = (SWCommandAttribute)Attribute.GetCustomAttribute(method, typeof(SWCommandAttribute));
if(CommandMethodAttr != null)
{
methodBody.SetCustomAttribute(SWCommandAttribute.GetCustomAttributeBuilder(CommandMethodAttr));
}
// define method parameters with their attributes
for(int i = 0; i < paramCount; ++i)
{
ParameterBuilder param = methodBody.DefineParameter(i+1, paramAttrs[i], paramNames[i]);
SWParameterAttribute[] ParameterAttr = (SWParameterAttribute[])prms[i].GetCustomAttributes(typeof(SWParameterAttribute), false);
if(ParameterAttr.Length > 0) param.SetCustomAttribute(SWParameterAttribute.GetCustomAttributeBuilder(ParameterAttr[0]));
}
// generate method body
GenerateMethodBody(methodBody.GetILGenerator(), RetType, prms);
}
/// <summary>
/// Generates an implementation to the method.
/// </summary>
/// <param name="ilGen">ILGenerator object.</param>
/// <param name="RetType">Method's return type</param>
/// <param name="prms">Method's parameters.</param>
private static void GenerateMethodBody(ILGenerator ilGen, Type RetType, ParameterInfo [] prms)
{
/*
* // declaring local variables
* MethodInfo V_0;
* Type V_1;
* object[] V_2;
* object V_3;
* RetType V_4;
* object[] V_5;
*/
LocalBuilder V_0 = ilGen.DeclareLocal(typeof (MethodInfo));
LocalBuilder V_1 = ilGen.DeclareLocal(typeof (Type));
LocalBuilder V_2 = ilGen.DeclareLocal(typeof (object[]));
LocalBuilder V_3 = ilGen.DeclareLocal(typeof (object));
LocalBuilder V_4 = ilGen.DeclareLocal(RetType);
LocalBuilder V_5 = ilGen.DeclareLocal(typeof (object[]));
/*
* V_0 = MethodBase.GetCurrentMethod();
*/
MethodInfo miLocalMethod = typeof(MethodBase).GetMethod ("GetCurrentMethod");
ilGen.Emit(OpCodes.Callvirt, miLocalMethod);
ilGen.Emit(OpCodes.Castclass, typeof(MethodInfo));
ilGen.Emit(OpCodes.Stloc_S, V_0);
/*
* V_5 = new object[prms.Length];
*/
ilGen.Emit(OpCodes.Ldc_I4, prms.Length);
ilGen.Emit(OpCodes.Newarr, typeof(object));
ilGen.Emit(OpCodes.Stloc_S, V_5);
for(int i = 0; i < prms.Length; ++i)
{
/*
* V_5[i] = {method argument in position i+1};
*/
ilGen.Emit(OpCodes.Ldloc_S, V_5);
ilGen.Emit(OpCodes.Ldc_I4, i);
ilGen.Emit(OpCodes.Ldarg_S, i+1);
// if method argument is a value type then box it
if(prms[i].ParameterType.IsValueType)
{
ilGen.Emit(OpCodes.Box, prms[i].ParameterType);
}
else if(prms[i].ParameterType.IsByRef)
{
// get type from reference type
Type reftype = SWExecutor.GetRefType(prms[i].ParameterType);
// and box by this type
if(reftype != null)
{
ilGen.Emit(OpCodes.Ldobj, reftype);
if(reftype.IsValueType)
{
ilGen.Emit(OpCodes.Box, reftype);
}
}
}
ilGen.Emit(OpCodes.Stelem_Ref);
}
/*
* V_5 = V_2;
*/
ilGen.Emit(OpCodes.Ldloc_S, V_5);
ilGen.Emit(OpCodes.Stloc_S, V_2);
/*
* V_3 = SWExecutor.ExecuteMethodAndGetResult(
* m_connection,
* m_transaction,
* V_0,
* V_2
* );
*/
// load this.m_connection
ilGen.Emit(OpCodes.Ldarg_0);// this
FieldInfo fldConnection = typeof(SqlWrapperBase).GetField("m_connection", BindingFlags.Instance|BindingFlags.NonPublic);
ilGen.Emit(OpCodes.Ldfld, fldConnection);
// load this.m_transaction
ilGen.Emit(OpCodes.Ldarg_0); // this
FieldInfo fldTransaction = typeof(SqlWrapperBase).GetField("m_transaction", BindingFlags.Instance|BindingFlags.NonPublic);
ilGen.Emit(OpCodes.Ldfld, fldTransaction);
// load V_0
ilGen.Emit(OpCodes.Ldloc_S, V_0);
// load V_2
ilGen.Emit(OpCodes.Ldloc_S, V_2);
// load this.m_autoCloseConnection
ilGen.Emit(OpCodes.Ldarg_0); // this
FieldInfo fldAutoCloseConnection = typeof(SqlWrapperBase).GetField("m_autoCloseConnection", BindingFlags.Instance|BindingFlags.NonPublic);
ilGen.Emit(OpCodes.Ldfld, fldAutoCloseConnection);
// call SWExecutor.ExecuteMethodAndGetResult methos
MethodInfo miExecuteMethodAndGetResult = typeof (SWExecutor).GetMethod ("ExecuteMethodAndGetResult", BindingFlags.Public | BindingFlags.Static);
ilGen.Emit(OpCodes.Call, miExecuteMethodAndGetResult);
// result -> V_3
ilGen.Emit (OpCodes.Stloc_S, V_3);
// returning parameters passed by reference
for(int i = 0; i < prms.Length; ++i)
{
if(prms[i].ParameterType.IsByRef)
{
Type reftype = SWExecutor.GetRefType(prms[i].ParameterType);
if(reftype != null)
{
/*
* {method argument in position i+1} = V_2[i]
*/
ilGen.Emit(OpCodes.Ldarg_S, i+1);
ilGen.Emit(OpCodes.Ldloc_S, V_2);
ilGen.Emit(OpCodes.Ldc_I4, i);
ilGen.Emit(OpCodes.Ldelem_Ref);
if(reftype.IsValueType)
{
ilGen.Emit(OpCodes.Unbox, reftype);
ilGen.Emit(OpCodes.Ldobj, reftype);
}
ilGen.Emit(OpCodes.Stobj, reftype);
}
}
}
if(RetType.FullName != "System.Void")
{
/*
* return (RetType)V_3;
*/
ilGen.Emit(OpCodes.Ldloc_S, V_3);
if(RetType.IsValueType)
{
ilGen.Emit(OpCodes.Unbox, RetType);
ilGen.Emit(OpCodes.Ldobj, RetType);
}
else
{
ilGen.Emit(OpCodes.Castclass, RetType);
}
ilGen.Emit (OpCodes.Stloc_S, V_4);
ilGen.Emit(OpCodes.Ldloc_S, V_4);
}
ilGen.Emit(OpCodes.Ret);
}
/// <summary>
/// Checks if a type is an interface.
/// </summary>
/// <param name="typeToWrap">Type object.</param>
/// <returns></returns>
private static bool IsInterface(Type typeToWrap)
{
return typeToWrap.IsInterface;
}
/// <summary>
/// Checks if a method is abstract.
/// </summary>
/// <param name="method">MethodInfo object.</param>
/// <returns></returns>
private static bool IsAbstractMethod(MethodInfo method)
{
return method.IsAbstract;
}
/// <summary>
/// Saves the created assembly to a file.
/// </summary>
/// <param name="fileName">A file name.</param>
public static void SaveAssemply(string fileName)
{
m_asmBuilder.Save(fileName);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BlobEntity.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Utilities.Serialization;
namespace DataAccessLayer
{
/// <summary>
/// An entity wrapper for blob reference entities.
/// </summary>
public class BlobEntity : EntityWrapperBase
{
/// <summary>Property Name for BlobPropertyType property.</summary>
public const string BlobPropertyTypeName = "BlobPropertyType";
/// <summary>Property Name for BlobBytes property.</summary>
public const string BlobDataPropertyName = "BlobData";
/// <summary>Category Name for Blob Entities.</summary>
public const string CategoryName = "DataReference";
/// <summary>Initializes a new instance of the <see cref="BlobEntity"/> class.</summary>
/// <param name="entity">The IEntity object from which to construct.</param>
public BlobEntity(IEntity entity)
{
this.Initialize(entity);
// If entity is not really an IRawEntity but an IEntity, and it's a legacy blob
// with BlobBytes populated, Initialize will strip the BlobBytes since they
// are not part of the entity properties. Make sure we carry them over here.
// TODO: back compat only until entities are migrated
var legacyBlob = entity as BlobEntity;
if (legacyBlob != null && legacyBlob.BlobBytes != null)
{
this.BlobBytes = legacyBlob.BlobBytes;
}
}
/// <summary>Initializes a new instance of the <see cref="BlobEntity"/> class.</summary>
/// <param name="externalEntityId">The external entity Id to assign the entity.</param>
public BlobEntity(EntityId externalEntityId)
: this(externalEntityId, null)
{
}
/// <summary>Initializes a new instance of the <see cref="BlobEntity"/> class.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <param name="serializedObjToBlob">The string obj to blob.</param>
public BlobEntity(EntityId externalEntityId, string serializedObjToBlob)
{
// Construct the underlying wrapped entity
var wrappedEntity = new Entity
{
ExternalEntityId = externalEntityId,
EntityCategory = CategoryName,
};
this.Initialize(wrappedEntity);
this.BlobPropertyType = string.Empty;
// Set the blob string on the entity if provided
if (serializedObjToBlob != null)
{
this.BlobData = serializedObjToBlob;
}
}
/// <summary>Initializes a new instance of the <see cref="BlobEntity"/> class.</summary>
public BlobEntity()
{
}
/// <summary>Gets or sets BlobData.</summary>
public EntityProperty BlobData
{
get { return this.TryGetEntityPropertyByName(BlobDataPropertyName, null); }
set { this.SetEntityProperty(new EntityProperty { Name = BlobDataPropertyName, Value = value.Value }); }
}
/// <summary>Gets or sets Blob property type.</summary>
public EntityProperty BlobPropertyType
{
get { return this.TryGetEntityPropertyByName(BlobPropertyTypeName, null); }
set { this.SetEntityProperty(new EntityProperty { Name = BlobPropertyTypeName, Value = value.Value }); }
}
/// <summary>Gets or sets blob bytes. Backward compatibility only, for migrating legacy blob entities.</summary>
internal byte[] BlobBytes { get; set; }
/// <summary>Build a BlobEntity given a DataContract serializable object.</summary>
/// <param name="externalEntityId">The external entity Id to assign the entity.</param>
/// <param name="objToBlob">The object that will be serialized.</param>
/// <typeparam name="T">Type of the object to be serialized.</typeparam>
/// <returns>A blob entity that has not yet been persisted.</returns>
public static BlobEntity BuildBlobEntity<T>(EntityId externalEntityId, T objToBlob) where T : class
{
return AddDataToBlob(objToBlob, blobString => new BlobEntity(externalEntityId, blobString));
}
/// <summary>Build a BlobEntity given a DataContract serializable object.</summary>
/// <param name="objToBlob">The object that will be serialized.</param>
/// <typeparam name="T">Type of the object to be serialized.</typeparam>
public void UpdateBlobEntity<T>(T objToBlob) where T : class
{
AddDataToBlob(objToBlob, blobString => { this.BlobData = blobString; return this; });
}
/// <summary>Deserialize the contained blob bytes.</summary>
/// <typeparam name="TResult">Target type of deserialize</typeparam>
/// <returns>The deserialized object (default construction if blob bytes are null)</returns>
/// <exception cref="DataAccessException">If BlobData is not set.</exception>
/// <exception cref="AppsJsonException">If BlobData cannot deserialize to requested type.</exception>
public TResult DeserializeBlob<TResult>() where TResult : class
{
// TODO: For backward compatibility. This should be removed when possible after migration
if (this.BlobBytes != null)
{
return this.DeserializeBlobFromXml<TResult>();
}
// If we don't have a blob string, fail
if (this.BlobData.Value == null)
{
throw new DataAccessException(
"Blob entity has no blob data: {0}.".FormatInvariant((EntityId)ExternalEntityId));
}
// First determine if the generic parameter is string. We want to avoid
// serialize/deserialize for strings.
var deserializedObj = this.BlobData.Value.SerializationValue as TResult;
if (deserializedObj != null)
{
return deserializedObj;
}
// Otherwise deserialize as json.
return AppsJsonSerializer.DeserializeObject<TResult>(this.BlobData.Value.SerializationValue);
}
/// <summary>
/// Backward compatibility only, for migrating legacy blob entities.Migration only:
/// Deserialize the contained blob bytes previously saved as xml serialized data.
/// </summary>
/// <typeparam name="TResult">Target type of deserialize</typeparam>
/// <returns>The deserialized object (default construction if blob bytes are null)</returns>
/// <exception cref="DataAccessException">If BlobBytes are not set.</exception>
internal TResult DeserializeBlobFromXml<TResult>()
{
if (this.BlobBytes == null)
{
throw new DataAccessException(
"Blob entity has no blob data.".FormatInvariant((EntityId)ExternalEntityId));
}
// Deserialize the bytes.
using (var stream = new MemoryStream(this.BlobBytes))
{
var serializer = new DataContractSerializer(typeof(TResult));
stream.Seek(0, SeekOrigin.Begin);
return (TResult)serializer.ReadObject(stream);
}
}
/// <summary>Abstract method to validate type of entity.</summary>
/// <param name="entity">The entity.</param>
protected override void ValidateEntityType(IEntity entity)
{
ThrowIfCategoryMismatch(entity, CategoryName);
}
/// <summary>Add data to a given a DataContract serializable object and builder method.</summary>
/// <param name="objToBlob">The object that will be serialized.</param>
/// <param name="buildBlob">Builder method returning a blob.</param>
/// <typeparam name="T">Type of the object to be serialized.</typeparam>
/// <returns>A blob entity with the serialized data.</returns>
private static BlobEntity AddDataToBlob<T>(T objToBlob, Func<string, BlobEntity> buildBlob) where T : class
{
// If data is already a string, don't bother to serialize it
var candidateData = objToBlob as string;
if (candidateData != null)
{
// Construct a entity object
return buildBlob(candidateData);
}
// Otherwise serialize to json string
try
{
if (objToBlob == null)
{
throw new ArgumentException("Cannot serialize null object to blob.");
}
var blobString = JsonConvert.SerializeObject(objToBlob);
return buildBlob(blobString);
}
catch (Exception e)
{
var msg = "Could not serialize entity as requested type: {0}".FormatInvariant(typeof(T).FullName);
throw new DataAccessException(msg, e);
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using Common.Logging;
using Common.Logging.Simple;
using NUnit.Framework;
using Spring.Collections;
using Spring.Core;
using Spring.Core.TypeConversion;
using Spring.Objects.Factory;
using Spring.Util;
#endregion
namespace Spring.Objects
{
/// <summary>
/// Unit tests for the ObjectWrapper class.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Mark Pollack (.NET)</author>
/// <author>Rick Evans (.NET)</author>
[TestFixture]
public sealed class ObjectWrapperTests
{
/// <summary>
/// The setup logic executed before the execution of this test fixture.
/// </summary>
[TestFixtureSetUp]
public void FixtureSetUp()
{
// enable logging (to nowhere), just to exercisee the logging code...
LogManager.Adapter = new NoOpLoggerFactoryAdapter();
}
#region Classes Used During Tests
public class Person
{
private IList favoriteNames = new ArrayList();
private IDictionary properties = new Hashtable();
private string sillyString;
public Person()
{
favoriteNames.Add("p1");
favoriteNames.Add("p2");
}
public Person(IList favNums)
{
favoriteNames = favNums;
}
public string SillyString
{
get { return sillyString; }
}
public IList FavoriteNames
{
get { return favoriteNames; }
}
public IDictionary Properties
{
get { return properties; }
}
public string this[int index]
{
get { return (string)favoriteNames[index]; }
set { favoriteNames[index] = value; }
}
public string this[string keyName]
{
get { return (string) properties[keyName]; }
set { properties.Add(keyName,value); }
}
public string this[int index, string keyname]
{
get { return sillyString; }
set { sillyString = index + "-" + keyname + ",val=" + value;}
}
}
public class GenericPerson
{
private List<string> favoriteNames = new List<string>();
private IDictionary<string, string> properties = new Dictionary<string, string>();
public GenericPerson()
{
favoriteNames.Add("p1");
favoriteNames.Add("p2");
}
public GenericPerson(List<string> favNums)
{
favoriteNames = favNums;
}
/*
public string this[int index]
{
get { return (string)favoriteNames[index]; }
set { favoriteNames[index] = value; }
}
*/
public string this[string keyName]
{
get { return properties[keyName]; }
set { properties.Add(keyName, value); }
}
}
public class AltPerson
{
private IList favoriteNames = new ArrayList();
public AltPerson()
{
favoriteNames.Add("ap1");
favoriteNames.Add("ap2");
}
public AltPerson(IList favNums)
{
favoriteNames = favNums;
}
[IndexerName("FavoriteName")]
public string this[int index]
{
get { return (string)favoriteNames[index]; }
set { favoriteNames[index] = value; }
}
}
public class NoNullsList : ArrayList
{
public override int Add(object value)
{
if (value == null)
{
throw new NullReferenceException("Adding nulls is not supported in this implementation.");
}
return base.Add(value);
}
}
private class Honey
{
public Honey(IList akas)
{
_akas = new Aliases(akas);
}
protected Aliases _akas;
public Aliases AlsoKnownAs
{
get { return _akas; }
}
public string this[int index]
{
get { return AlsoKnownAs[index]; }
}
}
private class NonReadableHoney : Honey
{
public NonReadableHoney(IList akas) : base(akas)
{
}
new public Aliases AlsoKnownAs
{
set { _akas = value; }
}
}
private class Milk
{
public Milk(Honey[] honeys)
{
}
public Honey[] Honeys
{
set
{
}
}
}
private sealed class Aliases
{
private IList _names;
public Aliases() : this(new ArrayList())
{
}
public Aliases(IList names)
{
_names = names;
}
public string this[int index]
{
get { return (string) _names[index]; }
set { _names[index] = value; }
}
}
private sealed class RealNestedTestObject
{
public TestObject Datum
{
get { return _datum; }
set { _datum = value; }
}
private TestObject _datum;
}
private sealed class WanPropsClass
{
public bool IsWan
{
get { return true; }
}
}
private sealed class StringAppenderConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof (string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(
ITypeDescriptorContext context, CultureInfo culture, object val)
{
if (val is string)
{
return "OctopusOil : " + val;
}
return base.ConvertFrom(context, culture, val);
}
}
private sealed class TestStringArrayConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof (string[]))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object val)
{
if (val is string[])
{
return "-" + StringUtils.CollectionToCommaDelimitedString(val as string[]) + "-";
}
return base.ConvertFrom(context, culture, val);
}
}
private sealed class TestObjectArrayConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof (string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object val)
{
if (val is string)
{
return new TestObject((string) val, 99);
}
return base.ConvertFrom(context, culture, val);
}
}
private sealed class ObjectWithTypeProperty
{
private Type _type;
public Type Type
{
get { return _type; }
set { _type = value; }
}
}
/// <summary>
/// A class for use in testing the object wrapper with read only properties.
/// </summary>
private sealed class NoRead
{
public int Age
{
set
{
}
}
}
private sealed class GetterObject
{
public string Name
{
get
{
if (_name == null)
{
throw new ApplicationException("name property must be set");
}
return _name;
}
set { _name = value; }
}
private string _name;
}
private sealed class ThrowsException
{
public void DoSomething(Exception t)
{
throw t;
}
}
internal sealed class PrimitiveArrayObject
{
public int[] Array
{
get { return array; }
set { this.array = value; }
}
private int[] array;
}
private sealed class PropsTest
{
public NameValueCollection Properties
{
set
{
}
}
public String Name
{
set
{
}
}
public String[] StringArray
{
set { this.stringArray = value; }
}
public int[] IntArray
{
set { this.intArray = value; }
}
public String[] stringArray;
public int[] intArray;
}
#endregion
#region Methods
/// <summary>
/// Factory method for getting an ObjectWrapper instance.
/// </summary>
/// <returns>A new object wrapper (with no WrappedObject).</returns>
private ObjectWrapper GetWrapper()
{
return new ObjectWrapper();
}
/// <summary>
/// Factory method for getting an ObjectWrapper instance.
/// </summary>
/// <param name="objectToBeWrapped">
/// The object that is to be wrapped by the returned object wrapper.
/// </param>
/// <returns>
/// A new object wrapper that wraps the supplied <paramref name="objectToBeWrapped"/>.
/// </returns>
private ObjectWrapper GetWrapper(object objectToBeWrapped)
{
return new ObjectWrapper(objectToBeWrapped);
}
#endregion
[Test]
[ExpectedException(typeof (TypeMismatchException))]
public void SetPropertyUsingValueThatNeedsConversionWithNoCustomConverterRegistered()
{
ObjectWrapper wrapper = GetWrapper(new TestObject("Rick", 30));
// needs conversion to NestedTestObject...
wrapper.SetPropertyValue("doctor", "Pollack, Pinch, & Pounce");
}
[Test]
[Ignore()]
public void GetValueOfCustomIndexerProperty()
{
ObjectWrapper wrapper = GetWrapper();
Honey darwin = new Honey(new string[] {"dickens", "of gaunt"});
wrapper.WrappedInstance = darwin;
string alias = (string) wrapper.GetPropertyValue("AlsoKnownAs[1]");
Assert.AreEqual("of gaunt", alias);
alias = (string) wrapper.GetPropertyValue("[1]");
Assert.AreEqual("of gaunt", alias, "indexer on object not working.");
wrapper.SetPropertyValue("Item[1]", "of foobar");
alias = (string)wrapper.GetPropertyValue("[1]");
Assert.AreEqual("of foobar", alias, "indexer on object not working.");
}
[Test]
[Ignore()]
public void GetSetIndexerProperties()
{
IList favNames = new ArrayList();
favNames.Add("Master Shake");
favNames.Add("Meatwad");
favNames.Add("Frylock");
Person p = new Person(favNames);
ObjectWrapper wrapper = GetWrapper();
wrapper.WrappedInstance = p;
//This is 'new' Spring.Expressions notation, i.e. not "Item[i]" but plain [i].
string name = (string)wrapper.GetPropertyValue("[0]");
Assert.AreEqual("Master Shake", name);
wrapper.SetPropertyValue("[0]", "Carl");
name = (string)wrapper.GetPropertyValue("[0]");
Assert.AreEqual("Carl", name);
//Try with Custom Indexer Name.
favNames = new ArrayList();
favNames.Add("Master Shake");
favNames.Add("Meatwad");
favNames.Add("Frylock");
AltPerson ap = new AltPerson(favNames);
wrapper = GetWrapper();
wrapper.WrappedInstance = ap;
name = (string)wrapper.GetPropertyValue("FavoriteName[0]");
Assert.AreEqual("Master Shake", name);
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetValueOfCustomIndexerPropertyWithMalformedIndexer()
{
ObjectWrapper wrapper = GetWrapper();
Honey darwin = new Honey(new string[] {"dickens", "of gaunt"});
wrapper.WrappedInstance = darwin;
wrapper.GetPropertyValue("AlsoKnownAs[1");
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void GetPropertyTypeWithNullPropertyPath()
{
GetWrapper().GetPropertyType(null);
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void GetPropertyTypeWithEmptyPropertyPath()
{
GetWrapper().GetPropertyType(string.Empty);
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void GetPropertyTypeWithWhitespacedPropertyPath()
{
GetWrapper().GetPropertyType(" ");
}
[Test]
public void GetPropertyType()
{
ObjectWrapper wrapper = GetWrapper(new TestObject());
Type propertyType = wrapper.GetPropertyType("name");
Assert.AreEqual(typeof (string), propertyType);
}
[Test]
public void GetPropertyTypeFromField_SPRNET502()
{
ObjectWrapper wrapper = GetWrapper(new TestObject());
Type propertyType = wrapper.GetPropertyType("FileModeEnum");
Assert.AreEqual(typeof (FileMode), propertyType);
}
[Test]
public void GetPropertyTypeWithNestedLookup()
{
TestObject target = new TestObject();
target.Spouse = new TestObject("Fiona", 28);
ObjectWrapper wrapper = GetWrapper(target);
Type propertyType = wrapper.GetPropertyType("spouse.age");
Assert.AreEqual(typeof (int), propertyType);
}
[Test]
[ExpectedException(typeof (NotWritablePropertyException))]
public void SetValueOfCustomIndexerPropertyWithNonReadablePropertyInIndexedPath()
{
ObjectWrapper wrapper = GetWrapper();
Honey[] honeys = new NonReadableHoney[] {new NonReadableHoney(new string[] {"hsu", "feng"})};
wrapper.WrappedInstance = new Milk(honeys);
wrapper.SetPropertyValue("Honeys[0][0]", "mei");
}
[Test]
[ExpectedException(typeof (TypeMismatchException))]
public void SetPropertyThatRequiresTypeConversionWithNonConvertibleType()
{
ObjectWrapper wrapper = GetWrapper();
TestObject to = new TestObject();
wrapper.WrappedInstance = to;
wrapper.SetPropertyValue("RealLawyer", "Noob");
Console.Out.WriteLine(to.RealLawyer);
}
/// <summary>
/// This test blows up because index is out of range.
/// </summary>
[Test]
[ExpectedException(typeof(InvalidPropertyException))]
public void SetIndexedPropertyOnListThatsOutOfRange()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
to.Friends = new NoNullsList();
wrapper.SetPropertyValue("Friends[5]", "Inheritance Tax");
}
/// <summary>
/// Tests that a property lookup such as <c>foo[0][1]['ben'][12]</c> is ok
/// Well, rather it tests that its valid... 'cos man, that shoh ain't ok :D
/// </summary>
[Test]
public void GetChainedIndexers()
{
Honey to = new Honey(new string[] {"wee", "jakey", "ned"});
ObjectWrapper wrapper = GetWrapper(to);
Assert.AreEqual('j', wrapper.GetPropertyValue("AlsoKnownAs[1][0]"));
}
/// <summary>
/// Test that passing a null value of the object to manipulate with the ObjectWrapper
/// will throw a FatalPropertyException with the correct exception message.
/// </summary>
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void NullObject()
{
new ObjectWrapper((object) null);
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void InstantiateWithInterfaceType()
{
new ObjectWrapper(typeof (IList));
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void InstantiateWithAbstractType()
{
new ObjectWrapper(typeof (AbstractObjectFactoryTests));
}
[Test]
public void InstantiateWithOkType()
{
IObjectWrapper wrapper = GetWrapper(typeof (TestObject));
Assert.IsNotNull(wrapper.WrappedInstance);
}
[Test]
public void NestedProperties()
{
string doctorCompany = "";
string lawyerCompany = "Dr. Sueem";
TestObject to = new TestObject();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Doctor.Company", doctorCompany);
wrapper.SetPropertyValue("Lawyer.Company", lawyerCompany);
Assert.AreEqual(doctorCompany, to.Doctor.Company);
Assert.AreEqual(lawyerCompany, to.Lawyer.Company);
}
[Test]
public void GetterThrowsException()
{
GetterObject go = new GetterObject();
IObjectWrapper wrapper = GetWrapper(go);
wrapper.SetPropertyValue("Name", "tom");
Assert.IsTrue(go.Name.Equals("tom"), "Expected name to be set to 'tom'");
}
[Test]
[ExpectedException(typeof (NotReadablePropertyException))]
public void TryToReadTheValueOfAWriteOnlyProperty()
{
NoRead nr = new NoRead();
ObjectWrapper wrapper = GetWrapper(nr);
wrapper.GetPropertyValue("Age");
}
[Test]
[ExpectedException(typeof(NullValueInNestedPathException))]
public void TryToReadAnIndexedValueFromANullProperty()
{
TestObject o = new TestObject();
o.Friends = null;
ObjectWrapper wrapper = GetWrapper(o);
wrapper.GetPropertyValue("Friends[2]");
}
/// <summary>
/// Test that applying an empty MutablePropertyValues does not modify the object contents.
/// </summary>
[Test]
public void EmptyPropertyValuesSet()
{
TestObject t = new TestObject();
int age = 50;
string name = "Tony";
t.Age = age;
t.Name = name;
IObjectWrapper wrapper = GetWrapper(t);
Assert.IsTrue(t.Age.Equals(age), "Age is not set correctly");
Assert.IsTrue(name.Equals(t.Name), "Name is not set correctly");
wrapper.SetPropertyValues(new MutablePropertyValues());
Assert.IsTrue(t.Age.Equals(age), "Age is not set correctly");
Assert.IsTrue(name.Equals(t.Name), "Name is not set correctly");
}
/// <summary>
/// Test basic ObjectWrapper functionality by setting properties using MutablePropertyValues.
/// </summary>
[Test]
public void AllValid()
{
TestObject t = new TestObject();
string newName = "tony";
int newAge = 65;
string newTouchy = "valid";
IObjectWrapper wrapper = GetWrapper(t);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.Add(new PropertyValue("Age", newAge));
pvs.Add(new PropertyValue("Name", newName));
pvs.Add(new PropertyValue("Touchy", newTouchy));
wrapper.SetPropertyValues(pvs);
Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick");
Assert.IsTrue(t.Touchy.Equals(newTouchy), "Validly set property must stick");
Assert.IsTrue(t.Age == newAge, "Validly set property must stick");
}
[Test]
public void IndividualAllValid()
{
TestObject t = new TestObject();
String newName = "tony";
int newAge = 65;
string newTouchy = "valid";
IObjectWrapper wrapper = GetWrapper(t);
wrapper.SetPropertyValue("Age", newAge);
wrapper.SetPropertyValue(new PropertyValue("Name", newName));
wrapper.SetPropertyValue(new PropertyValue("Touchy", newTouchy));
Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick");
Assert.IsTrue(t.Touchy.Equals(newTouchy), "Validly set property must stick");
Assert.IsTrue(t.Age == newAge, "Validly set property must stick");
}
[Test]
public void SettingAnInvalidValue()
{
TestObject t = new TestObject();
string newName = "tony";
try
{
IObjectWrapper wrapper = GetWrapper(t);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.Add(new PropertyValue("Age", "foobar"));
pvs.Add(new PropertyValue("Name", newName));
wrapper.SetPropertyValues(pvs);
Assert.Fail("Should throw exception when setting an invalid value");
}
catch (PropertyAccessExceptionsException ex)
{
Assert.IsTrue(ex.ExceptionCount == 1, "Must contain 2 exceptions");
// Test validly set property matches
Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick");
Assert.IsTrue(t.Age == 0, "Invalidly set property must retain old value");
}
catch (Exception ex)
{
Assert.Fail(
"Shouldn't throw exception other than PropertyAccessExceptions. Exception Message = " + ex.Message);
}
}
[Test]
public void ArrayToStringConversion()
{
TestObject t = new TestObject();
IObjectWrapper wrapper = GetWrapper(t);
TypeConverterRegistry.RegisterConverter(typeof(string), new TestStringArrayConverter());
wrapper.SetPropertyValue("Name", new string[] {"a", "b"});
Assert.AreEqual("-a,b-", t.Name);
}
[Test]
public void ArrayToArrayConversion()
{
IndexedTestObject to = new IndexedTestObject();
IObjectWrapper wrapper = GetWrapper(to);
TypeConverterRegistry.RegisterConverter(typeof(TestObject), new TestObjectArrayConverter());
wrapper.SetPropertyValue("Array", new string[] {"a", "b"});
Assert.AreEqual("a", to.Array[0].Name);
Assert.AreEqual("b", to.Array[1].Name);
}
[Test]
public void PrimitiveArray()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Array", new String[] {"1", "2"});
Assert.AreEqual(2, to.Array.Length);
Assert.AreEqual(1, to.Array[0]);
Assert.AreEqual(2, to.Array[1]);
}
[Test]
public void PrimitiveArrayFromCommaDelimitedString()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Array", "1,2");
Assert.AreEqual(2, to.Array.Length);
Assert.AreEqual(1, to.Array[0]);
Assert.AreEqual(2, to.Array[1]);
}
[Test]
public void ObjectWrapperUpdates()
{
TestObject to = new TestObject("Rick", 2);
int newAge = 33;
ObjectWrapper wrapper = GetWrapper(to);
to.Age = newAge;
object owAge = wrapper.GetPropertyValue("Age");
Assert.IsTrue(owAge is Int32, "Age is an integer");
int owi = (int) owAge;
Assert.IsTrue(owi == newAge, "Object wrapper must pick up changes");
}
[Test]
public void SetWrappedInstanceOfSameClass()
{
TestObject to = new TestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Age = 11;
TestObject to2 = new TestObject();
wrapper.WrappedInstance = to2;
wrapper.SetPropertyValue("Age", 14);
Assert.IsTrue(to2.Age == 14, "2nd changed");
Assert.IsTrue(to.Age == 11, "1st didn't change");
}
[Test]
public void SetWrappedInstanceOfDifferentClass()
{
ThrowsException tex = new ThrowsException();
ObjectWrapper wrapper = GetWrapper(tex);
TestObject to2 = new TestObject();
wrapper.WrappedInstance = to2;
wrapper.SetPropertyValue("Age", 14);
Assert.IsTrue(to2.Age == 14);
}
[Test]
[ExpectedException(typeof (TypeMismatchException))]
public void TypeMismatch()
{
TestObject to = new TestObject();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Age", "foobar");
}
[Test]
[ExpectedException(typeof (TypeMismatchException))]
public void EmptyValueForPrimitiveProperty()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Age", "");
}
[Test]
public void GetProtectedPropertyValue()
{
TestObject foo = new TestObject();
IObjectWrapper wrapper = GetWrapper(foo);
string happyPlace = (string) wrapper.GetPropertyValue("HappyPlace");
Assert.AreEqual(TestObject.DefaultHappyPlace, happyPlace,
"Failed to read the value of a property with 'protected' access.");
}
[Test]
public void SetProtectedPropertyValue()
{
TestObject foo = new TestObject();
IObjectWrapper wrapper = GetWrapper(foo);
const string expectedHappyPlace = "The Rockies! Brrr...";
wrapper.SetPropertyValue(new PropertyValue("HappyPlace", expectedHappyPlace));
string happyPlace = (string) wrapper.GetPropertyValue("HappyPlace");
Assert.AreEqual(expectedHappyPlace, happyPlace,
"Failed to read / write the value of a property with 'protected' access.");
}
[Test]
public void GetPrivatePropertyValue()
{
TestObject foo = new TestObject();
IObjectWrapper wrapper = GetWrapper(foo);
string[] contents = (string[]) wrapper.GetPropertyValue("SamsoniteSuitcase");
Assert.IsTrue(ArrayUtils.AreEqual(TestObject.DefaultContentsOfTheSuitcase, contents),
"Failed to read the value of a property with 'private' access.");
}
[Test]
public void SetPrivatePropertyValue()
{
TestObject foo = new TestObject();
IObjectWrapper wrapper = GetWrapper(foo);
string[] expectedContents = new string[] {"Lloyd's Soul", "Harry's John Denver Records"};
wrapper.SetPropertyValue(new PropertyValue("SamsoniteSuitcase", expectedContents));
string[] contents = (string[]) wrapper.GetPropertyValue("SamsoniteSuitcase");
Assert.IsTrue(ArrayUtils.AreEqual(expectedContents, contents),
"Failed to read / write the value of a property with 'private' access.");
}
[Test]
public void GetNestedProperty()
{
ITestObject rod = new TestObject("rod", 31);
ITestObject kerry = new TestObject("kerry", 35);
rod.Spouse = kerry;
kerry.Spouse = rod;
IObjectWrapper wrapper = GetWrapper(rod);
int KA = (int) wrapper.GetPropertyValue("Spouse.Age");
Assert.IsTrue(KA == 35, "Expected kerry's age to be 35");
int RA = (int) wrapper.GetPropertyValue("Spouse.Spouse.Age");
Assert.IsTrue(RA == 31, "Expected rod's age to be 31");
ITestObject spousesSpouse = (ITestObject) wrapper.GetPropertyValue("Spouse.Spouse");
Assert.IsTrue(rod == spousesSpouse, "spousesSpouse == initial point");
}
[Test]
[ExpectedException(typeof (NullValueInNestedPathException))]
public void GetNestedPropertyValueNullValue()
{
TestObject rod = new TestObject("rod", 31);
rod.Doctor = new NestedTestObject(null);
GetWrapper(rod).GetPropertyValue("Doctor.Company.Length");
}
[Test]
public void SetNestedProperty()
{
ITestObject rod = new TestObject("rod", 31);
ITestObject kerry = new TestObject("kerry", 0);
IObjectWrapper wrapper = GetWrapper(rod);
wrapper.SetPropertyValue("Spouse", kerry);
Assert.AreEqual(rod.Spouse, kerry, "nested set did not work");
wrapper.SetPropertyValue("Spouse.Spouse", rod);
Assert.AreEqual(rod, rod.Spouse.Spouse, "Nested set did not work.");
wrapper.SetPropertyValue("Spouse.Age", 100);
Assert.AreEqual(100, kerry.Age, "Nested setting of primitive property did not work.");
}
[Test]
public void SetPropertyValue()
{
ITestObject bigby = new TestObject("Bigby", 4500);
ITestObject snow = new TestObject("Snow", 2500);
IObjectWrapper wrapper = GetWrapper(bigby);
wrapper.SetPropertyValue("Spouse", snow);
Assert.AreEqual(snow, bigby.Spouse);
}
[Test]
[ExpectedException(typeof (NullValueInNestedPathException))]
public void SetIndexedPropertyValueOnUninitializedPath()
{
TestObject obj = new TestObject("Bill", 4500);
IObjectWrapper wrapper = GetWrapper(obj);
wrapper.SetPropertyValue("hats [0]", "Hicks & Co");
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void SetIndexedPropertyValueOnNonIndexableType()
{
TestObject obj = new TestObject("Bill", 4500);
IObjectWrapper wrapper = GetWrapper(obj);
wrapper.SetPropertyValue("doctor [0]", "Hicks & Co");
}
[Test]
[ExpectedException(typeof (TypeMismatchException))]
public void SetPrimitivePropertyToNullReference()
{
TestObject obj = new TestObject("Bill", 4500);
IObjectWrapper wrapper = GetWrapper(obj);
wrapper.SetPropertyValue("Age", null);
}
[Test]
public void SetPropertyValueIgnoresCase()
{
ITestObject bigby = new TestObject("Bigby", 4500);
ITestObject snow = new TestObject("Snow", 2500);
IObjectWrapper wrapper = GetWrapper(bigby);
wrapper.SetPropertyValue("spouse", snow);
Assert.AreEqual(snow, bigby.Spouse,
"Property setting is not case insensitive with regard to the property name (and for CLS compliance it should be).");
}
[Test]
public void IntArrayProperty()
{
PropsTest pt = new PropsTest();
IObjectWrapper wrapper = GetWrapper(pt);
wrapper.SetPropertyValue("IntArray", new int[] {4, 5, 2, 3});
Assert.IsTrue(pt.intArray.Length == 4, "intArray length = 4");
Assert.IsTrue(pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3,
"correct values");
wrapper.SetPropertyValue("IntArray", new String[] {"4", "5", "2", "3"});
Assert.IsTrue(pt.intArray.Length == 4, "intArray length = 4");
Assert.IsTrue(pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3,
"correct values");
wrapper.SetPropertyValue("IntArray", 1);
Assert.IsTrue(pt.intArray.Length == 1, "intArray length = 1");
Assert.IsTrue(pt.intArray[0] == 1, "correct values");
wrapper.SetPropertyValue("IntArray", new String[] {"1"});
Assert.IsTrue(pt.intArray.Length == 1, "intArray length = 1");
Assert.IsTrue(pt.intArray[0] == 1, "correct values");
}
[Test]
public void NewWrappedInstancePropertyValuesGet()
{
ObjectWrapper wrapper = GetWrapper();
TestObject t = new TestObject("Tony", 50);
wrapper.WrappedInstance = t;
Assert.AreEqual(t.Age, wrapper.GetPropertyValue("Age"), "Object wrapper returns wrong property value");
TestObject u = new TestObject("Udo", 30);
wrapper.WrappedInstance = u;
Assert.AreEqual(u.Age, wrapper.GetPropertyValue("Age"), "Object wrapper returns cached property value");
}
[Test]
public void NewWrappedInstanceNestedPropertyValuesGet()
{
IObjectWrapper wrapper = GetWrapper();
TestObject t = new TestObject("Tony", 50);
t.Spouse = new TestObject("Sue", 40);
wrapper.WrappedInstance = t;
Assert.AreEqual(t.Spouse.Age, wrapper.GetPropertyValue("Spouse.Age"),
"Object wrapper returns wrong nested property value");
TestObject u = new TestObject("Udo", 30);
u.Spouse = new TestObject("Vera", 20);
wrapper.WrappedInstance = u;
Assert.AreEqual(u.Spouse.Age, wrapper.GetPropertyValue("Spouse.Age"),
"Object wrapper returns cached nested property value");
}
[Test]
public void StringArrayProperty()
{
PropsTest pt = new PropsTest();
ObjectWrapper wrapper = GetWrapper(pt);
wrapper.SetPropertyValue("StringArray", "foo,fi,fi,fum");
Assert.IsTrue(pt.stringArray.Length == 4, "StringArray length = 4");
Assert.IsTrue(
pt.stringArray[0].Equals("foo") && pt.stringArray[1].Equals("fi") && pt.stringArray[2].Equals("fi") &&
pt.stringArray[3].Equals("fum"), "in correct values of string array");
}
#region Test for DateTime Properties
internal class DateTimeTestObject
{
private DateTime _dt;
public DateTime TriggerDateTime
{
get { return _dt; }
set { _dt = value; }
}
}
[Test]
public void SetDateTimeProperty()
{
DateTimeTestObject o = new DateTimeTestObject();
ObjectWrapper wrapper = GetWrapper(o);
wrapper.SetPropertyValue("TriggerDateTime", "1991-10-10");
Assert.AreEqual(1991, ((DateTime) wrapper.GetPropertyValue("TriggerDateTime")).Year);
}
#endregion
#region Test for CultureInfo Properties
internal class CultureTestObject
{
private CultureInfo _ci;
public CultureInfo Cult
{
get { return _ci; }
set { _ci = value; }
}
}
[Test]
public void SetCultureInfoProperty()
{
CultureTestObject o = new CultureTestObject();
ObjectWrapper wrapper = GetWrapper(o);
wrapper.SetPropertyValue("Cult", "es-ES");
Assert.AreEqual("es-ES",
((CultureInfo) wrapper.GetPropertyValue("Cult")).Name);
}
#endregion
#region Tests for URI Properties
internal class URITestObject
{
private Uri _uri;
public Uri ResourceIdentifier
{
get { return _uri; }
set { _uri = value; }
}
}
[Test]
public void SetURIProperty()
{
URITestObject o = new URITestObject();
ObjectWrapper wrapper = GetWrapper(o);
wrapper.SetPropertyValue("ResourceIdentifier", "http://www.springframework.net");
Assert.AreEqual("www.springframework.net",
((Uri) wrapper.GetPropertyValue("ResourceIdentifier")).Host);
}
#endregion
#region Tests for Indexed Array Properties
[Test]
public void GetIndexedFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Array[0]"));
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexOutofRangeFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
wrapper.GetPropertyValue("Array[5]");
}
[Test]
public void SetIndexedFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
wrapper.SetPropertyValue("Array[2]", 6);
Assert.AreEqual(6, to.Array[2]);
}
[Test]
[ExpectedException(typeof(InvalidPropertyException))]
public void SetIndexOutOfRangeFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
wrapper.SetPropertyValue("Array[5]", 6);
}
/// <summary>
/// Test that we bail when attempting to get an indexed property with some guff for the index
/// </summary>
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithGuffIndexFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Array[HungerHurtsButStarvingWorks]"));
}
/// <summary>
/// Test that we bail when attempting to get an indexed property with some guff for the index
/// </summary>
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithMissingIndexFromArrayProperty()
{
PrimitiveArrayObject to = new PrimitiveArrayObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Array = new int[] {1, 2, 3, 4, 5};
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Array[]"));
}
#endregion
#region Tests for Indexed List Properties
internal class ListTestObject
{
private IList _list;
private ArrayList _arrayList;
public IList List
{
get { return _list; }
set { _list = value; }
}
public ArrayList ArrayList
{
get { return _arrayList; }
set { _arrayList = value; }
}
}
[Test]
public void GetIndexedFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("List[0]"));
}
[Test]
public void GetIndexedFromArrayListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.ArrayList = new ArrayList(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("ArrayList[0]"));
}
[Test]
[ExpectedException(typeof(InvalidPropertyException))]
public void GetIndexOutofRangeFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.GetPropertyValue("List[5]");
}
[Test]
public void SetIndexedFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.SetPropertyValue("List[0]", 6);
Assert.AreEqual(6, to.List[0]);
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void SetIndexedFromListPropertyUsingMixOfSingleAndDoubleQuotedDelimeters()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.SetPropertyValue("List['0\"]", 6);
Assert.AreEqual(6, to.List[0]);
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void SetIndexedFromListPropertyUsingNonNumericValueForTheIndex()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.SetPropertyValue("List[bingo]", 6);
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void SetIndexedFromListPropertyUsingEmptyValueForTheIndex()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.SetPropertyValue("List[]", 6);
}
[Test]
[Ignore("Addition of elements to the list via index that is out of range is not supported anymore.")]
public void SetIndexOutOfRangeFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
wrapper.SetPropertyValue("List[6]", 6);
Assert.AreEqual(6, to.List[6]);
Assert.IsNull(to.List[5]);
wrapper.SetPropertyValue("List[7]", 7);
Assert.AreEqual(7, to.List[7]);
}
/// <summary>
/// Test that we bail when attempting to get an indexed property with some guff for the index
/// </summary>
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithGuffIndexFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("List[HungerHurtsButStarvingWorks]"));
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithMissingIndexFromListProperty()
{
ListTestObject to = new ListTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.List = new ArrayList(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("List[]"));
}
#endregion
#region Tests for Indexed Dictionary Properties
internal class DictionaryTestObject
{
private IDictionary _dictionary;
public IDictionary Dictionary
{
get { return _dictionary; }
set { _dictionary = value; }
}
}
[Test]
public void GetIndexedFromDictionaryProperty()
{
DictionaryTestObject to = new DictionaryTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Dictionary = new Hashtable();
to.Dictionary.Add("key1", "value1");
Assert.AreEqual("value1", (string) wrapper.GetPropertyValue("Dictionary['key1']"));
}
[Test]
public void GetIndexMissingFromDictionaryProperty()
{
DictionaryTestObject to = new DictionaryTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Dictionary = new Hashtable();
Assert.IsNull(wrapper.GetPropertyValue("Dictionary['notthere']"));
}
[Test]
public void SetIndexedFromDictionaryProperty()
{
DictionaryTestObject to = new DictionaryTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Dictionary = new Hashtable();
wrapper.SetPropertyValue("Dictionary['key1']", "value1");
Assert.AreEqual("value1", to.Dictionary["key1"]);
}
[Test]
public void SettingADictionaryPropertyJustAddsTheValuesToTheExistingDictionary()
{
TestObject to = new TestObject();
to.AddPeriodicElement("Hsu", "Feng");
to.AddPeriodicElement("Piao", "Jin");
ObjectWrapper wrapper = GetWrapper(to);
IDictionary elements = new Hashtable();
elements.Add("Weekend", "News");
wrapper.SetPropertyValue("PeriodictabLE", elements);
Assert.AreEqual(3, to.PeriodicTable.Count);
}
#endregion
#region Tests for Indexed Set Properties
internal class SetTestObject
{
private ISet _set;
private HybridSet _aSet;
public ISet Set
{
get { return _set; }
set { _set = value; }
}
public HybridSet HybridSet
{
get { return _aSet; }
set { _aSet = value; }
}
}
[Test]
public void SettingASetPropertyJustAddsTheValuesToTheExistingSet()
{
TestObject to = new TestObject();
to.AddComputerName("Atari 2900");
to.AddComputerName("JCN");
ObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Computers", new HybridSet(new string[] {"Trusty SNES"}));
Assert.AreEqual(3, to.Computers.Count);
}
[Test]
[ExpectedException(typeof(InvalidPropertyException))]
public void GetIndexFromSetProperty()
{
SetTestObject to = new SetTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Set = new ListSet(new int[] { 1, 2, 3, 4, 5 });
Assert.AreEqual(1, (int)wrapper.GetPropertyValue("Set[1]"));
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexOutofRangeFromSetProperty()
{
SetTestObject to = new SetTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Set = new ListSet(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Set[23]"));
}
/// <summary>
/// Test that we bail when attempting to get an indexed property with some guff for the index
/// </summary>
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithGuffIndexFromSetProperty()
{
SetTestObject to = new SetTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Set = new ListSet(new int[] {1, 2, 3, 4, 5});
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Set[HungerHurtsButStarvingWorks]"));
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithMissingIndexFromSetProperty()
{
SetTestObject to = new SetTestObject();
IObjectWrapper wrapper = GetWrapper(to);
to.Set = new ListSet(new int[] {1, 2, 3, 4, 5});
object o = wrapper.GetPropertyValue("Set[]");
Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Set[]"));
}
#endregion
#region Test for Enumeration Properties
internal class EnumTestObject
{
private FileMode FileModeEnum;
public FileMode FileMode
{
get { return FileModeEnum; }
set { FileModeEnum = value; }
}
}
[Test]
public void SetEnumProperty()
{
EnumTestObject o = new EnumTestObject();
ObjectWrapper wrapper = GetWrapper(o);
wrapper.SetPropertyValue("FileMode", FileMode.Create);
Assert.AreEqual(FileMode.Create, (FileMode) wrapper.GetPropertyValue("FileMode"));
}
#endregion
[Test]
public void SetTypePropertyWithString()
{
ObjectWithTypeProperty to = new ObjectWithTypeProperty();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Type", "System.DateTime");
Assert.AreEqual(typeof (DateTime), to.Type);
}
[Test]
[ExpectedException(typeof (InvalidPropertyException))]
public void GetIndexedPropertyValueWithNonIndexedType()
{
TestObject to = new TestObject();
IObjectWrapper wrapper = GetWrapper(to);
wrapper.GetPropertyValue("FileMode[0]");
}
[Test]
[ExpectedException(typeof (NullValueInNestedPathException))]
public void SetPropertyValuesWithUnknownProperty()
{
TestObject to = new TestObject();
to.Doctor = null;
ObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Doctor.Company", "Bingo");
}
[Test]
[ExpectedException(typeof(InvalidPropertyException))]
public void SetPropertyValuesFailsWhenSettingNonExistantProperty()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
MutablePropertyValues values = new MutablePropertyValues();
values.Add("JeepersCreepersWhereDidYaGetThosePeepers", "OhThisWeirdBatGuySoldEmToMe...");
values.Add("Age", 19);
// the unknown and ridiculously named property should fail
wrapper.SetPropertyValues(values, false);
}
[Test]
public void SetPropertyValuesDoesNotFailWhenSettingNonExistantPropertyWithIgnorUnknownSetToTrue()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
MutablePropertyValues values = new MutablePropertyValues();
values.Add("Age", 19);
values.Add("JeepersCreepersWhereDidYaGetThosePeepers", "OhThisWeirdBatGuySoldEmToMe...");
// the unknown and ridiculously named property should fail
wrapper.SetPropertyValues(values, true);
Assert.AreEqual(19, to.Age, "The single good property in the property values should have been set though...");
}
[Test]
[ExpectedException(typeof(NotWritablePropertyException))]
public void SetPropertyValuesFailsWhenSettingReadOnlyProperty()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
MutablePropertyValues values = new MutablePropertyValues();
values.Add("ReadOnlyObjectNumber", 123);
wrapper.SetPropertyValues(values, false);
}
[Test]
public void SetPropertyValuesDoesNotFailWhenSettingReadOnlyPropertyWithIgnorUnknownSetToTrue()
{
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
MutablePropertyValues values = new MutablePropertyValues();
values.Add("ObjectNumber", 123);
values.Add("Age", 19);
wrapper.SetPropertyValues(values, true);
Assert.AreEqual(19, to.Age, "The single good property in the property values should have been set though...");
}
[Test]
public void SetArrayPropertyValue()
{
string[] expected = new string[] {"Fedora", "Gacy", "Banjo"};
TestObject to = new TestObject();
ObjectWrapper wrapper = GetWrapper(to);
wrapper.SetPropertyValue("Hats", expected);
Assert.IsNotNull(to.Hats);
Assert.AreEqual(expected.Length, to.Hats.Length);
for (int i = 0; i < expected.Length; ++i)
{
Assert.AreEqual(expected[i], to.Hats[i]);
}
}
[Test]
public void TestToString()
{
ObjectWrapper wrapper = GetWrapper();
Assert.IsTrue(wrapper.ToString().IndexOf("Exception encountered") >= 0);
wrapper.WrappedInstance = new WanPropsClass();
string expected = string.Format(
"{0}: wrapping class [{1}]; IsWan={2}",
wrapper.GetType().Name, wrapper.WrappedType.FullName, "{True}");
Assert.AreEqual(expected, wrapper.ToString());
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void GetPropertyInfoWithNullArgument()
{
ObjectWrapper wrapper = GetWrapper(new TestObject());
wrapper.GetPropertyInfo(null);
}
[Test]
[ExpectedException(typeof (FatalReflectionException))]
public void GetPropertyInfoWithNonPropertyExpression()
{
ObjectWrapper wrapper = GetWrapper(new TestObject());
wrapper.GetPropertyInfo("2 + 2");
}
[Test]
[ExpectedException(typeof (FatalObjectException))]
public void GetPropertyInfoWithNonParsableExpression()
{
ObjectWrapper wrapper = GetWrapper(new TestObject());
wrapper.GetPropertyInfo("[");
}
[Test]
public void GetNestedPropertyInfo()
{
RealNestedTestObject o = new RealNestedTestObject();
o.Datum = new TestObject();
o.Datum.Doctor = new NestedTestObject("Modlin");
ObjectWrapper wrapper = GetWrapper(o);
PropertyInfo info = wrapper.GetPropertyInfo("Datum.Doctor.Company");
Assert.IsNotNull(info);
}
[Test(Description="SPRNET-198")]
public void AmbiguousPropertyLookupIsHandledProperlyByLookingAtDerivedClassOnly()
{
ObjectWrapper wrapper = GetWrapper(new DerivedFoo());
wrapper.GetPropertyInfo("Bar");
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitcoin.DataEncoders;
namespace BTCPayServer.Security.Bitpay
{
public enum PairingResult
{
Partial,
Complete,
ReusedKey,
Expired
}
public class TokenRepository
{
readonly ApplicationDbContextFactory _Factory;
public TokenRepository(ApplicationDbContextFactory dbFactory)
{
ArgumentNullException.ThrowIfNull(dbFactory);
_Factory = dbFactory;
}
public async Task<BitTokenEntity[]> GetTokens(string sin)
{
if (sin == null)
return Array.Empty<BitTokenEntity>();
using var ctx = _Factory.CreateContext();
return (await ctx.PairedSINData.Where(p => p.SIN == sin)
.ToArrayAsync())
.Select(p => CreateTokenEntity(p))
.ToArray();
}
public async Task<String> GetStoreIdFromAPIKey(string apiKey)
{
using var ctx = _Factory.CreateContext();
return await ctx.ApiKeys.Where(o => o.Id == apiKey).Select(o => o.StoreId).FirstOrDefaultAsync();
}
public async Task GenerateLegacyAPIKey(string storeId)
{
// It is legacy support and Bitpay generate string of unknown format, trying to replicate them
// as good as possible. The string below got generated for me.
var chars = "ERo0vkBMOYhyU0ZHvirCplbLDIGWPdi1ok77VnW7QdE";
var generated = new char[chars.Length];
for (int i = 0; i < generated.Length; i++)
{
generated[i] = chars[(int)(RandomUtils.GetUInt32() % generated.Length)];
}
using var ctx = _Factory.CreateContext();
var existing = await ctx.ApiKeys.Where(o => o.StoreId == storeId && o.Type == APIKeyType.Legacy).ToListAsync();
if (existing.Any())
{
ctx.ApiKeys.RemoveRange(existing);
}
ctx.ApiKeys.Add(new APIKeyData() { Id = new string(generated), StoreId = storeId });
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
public async Task RevokeLegacyAPIKeys(string storeId)
{
var keys = await GetLegacyAPIKeys(storeId);
if (!keys.Any())
{
return;
}
using var ctx = _Factory.CreateContext();
ctx.ApiKeys.RemoveRange(keys.Select(s => new APIKeyData() { Id = s }));
await ctx.SaveChangesAsync();
}
public async Task<string[]> GetLegacyAPIKeys(string storeId)
{
using var ctx = _Factory.CreateContext();
return await ctx.ApiKeys.Where(o => o.StoreId == storeId && o.Type == APIKeyType.Legacy).Select(c => c.Id).ToArrayAsync();
}
private BitTokenEntity CreateTokenEntity(PairedSINData data)
{
return new BitTokenEntity()
{
Label = data.Label,
Value = data.Id,
SIN = data.SIN,
PairingTime = data.PairingTime,
StoreId = data.StoreDataId
};
}
public async Task<string> CreatePairingCodeAsync()
{
string pairingCodeId = null;
while (true)
{
pairingCodeId = Encoders.Base58.EncodeData(RandomUtils.GetBytes(6));
if (pairingCodeId.Length == 7) // woocommerce plugin check for exactly 7 digits
break;
}
using (var ctx = _Factory.CreateContext())
{
var now = DateTime.UtcNow;
var expiration = DateTime.UtcNow + TimeSpan.FromMinutes(15);
ctx.PairingCodes.Add(new PairingCodeData()
{
Id = pairingCodeId,
DateCreated = now,
Expiration = expiration,
TokenValue = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32))
});
await ctx.SaveChangesAsync();
}
return pairingCodeId;
}
public async Task<PairingCodeEntity> UpdatePairingCode(PairingCodeEntity pairingCodeEntity)
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeEntity.Id);
pairingCode.Label = pairingCodeEntity.Label;
await ctx.SaveChangesAsync();
return CreatePairingCodeEntity(pairingCode);
}
public async Task<PairingResult> PairWithStoreAsync(string pairingCodeId, string storeId)
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeId);
if (pairingCode == null || pairingCode.Expiration < DateTimeOffset.UtcNow)
return PairingResult.Expired;
pairingCode.StoreDataId = storeId;
var result = await ActivateIfComplete(ctx, pairingCode);
await ctx.SaveChangesAsync();
return result;
}
public async Task<PairingResult> PairWithSINAsync(string pairingCodeId, string sin)
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeId);
if (pairingCode == null || pairingCode.Expiration < DateTimeOffset.UtcNow)
return PairingResult.Expired;
pairingCode.SIN = sin;
var result = await ActivateIfComplete(ctx, pairingCode);
await ctx.SaveChangesAsync();
return result;
}
private async Task<PairingResult> ActivateIfComplete(ApplicationDbContext ctx, PairingCodeData pairingCode)
{
if (!string.IsNullOrEmpty(pairingCode.SIN) && !string.IsNullOrEmpty(pairingCode.StoreDataId))
{
ctx.PairingCodes.Remove(pairingCode);
// Can have concurrency issues... but no harm can be done
var alreadyUsed = await ctx.PairedSINData.Where(p => p.SIN == pairingCode.SIN && p.StoreDataId != pairingCode.StoreDataId).AnyAsync();
if (alreadyUsed)
return PairingResult.ReusedKey;
await ctx.PairedSINData.AddAsync(new PairedSINData()
{
Id = pairingCode.TokenValue,
PairingTime = DateTime.UtcNow,
Label = pairingCode.Label,
StoreDataId = pairingCode.StoreDataId,
SIN = pairingCode.SIN
});
return PairingResult.Complete;
}
return PairingResult.Partial;
}
public async Task<BitTokenEntity[]> GetTokensByStoreIdAsync(string storeId)
{
using var ctx = _Factory.CreateContext();
return (await ctx.PairedSINData.Where(p => p.StoreDataId == storeId).ToListAsync())
.Select(c => CreateTokenEntity(c))
.ToArray();
}
public async Task<PairingCodeEntity> GetPairingAsync(string pairingCode)
{
using var ctx = _Factory.CreateContext();
return CreatePairingCodeEntity(await ctx.PairingCodes.FindAsync(pairingCode));
}
private PairingCodeEntity CreatePairingCodeEntity(PairingCodeData data)
{
if (data == null)
return null;
return new PairingCodeEntity()
{
Id = data.Id,
Label = data.Label,
Expiration = data.Expiration,
CreatedTime = data.DateCreated,
TokenValue = data.TokenValue,
SIN = data.SIN
};
}
public async Task<bool> DeleteToken(string tokenId)
{
using var ctx = _Factory.CreateContext();
var token = await ctx.PairedSINData.FindAsync(tokenId);
if (token == null)
return false;
ctx.PairedSINData.Remove(token);
await ctx.SaveChangesAsync();
return true;
}
public async Task<BitTokenEntity> GetToken(string tokenId)
{
using var ctx = _Factory.CreateContext();
var token = await ctx.PairedSINData.FindAsync(tokenId);
if (token == null)
return null;
return CreateTokenEntity(token);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace OfficeDevPnP.Core.Tools.UnitTest.PnPBuildExtensions
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2014 - 2017 XLR8 Development Team /
// ---------------------------------------------------------------------------------- /
// Licensed under the Apache License, Version 2.0 (the "License"); /
// you may not use this file except in compliance with the License. /
// You may obtain a copy of the License at /
// /
// http://www.apache.org/licenses/LICENSE-2.0 /
// /
// Unless required by applicable law or agreed to in writing, software /
// distributed under the License is distributed on an "AS IS" BASIS, /
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
// See the License for the specific language governing permissions and /
// limitations under the License. /
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace XLR8.CGLib
{
public class FastMethod : FastBase
{
/// <summary>
/// Class object that this method belongs to.
/// </summary>
private readonly FastClass _fastClass;
/// <summary>
/// Method that is being proxied
/// </summary>
private readonly MethodInfo _targetMethod;
/// <summary>
/// Dynamic method that is constructed for invocation.
/// </summary>
private readonly DynamicMethod _dynamicMethod;
private readonly Invoker _invoker;
private readonly Action<object>[] _preInvocationTypeCheck;
private readonly bool _isExtension;
/// <summary>
/// Gets the target method.
/// </summary>
/// <value>The target method.</value>
public MethodInfo Target
{
get { return _targetMethod; }
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public String Name
{
get { return _targetMethod.Name; }
}
/// <summary>
/// Gets the type of the return.
/// </summary>
/// <value>The type of the return.</value>
public Type ReturnType
{
get { return _targetMethod.ReturnType; }
}
/// <summary>
/// Gets the type of the declaring.
/// </summary>
/// <value>The type of the declaring.</value>
public FastClass DeclaringType
{
get { return _fastClass; }
}
/// <summary>
/// Gets the parameter count.
/// </summary>
/// <value>The parameter count.</value>
public int ParameterCount
{
get { return _targetMethod.GetParameters().Length; }
}
/// <summary>
/// Constructs a wrapper around the target method.
/// </summary>
/// <param name="fastClass">The _fast class.</param>
/// <param name="method">The method.</param>
internal FastMethod(FastClass fastClass, MethodInfo method)
{
// Store the class that spawned us
_fastClass = fastClass;
_targetMethod = method;
_isExtension = _targetMethod.IsDefined(typeof (ExtensionAttribute), true);
// Create a unique name for the method
String dynamicMethodName = "_CGLibM_" + _fastClass.Id + "_" + method.Name;
// Generate the method
_dynamicMethod = new DynamicMethod(
dynamicMethodName,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
typeof(Object),
new Type[]{ typeof(Object), typeof(Object[]) },
_targetMethod.Module,
true);
EmitInvoker(method, _dynamicMethod.GetILGenerator());
_invoker = (Invoker) _dynamicMethod.CreateDelegate(typeof (Invoker));
_preInvocationTypeCheck = GetParameterTypes(method)
.Select(CreateInvocationCheck)
.ToArray();
}
private static readonly Action<object> PrimitiveInvocationCheck =
o =>
{
if (o == null)
{
throw new TargetInvocationException(
new ArgumentException("invalid assignment of null to primitive type"));
}
};
private static readonly Action<object> EmptyInvocationCheck =
o => { };
static Action<object> CreateInvocationCheck(Type parameterType)
{
if (parameterType.IsPrimitive)
{
return PrimitiveInvocationCheck;
}
else
{
return EmptyInvocationCheck;
}
}
static void EmitInvoker(MethodInfo method, ILGenerator il)
{
il.DeclareLocal(typeof(object));
// Get the method parameters
Type[] parameterTypes = GetParameterTypes(method);
// Is the method non-static
if ( !method.IsStatic )
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, method.DeclaringType);
}
// Load method arguments
for( int ii = 0 ; ii < parameterTypes.Length ; ii++ )
{
Type paramType = parameterTypes[ii];
il.Emit(OpCodes.Ldarg_1);
EmitLoadInt(il, ii);
il.Emit(OpCodes.Ldelem_Ref);
EmitCastConversion(il, paramType);
}
// Emit code to call the method
il.Emit(OpCodes.Call, method);
if (method.ReturnType == typeof(void))
{
il.Emit(OpCodes.Ldnull);
}
else if ( method.ReturnType.IsValueType )
{
il.Emit(OpCodes.Box, method.ReturnType);
}
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
// Emit code for return value
il.Emit(OpCodes.Ret);
}
/// <summary>
/// Invokes the method on the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="paramList">The param list.</param>
public Object Invoke(Object target, params Object[] paramList)
{
#if USE_REFLECTION
return targetMethod.Invoke(target, paramList);
#else
if (_isExtension && (target != null))
{
var argList = new object[paramList.Length + 1];
argList[0] = target;
Array.Copy(paramList, 0, argList, 1, paramList.Length);
for (int ii = 0; ii < _preInvocationTypeCheck.Length; ii++)
{
_preInvocationTypeCheck[ii].Invoke(argList[ii]);
}
return _invoker(null, argList);
}
else
{
for (int ii = 0; ii < _preInvocationTypeCheck.Length; ii++)
{
_preInvocationTypeCheck[ii].Invoke(paramList[ii]);
}
return _invoker(target, paramList);
}
#endif
}
/// <summary>
/// Invokes the method on the specified target.
/// </summary>
/// <param name="paramList">The param list.</param>
/// <returns></returns>
public Object InvokeStatic(params Object[] paramList)
{
return _invoker(null, paramList);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Reflection;
using System.Xml;
using NUnit.Framework.Api;
using NUnit.Framework.Internal.Commands;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The Test abstract class represents a test within the framework.
/// </summary>
public abstract class Test : ITest, IComparable
{
#region Fields
/// <summary>
/// Static value to seed ids. It's started at 1000 so any
/// uninitialized ids will stand out.
/// </summary>
private static int nextID = 1000;
private int id;
private string name;
private string fullName;
/// <summary>
/// Indicates whether the test should be executed
/// </summary>
private RunState runState;
/// <summary>
/// Test suite containing this test, or null
/// </summary>
private ITest parent;
/// <summary>
/// A dictionary of properties, used to add information
/// to tests without requiring the class to change.
/// </summary>
private PropertyBag properties;
/// <summary>
/// The System.Type of the fixture for this test suite, if there is one
/// </summary>
private Type fixtureType;
/// <summary>
/// The fixture object, if it has been created
/// </summary>
private object fixture;
/// <summary>
/// The SetUp methods.
/// </summary>
protected MethodInfo[] setUpMethods;
/// <summary>
/// The teardown method
/// </summary>
protected MethodInfo[] tearDownMethods;
/// <summary>
/// Argument list for use in executing the test.
/// </summary>
internal object[] arguments;
private TestCommand testCommand;
#endregion
#region Construction
/// <summary>
/// Constructs a test given its name
/// </summary>
/// <param name="name">The name of the test</param>
protected Test( string name )
{
this.fullName = name;
this.name = name;
this.id = unchecked(nextID++);
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given the path through the
/// test hierarchy to its parent and a name.
/// </summary>
/// <param name="pathName">The parent tests full name</param>
/// <param name="name">The name of the test</param>
protected Test( string pathName, string name )
{
this.fullName = pathName == null || pathName == string.Empty
? name : pathName + "." + name;
this.name = name;
this.id = unchecked(nextID++);
this.runState = RunState.Runnable;
}
/// <summary>
/// TODO: Documentation needed for constructor
/// </summary>
/// <param name="fixtureType"></param>
protected Test(Type fixtureType) : this(fixtureType.FullName)
{
this.fixtureType = fixtureType;
}
#endregion
#region ITest Members
/// <summary>
/// Gets or sets the id of the test
/// </summary>
/// <value></value>
public int Id
{
get { return id; }
set { id = value; }
}
/// <summary>
/// Gets or sets the name of the test
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the test
/// </summary>
/// <value></value>
public string FullName
{
get { return fullName; }
set { fullName = value; }
}
/// <summary>
/// Gets the Type of the fixture used in running this test
/// or null if no fixture type is associated with it.
/// </summary>
public Type FixtureType
{
get { return fixtureType; }
}
/// <summary>
/// Whether or not the test should be run
/// </summary>
public RunState RunState
{
get { return runState; }
set { runState = value; }
}
/// </summary>
/// <summary>
/// Gets the name used for the top-level element in the
/// XML representation of this test
/// </summary>
public abstract string XmlElementName
{
get;
}
/// <summary>
/// Gets a string representing the type of test. Used as an attribute
/// value in the XML representation of a test and has no other
/// function in the framework.
/// </summary>
public virtual string TestType
{
get { return this.GetType().Name; }
}
/// <summary>
/// Gets a count of test cases represented by
/// or contained under this test.
/// </summary>
public virtual int TestCaseCount
{
get { return 1; }
}
/// <summary>
/// Gets the properties for this test
/// </summary>
public IPropertyBag Properties
{
get
{
if ( properties == null )
properties = new PropertyBag();
return properties;
}
}
/// <summary>
/// Gets a bool indicating whether the current test
/// has any descendant tests.
/// </summary>
public abstract bool HasChildren { get; }
/// <summary>
/// Gets the parent as a Test object.
/// Used by the core to set the parent.
/// </summary>
public ITest Parent
{
get { return parent; }
set { parent = value; }
}
/// <summary>
/// Gets this test's child tests
/// </summary>
/// <value>A list of child tests</value>
#if true
public abstract System.Collections.Generic.IList<ITest> Tests { get; }
#else
public abstract System.Collections.IList Tests { get; }
#endif
#endregion
#region IXmlNodeBuilder Members
/// <summary>
/// Returns the Xml representation of the test
/// </summary>
/// <param name="recursive">If true, include child tests recursively</param>
/// <returns></returns>
public XmlNode ToXml(bool recursive)
{
XmlNode topNode = XmlHelper.CreateTopLevelElement("dummy");
XmlNode thisNode = AddToXml(topNode, recursive);
return thisNode;
}
/// <summary>
/// Returns an XmlNode representing the current result after
/// adding it as a child of the supplied parent node.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public abstract XmlNode AddToXml(XmlNode parentNode, bool recursive);
#endregion
#region IComparable Members
/// <summary>
/// Compares this test to another test for sorting purposes
/// </summary>
/// <param name="obj">The other test</param>
/// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
public int CompareTo(object obj)
{
Test other = obj as Test;
if (other == null)
return -1;
return this.FullName.CompareTo(other.FullName);
}
#endregion
#region Other Public Methods
/// <summary>
/// Creates a TestResult for this test.
/// </summary>
/// <returns>A TestResult suitable for this type of test.</returns>
public abstract TestResult MakeTestResult();
/// <summary>
/// Gets a test command to be used in executing this test
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public TestCommand GetTestCommand(ITestFilter filter)
{
if (testCommand == null)
testCommand = runState != RunState.Runnable && runState != RunState.Explicit
? new SkipCommand(this)
: MakeTestCommand(filter);
return testCommand;
}
///// <summary>
///// Gets a count of test cases that would be run using
///// the specified filter.
///// </summary>
///// <param name="filter"></param>
///// <returns></returns>
//public virtual int CountTestCases(TestFilter filter)
//{
// if (filter.Pass(this))
// return 1;
// return 0;
//}
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied ICustomAttributeProvider, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances.
/// </summary>
/// <param name="provider">An object implementing ICustomAttributeProvider</param>
public void ApplyCommonAttributes(ICustomAttributeProvider provider)
{
foreach (Attribute attribute in provider.GetCustomAttributes(typeof(NUnitAttribute), true))
{
IApplyToTest iApply = attribute as IApplyToTest;
if (iApply != null)
{
iApply.ApplyToTest(this);
}
}
}
#endregion
#region Protected Methods
/// <summary>
/// Make a test command for running this test
/// </summary>
/// <param name="filter">A test filter used to select child tests for inclusion.</param>
/// <returns>A TestCommand, which runs the test when executed.</returns>
protected abstract TestCommand MakeTestCommand(ITestFilter filter);
/// <summary>
/// Add standard attributes and members to a test node.
/// </summary>
/// <param name="thisNode"></param>
/// <param name="recursive"></param>
protected void PopulateTestNode(XmlNode thisNode, bool recursive)
{
XmlHelper.AddAttribute(thisNode, "id", this.Id.ToString());
XmlHelper.AddAttribute(thisNode, "name", this.Name);
XmlHelper.AddAttribute(thisNode, "fullname", this.FullName);
if (Properties.Count > 0)
Properties.AddToXml(thisNode, recursive);
}
#endregion
#region Internal Properties
/// <summary>
/// Gets or sets a fixture object for running this test.
/// Provided for use by LegacySuiteBuilder.
/// </summary>
internal object Fixture
{
get { return fixture; }
set { fixture = value; }
}
#if !NUNITLITE && false
/// <summary>
/// Gets a boolean value indicating whether this
/// test should run on it's own thread.
/// </summary>
internal virtual bool ShouldRunOnOwnThread
{
get
{
if (Properties.GetSetting(PropertyNames.RequiresThread, false))
return true;
ApartmentState state = (ApartmentState)Properties.GetSetting(PropertyNames.ApartmentState, ApartmentState.Unknown);
if (state == ApartmentState.Unknown)
return false;
return state != Thread.CurrentThread.GetApartmentState();
}
}
#endif
/// <summary>
/// Gets the set up methods.
/// </summary>
/// <returns></returns>
internal virtual MethodInfo[] SetUpMethods
{
get
{
if (setUpMethods == null && this.Parent != null)
{
TestSuite suite = this.Parent as TestSuite;
if (suite != null)
setUpMethods = suite.SetUpMethods;
}
return setUpMethods;
}
}
/// <summary>
/// Gets the tear down methods.
/// </summary>
/// <returns></returns>
internal virtual MethodInfo[] TearDownMethods
{
get
{
if (tearDownMethods == null && this.Parent != null)
{
TestSuite suite = this.Parent as TestSuite;
if (suite != null)
tearDownMethods = suite.TearDownMethods;
}
return tearDownMethods;
}
}
#endregion
}
}
| |
using CellSpacePartitionLib;
using FlockBuddy.Interfaces;
using FlockBuddy.Interfaces.Behaviors;
using FlockBuddy.SteeringBehaviors;
using GameTimer;
using Microsoft.Xna.Framework;
using PrimitiveBuddy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Vector2Extensions;
namespace FlockBuddy
{
/// <summary>
/// Definition of a simple vehicle that uses steering behaviors
/// </summary>
public class Boid : Mover, IBoid
{
#region Members
private Vector2 _totalForce = Vector2.Zero;
private Vector2 _directionForce = Vector2.Zero;
private Vector2 _speedForce = Vector2.Zero;
/// <summary>
/// a vector perpendicular to the heading vector
/// </summary>
private Vector2 _side;
#endregion Members
#region Properties
/// <summary>
/// The list of behaviors this boid will use
/// </summary>
protected List<IBehavior> Behaviors { get; set; }
/// <summary>
/// How to add up all the steering behaviors
/// </summary>
public SummingMethod SummingMethod { get; set; }
/// <summary>
/// the flock that owns this dude
/// </summary>
private IFlock MyFlock { get; set; }
public float RetargetTime { get; set; }
public CountdownTimer RetargetTimer { get; set; }
/// <summary>
/// how far out to check for neighbors
/// </summary>
public float NeighborsQueryRadius { get; set; }
/// <summary>
/// how far out to watch for predators
/// </summary>
public float PredatorsQueryRadius { get; set; }
/// <summary>
/// how far to watch out for prey
/// </summary>
public float PreyQueryRadius { get; set; }
/// <summary>
/// how far to watch out or vips to guard
/// </summary>
public float VipQueryRadius { get; set; }
public float ObstacleQueryRadius { get; set; }
public float WallQueryRadius { get; set; }
public float WaypointQueryRadius { get; set; }
public float Mass { get; set; }
public float MinSpeed { get; set; }
public float WalkSpeed { get; set; }
/// <summary>
/// If the total force is less than laziness, this boid will stop moving.
/// </summary>
public float Laziness { get; set; }
/// <summary>
/// the maximum speed this entity may travel at.
/// </summary>
public float MaxSpeed { get; set; }
/// <summary>
/// the maximum force this entity can produce to power itself (think rockets and thrust)
/// </summary>
public float MaxForce { get; set; }
/// <summary>
/// the maximum rate (radians per second)this vehicle can rotate
/// </summary>
public float MaxTurnRate { get; set; }
public override Vector2 Heading
{
get
{
return base.Heading;
}
set
{
// If the new heading is valid this fumction sets the entity's heading and side vectors accordingly
base.Heading = value;
//the side vector must always be perpendicular to the heading
_side = Heading.Perp();
}
}
public Vector2 Side
{
get
{
return _side;
}
}
#endregion //Properties
#region Methods
/// <summary>
/// Initializes a new instance of the <see cref="FlockBuddy.Boid"/> class.
/// </summary>
public Boid(IFlock owner,
Vector2 position,
Vector2 heading,
float speed,
float radius = BoidDefaults.BoidRadius)
: base(position,
radius,
heading,
speed)
{
MyFlock = owner;
MyFlock.AddBoid(this);
Behaviors = new List<IBehavior>();
RetargetTimer = new CountdownTimer();
Initialize();
}
public void Initialize(float mass = BoidDefaults.BoidMass,
float minSpeed = BoidDefaults.BoidMinSpeed,
float walkSpeed = BoidDefaults.BoidWalkSpeed,
float laziness = BoidDefaults.BoidLaziness,
float maxSpeed = BoidDefaults.BoidMaxSpeed,
float maxForce = BoidDefaults.BoidMaxForce,
float maxTurnRate = BoidDefaults.BoidMaxTurnRate,
SummingMethod summingMethod = BoidDefaults.DefaultSummingMethod,
float neighborsQueryRadius = BoidDefaults.BoidQueryRadius,
float predatorsQueryRadius = BoidDefaults.BoidQueryRadius,
float preyQueryRadius = BoidDefaults.BoidQueryRadius,
float vipQueryRadius = BoidDefaults.BoidQueryRadius,
float wallQueryRadius = BoidDefaults.BoidQueryRadius,
float obstacleQueryRadius = BoidDefaults.BoidQueryRadius,
float waypointQueryRadius = BoidDefaults.BoidQueryRadius,
float retargetTime = BoidDefaults.BoidRetargetTime)
{
Mass = mass;
MinSpeed = minSpeed;
WalkSpeed = walkSpeed;
Laziness = laziness;
MaxSpeed = maxSpeed;
MaxForce = maxForce;
MaxTurnRate = maxTurnRate;
SummingMethod = summingMethod;
NeighborsQueryRadius = neighborsQueryRadius;
PredatorsQueryRadius = predatorsQueryRadius;
PreyQueryRadius = preyQueryRadius;
VipQueryRadius = vipQueryRadius;
WallQueryRadius = wallQueryRadius;
ObstacleQueryRadius = obstacleQueryRadius;
WaypointQueryRadius = waypointQueryRadius;
RetargetTime = retargetTime;
RetargetTimer.Start(RetargetTime);
}
public IBehavior AddBehavior(BehaviorType behaviorType, float weight)
{
IBehavior behavior;
//first check if we alreadu have that behavior
if (!Behaviors.Exists(x => x.BehaviorType == behaviorType))
{
behavior = BaseBehavior.BehaviorFactory(behaviorType, this);
behavior.Weight = weight;
AddBehavior(behavior);
}
else
{
//we already have that behavior, just update the weight
behavior = Behaviors.Where(x => x.BehaviorType == behaviorType).First();
behavior.Weight = weight;
}
return behavior;
}
public void AddBehavior(IBehavior behavior)
{
if (!Behaviors.Exists(x => x.BehaviorType == behavior.BehaviorType))
{
Behaviors.Add(behavior);
Behaviors.Sort((x, y) => x.BehaviorType.CompareTo(y.BehaviorType));
}
else
{
//we already have that behavior, just update the weight
var currentbehavior = Behaviors.Where(x => x.BehaviorType == behavior.BehaviorType).First();
currentbehavior.Weight = behavior.Weight;
}
}
public void RemoveBehavior(IBehavior behavior)
{
Behaviors.Remove(behavior);
}
public void RemoveBehavior(BehaviorType behaviorType)
{
var behavior = Behaviors.Where(x => x.BehaviorType == behaviorType).FirstOrDefault();
if (behavior != null)
{
Behaviors.Remove(behavior);
}
}
/// <summary>
/// Updates the vehicle's position from a series of steering behaviors
/// </summary>
/// <param name="time"></param>
public override void Update(GameClock time)
{
base.Update(time);
//Acceleration = Force/Mass
GetForces();
//speed up or slow down depending on whether the target is ahead or behind
UpdateSpeed(_speedForce);
//turn towards that point if the vehicle has a non zero velocity
UpdateHeading(_directionForce);
//update the position
Vector2 currentPosition = Position + (Velocity * BoidTimer.TimeDelta);
//EnforceNonPenetrationConstraint(this, World()->Agents());
//treat the screen as a toroid
currentPosition = MyFlock.WrapWorldPosition(currentPosition);
//Update the position
Position = currentPosition;
}
/// <summary>
/// Given a target direction, either speed up or slow down the guy to get to it
/// </summary>
/// <param name="targetHeading"></param>
protected void UpdateSpeed(Vector2 targetHeading)
{
//update the speed but make sure vehicle does not exceed maximum velocity
Speed = MathHelper.Clamp(Speed + GetSpeedChange(targetHeading), MinSpeed, MaxSpeed);
}
protected float GetSpeedChange(Vector2 targetHeading)
{
//get the dot product of the current heading and the target
var dotHeading = Vector2.Dot(Heading, targetHeading);
//get the amount of force that can be applied pre timedelta
var maxForceDelta = MaxForce * BoidTimer.TimeDelta;
if (0f == dotHeading)
{
//if the dotproduct is exactly zero, we want to hit the target speed
if (Speed < WalkSpeed)
{
//if the total force is less than laziness, why bother speeding up?
if (_totalForce.LengthSquared() < (Laziness * Laziness))
{
return maxForceDelta *= -1f;
}
//we are going too slow, speed up!
return maxForceDelta;
}
else
{
//we are going too fast, slow down!
return maxForceDelta *= -1f;
}
}
else if ((0 < dotHeading) && (_totalForce.LengthSquared() >= (Laziness * Laziness)))
{
//if the dot product is greater than zero, we want to got the current direction
return maxForceDelta;
}
else if ((0 > dotHeading) && (_totalForce.LengthSquared() >= (Laziness * Laziness)))
{
//if the dot product is less than zero, we want to got the other direction
return maxForceDelta *= -1f;
}
else
{
//Don't go anywhere!
return 0f;
}
}
/// <summary>
/// given a target position, this method rotates the entity's heading and
/// side vectors by an amount not greater than m_dMaxTurnRate until it
/// directly faces the target.
/// </summary>
/// <param name="target"></param>
/// <returns>returns true when the heading is facing in the desired direction</returns>
protected bool UpdateHeading(Vector2 targetHeading)
{
//get the amount to turn towrads the new heading
float angle = 0.0f;
if (GetAmountToTurn(targetHeading, ref angle))
{
return true;
}
//update the heading
RotateHeading(angle);
return false;
}
/// <summary>
/// Given a target heading, figure out how much to turn towards that heading.
/// </summary>
/// <param name="targetHeading"></param>
/// <param name="angle"></param>
/// <returns>true if this dude's heading doesnt need to be updated.</returns>
protected bool GetAmountToTurn(Vector2 targetHeading, ref float angle)
{
if (targetHeading.LengthSquared() == 0.0f)
{
//we are at the target :P
return true;
}
//first determine the angle between the heading vector and the target
angle = Vector2Ext.AngleBetweenVectors(Heading, targetHeading);
angle = ClampAngle(angle);
//return true if the player is facing the target
if (Math.Abs(angle) < 0.001f)
{
return true;
}
//clamp the amount to turn between the maxturnrate of the timedelta
var maxTurnRateDelta = MaxTurnRate * BoidTimer.TimeDelta;
//clamp the amount to turn to the max turn rate
angle = MathHelper.Clamp(angle, -maxTurnRateDelta, maxTurnRateDelta);
return false;
}
/// <summary>
/// Update all the behaviors and calculate the steering force
/// </summary>
/// <returns></returns>
private void GetForces()
{
RetargetTimer.Update(BoidTimer);
if (!RetargetTimer.HasTimeRemaining)
{
//restart the timer
RetargetTimer.Start(RetargetTime);
var neighbors = FindNeighbors();
var predator = FindPredator();
var prey = FindPrey();
var vip = FindVip();
//update the obstacles: the detection box length is proportional to the agent's velocity
float boxLength = ObstacleQueryRadius + (Speed / MaxSpeed) * ObstacleQueryRadius;
//tag all obstacles within range of the box for processing
var obstacles = MyFlock.FindObstaclesInRange(this, boxLength);
//add all the walls
var walls = MyFlock.Walls;
foreach (var behavior in Behaviors)
{
var flockingBehavior = behavior as IFlockingBehavior;
if (null != flockingBehavior)
{
flockingBehavior.Buddies = neighbors;
}
var predatorBehavior = behavior as IPredatorBehavior;
if (null != predatorBehavior)
{
predatorBehavior.Prey = prey;
}
var preyBehavior = behavior as IPreyBehavior;
if (null != preyBehavior)
{
preyBehavior.Pursuer = predator;
}
var guardBehavior = behavior as IGuardBehavior;
if (null != guardBehavior)
{
guardBehavior.Vip = vip;
}
var obstacleBehavior = behavior as IObstacleBehavior;
if (null != obstacleBehavior)
{
obstacleBehavior.Obstacles = obstacles;
}
var wallBehavior = behavior as IWallBehavior;
if (null != wallBehavior)
{
wallBehavior.Walls = walls;
}
var pathBehavior = behavior as IPathBehavior;
if (null != pathBehavior)
{
pathBehavior.Path = MyFlock.Waypoints;
}
}
}
//calculate the combined force from each steering behavior in the vehicle's list
Calculate();
}
protected virtual IMover FindVip()
{
return MyFlock.FindClosestVipInRange(this, VipQueryRadius);
}
protected virtual IMover FindPrey()
{
return MyFlock.FindClosestPreyInRange(this, PreyQueryRadius);
}
protected virtual IMover FindPredator()
{
return MyFlock.FindClosestPredatorInRange(this, PredatorsQueryRadius);
}
protected virtual List<IMover> FindNeighbors()
{
return MyFlock.FindBoidsInRange(this, NeighborsQueryRadius);
}
/// <summary>
/// calculates and sums the steering forces from any active behaviors
/// </summary>
/// <returns></returns>
private void Calculate()
{
switch (SummingMethod)
{
case SummingMethod.WeightedAverage: { CalculateWeightedSum(); } break;
case SummingMethod.Prioritized: { CalculatePrioritized(); } break;
default: { CalculateDithered(); } break;
}
}
/// <summary>
/// this simply sums up all the active behaviors X their weights and
/// truncates the result to the max available steering force before returning
/// </summary>
/// <returns></returns>
private void CalculateWeightedSum()
{
_totalForce = Vector2.Zero;
_directionForce = Vector2.Zero;
_speedForce = Vector2.Zero;
for (int i = 0; i < Behaviors.Count; i++)
{
var steeringForce = Behaviors[i].GetSteering();
_totalForce += steeringForce;
_directionForce += steeringForce * Behaviors[i].DirectionChange;
_speedForce += steeringForce * Behaviors[i].SpeedChange;
if (Behaviors[i].BehaviorType == BehaviorType.Direction)
{
Debug.WriteLine(steeringForce.ToString());
}
}
//divide all forces by mass
_totalForce /= Mass;
_directionForce /= Mass;
_speedForce /= Mass;
}
/// <summary>
/// this method calls each active steering behavior in order of priority
/// and acumulates their forces until the max steering force magnitude
/// is reached, at which time the function returns the steering force
/// accumulated to that point
/// </summary>
/// <returns></returns>
private void CalculatePrioritized()
{
_totalForce = Vector2.Zero;
_directionForce = Vector2.Zero;
_speedForce = Vector2.Zero;
Vector2 steeringForce = Vector2.Zero;
Vector2 appliedForce;
for (int i = 0; i < Behaviors.Count; i++)
{
//get the steering forace from the behavior
steeringForce = Behaviors[i].GetSteering();
//apply as much of the steering force as is available
var result = AccumulateForce(ref _totalForce, out appliedForce, steeringForce);
//update the direction and speed vectors
_directionForce += appliedForce * Behaviors[i].DirectionChange;
_speedForce += appliedForce * Behaviors[i].SpeedChange;
//if we used up the available steering force, we are done collecting steering forces.
if (result)
{
break;
}
}
//divide all forces by mass
_totalForce /= Mass;
_directionForce /= Mass;
_speedForce /= Mass;
}
/// <summary>
/// this method sums up the active behaviors by assigning a probabilty
/// of being calculated to each behavior. It then tests the first priority
/// to see if it should be calcukated this simulation-step. If so, it
/// calculates the steering force resulting from this behavior. If it is
/// more than zero it returns the force. If zero, or if the behavior is
/// skipped it continues onto the next priority, and so on.
///
/// NOTE: Not all of the behaviors have been implemented in this method,
/// just a few, so you get the general idea
/// </summary>
/// <returns></returns>
private void CalculateDithered()
{
//reset the steering force
_totalForce = Vector2.Zero;
_directionForce = Vector2.Zero;
_speedForce = Vector2.Zero;
//if (IsActive(BehaviorType.wall_avoidance) && RandFloat() < Prm.prWallAvoidance)
//{
// steeringForce = WallAvoidance(m_pVehicle->World()->Walls()) *
// m_dWeightWallAvoidance / Prm.prWallAvoidance;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.obstacle_avoidance) && RandFloat() < Prm.prObstacleAvoidance)
//{
// steeringForce += ObstacleAvoidance(m_pVehicle->World()->Obstacles()) *
// m_dWeightObstacleAvoidance / Prm.prObstacleAvoidance;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.separation) && RandFloat() < Prm.prSeparation)
//{
// steeringForce += SeparationPlus(m_pVehicle->World()->Agents()) *
// m_dWeightSeparation / Prm.prSeparation;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.flee) && RandFloat() < Prm.prFlee)
//{
// steeringForce += Flee(m_pVehicle->World()->Crosshair()) * m_dWeightFlee / Prm.prFlee;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.evade) && RandFloat() < Prm.prEvade)
//{
// assert(m_pTargetAgent1 && "Evade target not assigned");
// steeringForce += Evade(m_pTargetAgent1) * m_dWeightEvade / Prm.prEvade;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.allignment) && RandFloat() < Prm.prAlignment)
//{
// steeringForce += AlignmentPlus(m_pVehicle->World()->Agents()) *
// m_dWeightAlignment / Prm.prAlignment;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.cohesion) && RandFloat() < Prm.prCohesion)
//{
// steeringForce += CohesionPlus(m_pVehicle->World()->Agents()) *
// m_dWeightCohesion / Prm.prCohesion;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.Wander) && RandFloat() < Prm.prWander)
//{
// steeringForce += Wander() * m_dWeightWander / Prm.prWander;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.seek) && RandFloat() < Prm.prSeek)
//{
// steeringForce += Seek(m_pVehicle->World()->Crosshair()) * m_dWeightSeek / Prm.prSeek;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
//if (IsActive(BehaviorType.arrive) && RandFloat() < Prm.prArrive)
//{
// steeringForce += Arrive(m_pVehicle->World()->Crosshair(), m_Deceleration) *
// m_dWeightArrive / Prm.prArrive;
// if (!steeringForce.isZero())
// {
// steeringForce.Truncate(m_pVehicle->MaxForce());
// return steeringForce;
// }
//}
}
/// <summary>
/// This function calculates how much of its max steering force the
/// vehicle has left to apply and then applies that amount of the
/// force to add.
/// </summary>
/// <param name="RunningTot"></param>
/// <param name="ForceToAdd"></param>
/// <returns></returns>
private bool AccumulateForce(ref Vector2 runningTot, out Vector2 appliedForce, Vector2 forceToAdd)
{
//calculate how much steering force the vehicle has used so far
float magnitudeSoFar = runningTot.Length();
//calculate how much steering force remains to be used by this vehicle
float magnitudeRemaining = MaxForce - magnitudeSoFar;
//return false if there is no more force left to use
if (magnitudeRemaining <= 0.0f)
{
appliedForce = Vector2.Zero;
return false;
}
//calculate the magnitude of the force we want to add
float magnitudeToAdd = forceToAdd.Length();
//if the magnitude of the sum of ForceToAdd and the running total
//does not exceed the maximum force available to this vehicle, just
//add together. Otherwise add as much of the ForceToAdd vector is
//possible without going over the max.
if (magnitudeToAdd < magnitudeRemaining)
{
appliedForce = forceToAdd;
runningTot += forceToAdd;
return true;
}
else
{
//add it to the steering force
appliedForce = forceToAdd.Normalized();
appliedForce *= magnitudeRemaining;
runningTot += appliedForce;
return false;
}
}
#endregion //Methods
#region Drawing
/// <summary>
/// Draw the bounding circle and heading of this boid
/// </summary>
/// <param name="prim"></param>
/// <param name="color"></param>
public override void Draw(IPrimitive prim, Color color)
{
base.Draw(prim, color);
}
/// <summary>
/// Draw the detection circle and point out all the neighbors
/// </summary>
/// <param name="curTime"></param>
public override void DrawNeigborQuery(IPrimitive prim, Color color)
{
////draw the query cells
//MyFlock.CellSpace.RenderCellIntersections(prim, Position, QueryRadius, Color.Green);
////get the query rectangle
//var queryRect = CellSpacePartition<Boid>.CreateQueryBox(Position, QueryRadius);
//prim.Rectangle(queryRect, Color.White);
//get the query circle
prim.Circle(Position, NeighborsQueryRadius, color);
////draw the neighbor dudes
//List<IMover> neighbors = MyFlock.FindNeighbors(this, QueryRadius);
//foreach (var neighbor in neighbors)
//{
// prim.Circle(neighbor.Position, neighbor.Radius, Color.Red);
//}
}
public override void DrawPursuitQuery(IPrimitive prim)
{
var pursuit = Behaviors.FirstOrDefault(x => x.BehaviorType == BehaviorType.Pursuit) as Pursuit;
if (null != pursuit && pursuit.Prey != null)
{
prim.Circle(Position, PreyQueryRadius, Color.Red);
}
else
{
prim.Circle(Position, PreyQueryRadius, Color.White);
}
}
public void DrawTotalForce(IPrimitive prim, Color color)
{
//draw the force being applied
prim.Line(Position, Position + _totalForce, color);
}
public void DrawWallFeelers(IPrimitive prim, Color color)
{
//get the wall avoidance steering behavior
var behav = Behaviors.Where(x => x is WallAvoidance).FirstOrDefault();
//draw all the whiskers
var wallAvoidance = behav as IWallBehavior;
if (null != wallAvoidance)
{
foreach (var whisker in wallAvoidance.Feelers)
{
prim.Line(Position, whisker, color);
}
}
}
/// <summary>
/// draw the current velocity
/// </summary>
/// <param name="prim"></param>
/// <param name="color"></param>
public void DrawVelocity(IPrimitive prim, Color color)
{
prim.Line(Position, Position + Velocity, color);
}
public void DrawSpeedForce(IPrimitive prim, Color color)
{
//draw a circle at the MaxForce line
//prim.Circle(Position, MaxForce, color);
//draw the speed force being applied
prim.Line(Position, Position + _speedForce, color);
}
#endregion //Drawing
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
namespace ServiceStack.Text.Common
{
public static class DeserializeListWithElements<TSerializer>
where TSerializer : ITypeSerializer
{
internal static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
private static Dictionary<Type, ParseListDelegate> ParseDelegateCache
= new Dictionary<Type, ParseListDelegate>();
public delegate object ParseListDelegate(ReadOnlySpan<char> value, Type createListType, ParseStringSpanDelegate parseFn);
public static Func<string, Type, ParseStringDelegate, object> GetListTypeParseFn(
Type createListType, Type elementType, ParseStringDelegate parseFn)
{
var func = GetListTypeParseStringSpanFn(createListType, elementType, v => parseFn(v.ToString()));
return (s, t, d) => func(s.AsSpan(), t, v => d(v.ToString()));
}
private static readonly Type[] signature = {typeof(ReadOnlySpan<char>), typeof(Type), typeof(ParseStringSpanDelegate)};
public static ParseListDelegate GetListTypeParseStringSpanFn(
Type createListType, Type elementType, ParseStringSpanDelegate parseFn)
{
if (ParseDelegateCache.TryGetValue(elementType, out var parseDelegate))
return parseDelegate.Invoke;
var genericType = typeof(DeserializeListWithElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetStaticMethod("ParseGenericList", signature);
parseDelegate = (ParseListDelegate)mi.MakeDelegate(typeof(ParseListDelegate));
Dictionary<Type, ParseListDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseListDelegate>(ParseDelegateCache) { [elementType] = parseDelegate };
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseDelegate.Invoke;
}
public static ReadOnlySpan<char> StripList(ReadOnlySpan<char> value)
{
if (value.IsNullOrEmpty())
return default;
value = value.Trim();
const int startQuotePos = 1;
const int endQuotePos = 2;
var ret = value[0] == JsWriter.ListStartChar
? value.Slice(startQuotePos, value.Length - endQuotePos)
: value;
var val = ret.AdvancePastWhitespace();
if (val.Length == 0)
return TypeConstants.EmptyStringSpan;
return val;
}
public static List<string> ParseStringList(string value)
{
return ParseStringList(value.AsSpan());
}
public static List<string> ParseStringList(ReadOnlySpan<char> value)
{
if ((value = StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : new List<string>();
var to = new List<string>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
var listValue = Serializer.UnescapeString(elementValue);
to.Add(listValue.Value());
if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength)
{
// If we ate a separator and we are at the end of the value,
// it means the last element is empty => add default
to.Add(null);
}
}
return to;
}
public static List<int> ParseIntList(string value) => ParseIntList(value.AsSpan());
public static List<int> ParseIntList(ReadOnlySpan<char> value)
{
if ((value = StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : new List<int>();
var to = new List<int>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
to.Add(MemoryProvider.Instance.ParseInt32(elementValue));
Serializer.EatItemSeperatorOrMapEndChar(value, ref i);
}
return to;
}
public static List<byte> ParseByteList(string value) => ParseByteList(value.AsSpan());
public static List<byte> ParseByteList(ReadOnlySpan<char> value)
{
if ((value = StripList(value)).IsNullOrEmpty())
return value.IsEmpty ? null : new List<byte>();
var to = new List<byte>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
to.Add(MemoryProvider.Instance.ParseByte(elementValue));
Serializer.EatItemSeperatorOrMapEndChar(value, ref i);
}
return to;
}
}
public static class DeserializeListWithElements<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
public static ICollection<T> ParseGenericList(string value, Type createListType, ParseStringDelegate parseFn)
{
return ParseGenericList(value.AsSpan(), createListType, v => parseFn(v.ToString()));
}
public static ICollection<T> ParseGenericList(ReadOnlySpan<char> value, Type createListType, ParseStringSpanDelegate parseFn)
{
var isReadOnly = createListType != null && (createListType.IsGenericType && createListType.GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>));
var to = (createListType == null || isReadOnly)
? new List<T>()
: (ICollection<T>)createListType.CreateInstance();
var objSerializer = Json.JsonTypeSerializer.Instance.ObjectDeserializer;
if (to is List<object> && objSerializer != null && typeof(TSerializer) == typeof(Json.JsonTypeSerializer))
return (ICollection<T>)objSerializer(value);
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)).IsEmpty)
return null;
if (value.IsNullOrEmpty())
return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to;
var tryToParseItemsAsPrimitiveTypes =
typeof(T) == typeof(object) && JsConfig.TryToParsePrimitiveTypeValues;
if (!value.IsNullOrEmpty())
{
var valueLength = value.Length;
var i = 0;
Serializer.EatWhitespace(value, ref i);
if (i < valueLength && value[i] == JsWriter.MapStartChar)
{
do
{
var itemValue = Serializer.EatTypeValue(value, ref i);
if (!itemValue.IsEmpty)
{
to.Add((T)parseFn(itemValue));
}
else
{
to.Add(default);
}
Serializer.EatWhitespace(value, ref i);
} while (++i < value.Length);
}
else
{
while (i < valueLength)
{
var startIndex = i;
var elementValue = Serializer.EatValue(value, ref i);
var listValue = elementValue;
var isEmpty = listValue.IsNullOrEmpty();
if (!isEmpty)
{
if (tryToParseItemsAsPrimitiveTypes)
{
Serializer.EatWhitespace(value, ref startIndex);
to.Add((T)DeserializeType<TSerializer>.ParsePrimitive(elementValue.Value(), value[startIndex]));
}
else
{
to.Add((T)parseFn(elementValue));
}
}
if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength)
{
// If we ate a separator and we are at the end of the value,
// it means the last element is empty => add default
to.Add(default);
continue;
}
if (isEmpty)
to.Add(default);
}
}
}
//TODO: 8-10-2011 -- this CreateInstance call should probably be moved over to ReflectionExtensions,
//but not sure how you'd like to go about caching constructors with parameters -- I would probably build a NewExpression, .Compile to a LambdaExpression and cache
return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to;
}
}
public static class DeserializeList<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ParseStringSpanDelegate CacheFn;
static DeserializeList()
{
CacheFn = GetParseStringSpanFn();
}
public static ParseStringDelegate Parse => v => CacheFn(v.AsSpan());
public static ParseStringSpanDelegate ParseStringSpan => CacheFn;
public static ParseStringDelegate GetParseFn() => v => GetParseStringSpanFn()(v.AsSpan());
public static ParseStringSpanDelegate GetParseStringSpanFn()
{
var listInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IList<>));
if (listInterface == null)
throw new ArgumentException($"Type {typeof(T).FullName} is not of type IList<>");
//optimized access for regularly used types
if (typeof(T) == typeof(List<string>))
return DeserializeListWithElements<TSerializer>.ParseStringList;
if (typeof(T) == typeof(List<int>))
return DeserializeListWithElements<TSerializer>.ParseIntList;
var elementType = listInterface.GetGenericArguments()[0];
var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseStringSpanFn(elementType);
if (supportedTypeParseMethod != null)
{
var createListType = typeof(T).HasAnyTypeDefinitionsOf(typeof(List<>), typeof(IList<>))
? null : typeof(T);
var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseStringSpanFn(createListType, elementType, supportedTypeParseMethod);
return value => parseFn(value, createListType, supportedTypeParseMethod);
}
return null;
}
}
internal static class DeserializeEnumerable<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ParseStringSpanDelegate CacheFn;
static DeserializeEnumerable()
{
CacheFn = GetParseStringSpanFn();
}
public static ParseStringDelegate Parse => v => CacheFn(v.AsSpan());
public static ParseStringSpanDelegate ParseStringSpan => CacheFn;
public static ParseStringDelegate GetParseFn() => v => GetParseStringSpanFn()(v.AsSpan());
public static ParseStringSpanDelegate GetParseStringSpanFn()
{
var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>));
if (enumerableInterface == null)
throw new ArgumentException($"Type {typeof(T).FullName} is not of type IEnumerable<>");
//optimized access for regularly used types
if (typeof(T) == typeof(IEnumerable<string>))
return DeserializeListWithElements<TSerializer>.ParseStringList;
if (typeof(T) == typeof(IEnumerable<int>))
return DeserializeListWithElements<TSerializer>.ParseIntList;
var elementType = enumerableInterface.GetGenericArguments()[0];
var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseStringSpanFn(elementType);
if (supportedTypeParseMethod != null)
{
const Type createListTypeWithNull = null; //Use conversions outside this class. see: Queue
var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseStringSpanFn(
createListTypeWithNull, elementType, supportedTypeParseMethod);
return value => parseFn(value, createListTypeWithNull, supportedTypeParseMethod);
}
return null;
}
}
}
| |
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine.UI;
using UnityEngine.Assertions;
namespace UnityPlatformer {
/// <summary>
/// List of part a character can have, maybe needed to handle
/// how to reach to certain Damages
/// </summary>
public enum CharacterPart {
None = 0,
FakeBody = 1,
Body = 1 << 2,
RightHand = 1 << 3,
LeftHand = 1 << 4,
RightFoot = 1 << 5,
LeftFoot = 1 << 6,
Head = 1 << 7,
Weapon = 1 << 8,
Projectile = 1 << 9,
}
/// <summary>
/// Type of HitBoxe, what it do
/// </summary>
public enum HitBoxType {
DealDamage,
RecieveDamage,
EnterAreas
}
/// <summary>
/// HitBoxes are triggers that Deal/Revieve Damage or enter areas(tile)\n
/// DealDamage require Damage MonoBehaviour\n
/// EnterAreas require Collider2D to be BoxCollider2D
/// </summary>
//[RequireComponent (typeof (Rigidbody2D))] // only for DealDamage...
[RequireComponent (typeof (Collider2D))]
public class HitBox : MonoBehaviour {
/// <summary>
/// Character part this HitBox belong
/// </summary>
public CharacterPart part;
/// <summary>
/// Flag
/// </summary>
public bool useGlobalMask = true;
/// <summary>
/// Who can deal damage to me?
///
/// Only used when type=HitBoxType.RecieveDamage.
/// </summary>
[DisableIf("useGlobalMask")]
public LayerMask collisionMask;
/// <summary>
/// HitBox owner
/// </summary>
[Comment("Who am I?")]
public CharacterHealth owner;
/// <summary>
/// HitBoxType
/// </summary>
public HitBoxType type = HitBoxType.DealDamage;
/// <summary>
/// Can i deal damage to myself?
/// </summary>
public bool dealDamageToSelf = false;
/// <summary>
/// Combo to check character state
/// </summary>
public CharacterStatesCheck characterState;
/// <summary>
/// Damage info, only used type=HitBoxType.DealDamage.
/// </summary>
internal Damage damage;
/// <summary>
/// check missconfigurations and initialize
/// </summary>
public void Start() {
Assert.IsNotNull(owner, "CharacterHealth owner is required at " + gameObject.GetFullName());
damage = GetComponent<Damage> ();
if (type == HitBoxType.DealDamage) {
Assert.IsNotNull(damage, "Missing MonoBehaviour Damage at " + gameObject.GetFullName() + " because typem is DealDamage");
}
if (type == HitBoxType.EnterAreas) {
BoxCollider2D box2d = GetComponent<BoxCollider2D>();
Assert.IsNotNull(box2d, "Missing MonoBehaviour BoxCollider2D at " + gameObject.GetFullName() + " because typem is EnterAreas");
}
if (type == HitBoxType.EnterAreas) {
if (owner.character.enterAreas != null && owner.character.enterAreas != this ) {
Debug.LogWarning("Only one EnterAreas HitBox is allowed!");
}
owner.character.enterAreas = this;
}
Utils.KinematicTrigger(gameObject);
}
#if UNITY_EDITOR
/// <summary>
/// Set layer to Configuration.ropesMask
/// </summary>
public void Reset() {
if (characterState == null) {
characterState = new CharacterStatesCheck();
}
gameObject.layer = Configuration.instance.hitBoxesMask;
owner = GetComponentInParent<CharacterHealth>();
Utils.KinematicTrigger(gameObject);
}
#endif
/// <summary>
/// Return if the HitBox is disabled base on enabledOnStates
/// </summary>
public bool IsDisabled() {
return !characterState.ValidStates(owner.character);
}
#if UNITY_EDITOR
/// <summary>
/// Draw in the Editor mode
/// </summary>
[DrawGizmo(GizmoType.InSelectionHierarchy | GizmoType.NotInSelectionHierarchy)]
void OnDrawGizmos() {
switch(type) {
case HitBoxType.DealDamage:
Gizmos.color = Color.red;
break;
case HitBoxType.RecieveDamage:
Gizmos.color = Color.yellow;
break;
case HitBoxType.EnterAreas:
Gizmos.color = Color.green;
break;
}
Utils.DrawCollider2D(gameObject);
//Handles.Label(transform.position + new Vector3(-box.size.x * 0.5f, box.size.y * 0.5f, 0), "HitBox: " + type);
}
#endif
/// <summary>
/// Get final collision mask, taking into consideration useGlobalMask flags
/// </summary>
public LayerMask GetCollisionMask() {
if (useGlobalMask) {
switch(type) {
case HitBoxType.DealDamage:
return Configuration.instance.dealDamageMask;
case HitBoxType.RecieveDamage:
return Configuration.instance.recieveDamageMask;
case HitBoxType.EnterAreas:
return Configuration.instance.enterAreasMask;
}
}
return collisionMask;
}
/// <summary>
/// I'm a DealDamage, o is RecieveDamage, then Deal Damage to it's owner!
/// </summary>
public void OnTriggerEnter2D(Collider2D o) {
if (type == HitBoxType.DealDamage) {
// source disabled?
if (IsDisabled()) {
Log.Debug("{0} cannot deal damage it's disabled", this.gameObject.GetFullName());
return;
}
//Debug.LogFormat("me {0} of {1} collide with {2}@{3}", name, owner, o.gameObject, o.gameObject.layer);
var hitbox = o.gameObject.GetComponent<HitBox> ();
Log.Silly("o is a HitBox? {0} at {0}", hitbox, o.gameObject.GetFullName());
if (hitbox != null && hitbox.type == HitBoxType.RecieveDamage) {
Log.Debug("Collide {0} with {1}", gameObject.GetFullName(), hitbox.gameObject.GetFullName());
// target disabled?
if (hitbox.IsDisabled()) {
Log.Debug("{0} cannot recieve damage it's disabled", o.gameObject.GetFullName());
return;
}
// can I deal damage to this HitBox?
// check layer
if (hitbox.GetCollisionMask().Contains(gameObject.layer)) {
Log.Silly("compatible layers");
// check we not the same, or i can damage to myself at lest
if (dealDamageToSelf || (!dealDamageToSelf && hitbox.owner != damage.causer)) {
Log.Debug("Damage to {0} with {1}", hitbox.owner.gameObject.GetFullName(), damage);
hitbox.owner.Damage(damage);
}
} else {
Log.Silly("incompatible layers {0} vs {1}",
string.Join(",", hitbox.GetCollisionMask().MaskToNames()),
LayerMask.LayerToName(gameObject.layer)
);
}
}
}
}
}
}
| |
namespace android.database
{
[global::MonoJavaBridge.JavaInterface(typeof(global::android.database.Cursor_))]
public partial interface Cursor : global::MonoJavaBridge.IJavaObject
{
short getShort(int arg0);
int getInt(int arg0);
long getLong(int arg0);
float getFloat(int arg0);
double getDouble(int arg0);
void close();
global::java.lang.String getString(int arg0);
bool isFirst();
bool isClosed();
int getPosition();
global::android.os.Bundle getExtras();
void registerContentObserver(android.database.ContentObserver arg0);
void unregisterContentObserver(android.database.ContentObserver arg0);
int getCount();
bool move(int arg0);
bool moveToPosition(int arg0);
bool moveToFirst();
bool moveToLast();
bool moveToNext();
bool moveToPrevious();
bool isLast();
bool isBeforeFirst();
bool isAfterLast();
int getColumnIndex(java.lang.String arg0);
int getColumnIndexOrThrow(java.lang.String arg0);
global::java.lang.String getColumnName(int arg0);
global::java.lang.String[] getColumnNames();
int getColumnCount();
byte[] getBlob(int arg0);
void copyStringToBuffer(int arg0, android.database.CharArrayBuffer arg1);
bool isNull(int arg0);
void deactivate();
bool requery();
void registerDataSetObserver(android.database.DataSetObserver arg0);
void unregisterDataSetObserver(android.database.DataSetObserver arg0);
void setNotificationUri(android.content.ContentResolver arg0, android.net.Uri arg1);
bool getWantsAllOnMoveCalls();
global::android.os.Bundle respond(android.os.Bundle arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.database.Cursor))]
internal sealed partial class Cursor_ : java.lang.Object, Cursor
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Cursor_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
short android.database.Cursor.getShort(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::android.database.Cursor_.staticClass, "getShort", "(I)S", ref global::android.database.Cursor_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
int android.database.Cursor.getInt(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getInt", "(I)I", ref global::android.database.Cursor_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
long android.database.Cursor.getLong(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.database.Cursor_.staticClass, "getLong", "(I)J", ref global::android.database.Cursor_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
float android.database.Cursor.getFloat(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.database.Cursor_.staticClass, "getFloat", "(I)F", ref global::android.database.Cursor_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
double android.database.Cursor.getDouble(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.database.Cursor_.staticClass, "getDouble", "(I)D", ref global::android.database.Cursor_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
void android.database.Cursor.close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "close", "()V", ref global::android.database.Cursor_._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
global::java.lang.String android.database.Cursor.getString(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.database.Cursor_.staticClass, "getString", "(I)Ljava/lang/String;", ref global::android.database.Cursor_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m7;
bool android.database.Cursor.isFirst()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isFirst", "()Z", ref global::android.database.Cursor_._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
bool android.database.Cursor.isClosed()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isClosed", "()Z", ref global::android.database.Cursor_._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
int android.database.Cursor.getPosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getPosition", "()I", ref global::android.database.Cursor_._m9);
}
private static global::MonoJavaBridge.MethodId _m10;
global::android.os.Bundle android.database.Cursor.getExtras()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.database.Cursor_.staticClass, "getExtras", "()Landroid/os/Bundle;", ref global::android.database.Cursor_._m10) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m11;
void android.database.Cursor.registerContentObserver(android.database.ContentObserver arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "registerContentObserver", "(Landroid/database/ContentObserver;)V", ref global::android.database.Cursor_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
void android.database.Cursor.unregisterContentObserver(android.database.ContentObserver arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "unregisterContentObserver", "(Landroid/database/ContentObserver;)V", ref global::android.database.Cursor_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
int android.database.Cursor.getCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getCount", "()I", ref global::android.database.Cursor_._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
bool android.database.Cursor.move(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "move", "(I)Z", ref global::android.database.Cursor_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
bool android.database.Cursor.moveToPosition(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "moveToPosition", "(I)Z", ref global::android.database.Cursor_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
bool android.database.Cursor.moveToFirst()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "moveToFirst", "()Z", ref global::android.database.Cursor_._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
bool android.database.Cursor.moveToLast()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "moveToLast", "()Z", ref global::android.database.Cursor_._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
bool android.database.Cursor.moveToNext()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "moveToNext", "()Z", ref global::android.database.Cursor_._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
bool android.database.Cursor.moveToPrevious()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "moveToPrevious", "()Z", ref global::android.database.Cursor_._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
bool android.database.Cursor.isLast()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isLast", "()Z", ref global::android.database.Cursor_._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
bool android.database.Cursor.isBeforeFirst()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isBeforeFirst", "()Z", ref global::android.database.Cursor_._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
bool android.database.Cursor.isAfterLast()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isAfterLast", "()Z", ref global::android.database.Cursor_._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
int android.database.Cursor.getColumnIndex(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getColumnIndex", "(Ljava/lang/String;)I", ref global::android.database.Cursor_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
int android.database.Cursor.getColumnIndexOrThrow(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getColumnIndexOrThrow", "(Ljava/lang/String;)I", ref global::android.database.Cursor_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
global::java.lang.String android.database.Cursor.getColumnName(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.database.Cursor_.staticClass, "getColumnName", "(I)Ljava/lang/String;", ref global::android.database.Cursor_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m26;
global::java.lang.String[] android.database.Cursor.getColumnNames()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::android.database.Cursor_.staticClass, "getColumnNames", "()[Ljava/lang/String;", ref global::android.database.Cursor_._m26) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m27;
int android.database.Cursor.getColumnCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.Cursor_.staticClass, "getColumnCount", "()I", ref global::android.database.Cursor_._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
byte[] android.database.Cursor.getBlob(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.database.Cursor_.staticClass, "getBlob", "(I)[B", ref global::android.database.Cursor_._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as byte[];
}
private static global::MonoJavaBridge.MethodId _m29;
void android.database.Cursor.copyStringToBuffer(int arg0, android.database.CharArrayBuffer arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "copyStringToBuffer", "(ILandroid/database/CharArrayBuffer;)V", ref global::android.database.Cursor_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m30;
bool android.database.Cursor.isNull(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "isNull", "(I)Z", ref global::android.database.Cursor_._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
void android.database.Cursor.deactivate()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "deactivate", "()V", ref global::android.database.Cursor_._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
bool android.database.Cursor.requery()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "requery", "()Z", ref global::android.database.Cursor_._m32);
}
private static global::MonoJavaBridge.MethodId _m33;
void android.database.Cursor.registerDataSetObserver(android.database.DataSetObserver arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V", ref global::android.database.Cursor_._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
void android.database.Cursor.unregisterDataSetObserver(android.database.DataSetObserver arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V", ref global::android.database.Cursor_._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
void android.database.Cursor.setNotificationUri(android.content.ContentResolver arg0, android.net.Uri arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.Cursor_.staticClass, "setNotificationUri", "(Landroid/content/ContentResolver;Landroid/net/Uri;)V", ref global::android.database.Cursor_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m36;
bool android.database.Cursor.getWantsAllOnMoveCalls()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.Cursor_.staticClass, "getWantsAllOnMoveCalls", "()Z", ref global::android.database.Cursor_._m36);
}
private static global::MonoJavaBridge.MethodId _m37;
global::android.os.Bundle android.database.Cursor.respond(android.os.Bundle arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.database.Cursor_.staticClass, "respond", "(Landroid/os/Bundle;)Landroid/os/Bundle;", ref global::android.database.Cursor_._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Bundle;
}
static Cursor_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.database.Cursor_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/Cursor"));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Commencement.Core.Domain;
using Commencement.Tests.Core;
using Commencement.Tests.Core.Extensions;
using Commencement.Tests.Core.Helpers;
using FluentNHibernate.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
using UCDArch.Testing;
namespace Commencement.Tests.Repositories
{
/// <summary>
/// Entity Name: MajorCode
/// LookupFieldName: Name
/// </summary>
[TestClass]
public class MajorCodeRepositoryTests : AbstractRepositoryTests<MajorCode, string, MajorCodeMap>
{
/// <summary>
/// Gets or sets the MajorCode repository.
/// </summary>
/// <value>The MajorCode repository.</value>
public IRepositoryWithTypedId<MajorCode, string > MajorCodeRepository { get; set; }
public IRepositoryWithTypedId<College, string> CollegeRepository { get; set; }
#region Init and Overrides
/// <summary>
/// Initializes a new instance of the <see cref="MajorCodeRepositoryTests"/> class.
/// </summary>
public MajorCodeRepositoryTests()
{
MajorCodeRepository = new RepositoryWithTypedId<MajorCode, string>();
CollegeRepository = new RepositoryWithTypedId<College, string>();
}
/// <summary>
/// Gets the valid entity of type T
/// </summary>
/// <param name="counter">The counter.</param>
/// <returns>A valid entity of type T</returns>
protected override MajorCode GetValid(int? counter)
{
var rtValue = CreateValidEntities.MajorCode(counter);
var notNullCounter = "99";
if (counter != null)
{
notNullCounter = ((int) counter).ToString();
}
rtValue.SetIdTo(notNullCounter);
return rtValue;
}
/// <summary>
/// A Query which will return a single record
/// </summary>
/// <param name="numberAtEnd"></param>
/// <returns></returns>
protected override IQueryable<MajorCode> GetQuery(int numberAtEnd)
{
return MajorCodeRepository.Queryable.Where(a => a.Name.EndsWith(numberAtEnd.ToString()));
}
/// <summary>
/// A way to compare the entities that were read.
/// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
/// </summary>
/// <param name="entity"></param>
/// <param name="counter"></param>
protected override void FoundEntityComparison(MajorCode entity, int counter)
{
Assert.AreEqual("Name" + counter, entity.Name);
}
/// <summary>
/// Updates , compares, restores.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="action">The action.</param>
protected override void UpdateUtility(MajorCode entity, ARTAction action)
{
const string updateValue = "Updated";
switch (action)
{
case ARTAction.Compare:
Assert.AreEqual(updateValue, entity.Name);
break;
case ARTAction.Restore:
entity.Name = RestoreValue;
break;
case ARTAction.Update:
RestoreValue = entity.Name;
entity.Name = updateValue;
break;
}
}
/// <summary>
/// Loads the data.
/// </summary>
protected override void LoadData()
{
MajorCodeRepository.DbContext.BeginTransaction();
LoadRecords(5);
MajorCodeRepository.DbContext.CommitTransaction();
}
#endregion Init and Overrides
#region Name Tests
#region Valid Tests
/// <summary>
/// Tests the Name with null value saves.
/// </summary>
[TestMethod]
public void TestNameWithNullValueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.Name = null;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Name with empty string saves.
/// </summary>
[TestMethod]
public void TestNameWithEmptyStringSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.Name = string.Empty;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Name with one space saves.
/// </summary>
[TestMethod]
public void TestNameWithOneSpaceSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.Name = " ";
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Name with one character saves.
/// </summary>
[TestMethod]
public void TestNameWithOneCharacterSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.Name = "x";
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the Name with long value saves.
/// </summary>
[TestMethod]
public void TestNameWithLongValueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.Name = "x".RepeatTimes(999);
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, majorCode.Name.Length);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion Name Tests
#region DisciplineCode Tests
#region Valid Tests
/// <summary>
/// Tests the DisciplineCode with null value saves.
/// </summary>
[TestMethod]
public void TestDisciplineCodeWithNullValueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.DisciplineCode = null;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the DisciplineCode with empty string saves.
/// </summary>
[TestMethod]
public void TestDisciplineCodeWithEmptyStringSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.DisciplineCode = string.Empty;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the DisciplineCode with one space saves.
/// </summary>
[TestMethod]
public void TestDisciplineCodeWithOneSpaceSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.DisciplineCode = " ";
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the DisciplineCode with one character saves.
/// </summary>
[TestMethod]
public void TestDisciplineCodeWithOneCharacterSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.DisciplineCode = "x";
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the DisciplineCode with long value saves.
/// </summary>
[TestMethod]
public void TestDisciplineCodeWithLongValueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.DisciplineCode = "x".RepeatTimes(999);
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.AreEqual(999, majorCode.DisciplineCode.Length);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion DisciplineCode Tests
#region College Tests
#region Invalid Tests
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestCollegeWithNewValueDoesNotSave()
{
MajorCode majorCode;
try
{
#region Arrange
LoadColleges(3);
majorCode = GetValid(9);
majorCode.College = CreateValidEntities.College(99);
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
#region Assert
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.College, Entity: Commencement.Core.Domain.College", ex.Message);
throw;
#endregion Assert
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestCollegeWithNullValueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.College = null;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(majorCode.College);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
[TestMethod]
public void TestCollegeWithExistingValueSaves()
{
#region Arrange
LoadColleges(3);
var majorCode = GetValid(9);
majorCode.College = CollegeRepository.GetById("2");
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNotNull(majorCode.College);
Assert.AreEqual("Name2", majorCode.College.Name);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
#endregion Valid Tests
#endregion College Tests
#region ConsolidationMajor Tests
#region Invalid Tests
/// <summary>
/// Tests the ConsolidationMajor with A value of new Value does not save.
/// </summary>
[TestMethod]
[ExpectedException(typeof(NHibernate.TransientObjectException))]
public void TestConsolidationMajorWithAValueOfNewValueDoesNotSave()
{
MajorCode majorCode = null;
try
{
#region Arrange
majorCode = GetValid(9);
majorCode.ConsolidationMajor = CreateValidEntities.MajorCode(15);
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
}
catch (Exception ex)
{
Assert.IsNotNull(majorCode);
Assert.IsNotNull(ex);
Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: Commencement.Core.Domain.MajorCode, Entity: Commencement.Core.Domain.MajorCode", ex.Message);
throw;
}
}
#endregion Invalid Tests
#region Valid Tests
[TestMethod]
public void TestMajorCodeWithNullConsolidationMajorSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.ConsolidationMajor = null;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(majorCode.ConsolidationMajor);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
[TestMethod]
public void TestMajorCodeWithExistingConsolidationMajorSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.ConsolidationMajor = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(majorCode.ConsolidationMajor);
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
var saveId = majorCode.Id;
#endregion Act
#region Assert
Assert.IsNotNull(majorCode.ConsolidationMajor);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
NHibernateSessionManager.Instance.GetSession().Evict(majorCode);
majorCode = MajorCodeRepository.GetNullableById(saveId);
Assert.IsNotNull(majorCode.ConsolidationMajor);
#endregion Assert
}
#endregion Valid Tests
#region Cascade Tests
[TestMethod]
public void TestDeleteMajorCodeDoesNotCascadeToOtherMajorCode()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.ConsolidationMajor = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(majorCode.ConsolidationMajor);
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
var saveId = majorCode.Id;
#endregion Arrange
#region Act
NHibernateSessionManager.Instance.GetSession().Evict(majorCode);
majorCode = MajorCodeRepository.GetNullableById(saveId);
Assert.IsNotNull(majorCode);
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.Remove(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsNull(MajorCodeRepository.GetNullableById(saveId));
Assert.IsNotNull(MajorCodeRepository.GetNullableById("2"));
#endregion Assert
}
#endregion Cascade Tests
#endregion ConsolidationMajor Tests
#region IsActive Tests
/// <summary>
/// Tests the IsActive is false saves.
/// </summary>
[TestMethod]
public void TestIsActiveIsFalseSaves()
{
#region Arrange
MajorCode majorCode = GetValid(9);
majorCode.IsActive = false;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsFalse(majorCode.IsActive);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
/// <summary>
/// Tests the IsActive is true saves.
/// </summary>
[TestMethod]
public void TestIsActiveIsTrueSaves()
{
#region Arrange
var majorCode = GetValid(9);
majorCode.IsActive = true;
#endregion Arrange
#region Act
MajorCodeRepository.DbContext.BeginTransaction();
MajorCodeRepository.EnsurePersistent(majorCode);
MajorCodeRepository.DbContext.CommitTransaction();
#endregion Act
#region Assert
Assert.IsTrue(majorCode.IsActive);
Assert.IsFalse(majorCode.IsTransient());
Assert.IsTrue(majorCode.IsValid());
#endregion Assert
}
#endregion IsActive Tests
#region Major Tests
[TestMethod]
public void TestMajorReturnsThisMajorCodeWhenConsolidationMajorIsNull()
{
#region Arrange
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = null;
#endregion Arrange
#region Assert
Assert.AreEqual("3", record.Major.Id);
Assert.AreEqual("Name3", record.Major.Name);
#endregion Assert
}
[TestMethod]
public void TestMajorReturnsOtherMajorCodeWhenConsolidationMajorIsNotNull()
{
#region Arrange
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(record.ConsolidationMajor);
#endregion Arrange
#region Assert
Assert.AreEqual("2", record.Major.Id);
Assert.AreEqual("Name2", record.Major.Name);
#endregion Assert
}
#endregion Major Tests
#region MajorName Tests
[TestMethod]
public void TestMajorNameReturnsExpectedValue1()
{
#region Arrange
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = null;
#endregion Arrange
#region Assert
Assert.AreEqual("3", record.Major.Id);
Assert.AreEqual("Name3", record.MajorName);
#endregion Assert
}
[TestMethod]
public void TestMajorNameReturnsExpectedValue2()
{
#region Arrange
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(record.ConsolidationMajor);
#endregion Arrange
#region Assert
Assert.AreEqual("2", record.Major.Id);
Assert.AreEqual("Name2", record.MajorName);
#endregion Assert
}
#endregion MajorName Tests
#region MajorCollege Tests
[TestMethod]
public void TestMajorCollegeReturnsExpectedValue1()
{
#region Arrange
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = null;
record.College = CreateValidEntities.College(16);
#endregion Arrange
#region Assert
Assert.AreEqual("3", record.Major.Id);
Assert.AreEqual("Name16", record.MajorCollege.Name);
#endregion Assert
}
[TestMethod]
public void TestMajorCollegeReturnsExpectedValue2()
{
#region Arrange
Repository.OfType<College>().DbContext.BeginTransaction();
LoadColleges(3);
var toUpdate = MajorCodeRepository.GetNullableById("2");
toUpdate.College = Repository.OfType<College>().Queryable.First();
Repository.OfType<MajorCode>().EnsurePersistent(toUpdate);
Repository.OfType<College>().DbContext.CommitTransaction();
NHibernateSessionManager.Instance.GetSession().Evict(toUpdate);
var record = MajorCodeRepository.GetNullableById("3");
Assert.IsNotNull(record);
record.ConsolidationMajor = MajorCodeRepository.GetNullableById("2");
Assert.IsNotNull(record.ConsolidationMajor);
record.College = CreateValidEntities.College(16);
#endregion Arrange
#region Assert
Assert.AreEqual("2", record.Major.Id);
Assert.AreEqual("Name1", record.MajorCollege.Name);
#endregion Assert
}
#endregion MajorCollege Tests
#region Fluent Mapping Tests
[TestMethod]
public void TestCanCorrectlyMapMajorCode1()
{
#region Arrange
var session = NHibernateSessionManager.Instance.GetSession();
LoadColleges(3);
var college = CollegeRepository.GetById("2");
Assert.IsNotNull(college);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<MajorCode>(session, new MajorCodeEqualityComparer())
.CheckProperty(c => c.Id, "APRF")
.CheckProperty(c => c.College, college)
.CheckProperty(c => c.DisciplineCode, "ENVSC")
.CheckProperty(c => c.Name, "Pre Forestry (C.W.0.) Program")
.CheckProperty(c => c.IsActive, true)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapMajorCode1A()
{
#region Arrange
var session = NHibernateSessionManager.Instance.GetSession();
LoadColleges(3);
var college = CollegeRepository.GetById("2");
Assert.IsNotNull(college);
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<MajorCode>(session, new MajorCodeEqualityComparer())
.CheckProperty(c => c.Id, "APRF")
.CheckProperty(c => c.College, college)
.CheckProperty(c => c.DisciplineCode, "ENVSC")
.CheckProperty(c => c.Name, "Pre Forestry (C.W.0.) Program")
.CheckProperty(c => c.IsActive, false)
.VerifyTheMappings();
#endregion Act/Assert
}
[TestMethod]
public void TestCanCorrectlyMapMajorCode2()
{
#region Arrange
var session = NHibernateSessionManager.Instance.GetSession();
LoadColleges(3);
var college = CollegeRepository.GetById("2");
Assert.IsNotNull(college);
var majorCode = MajorCodeRepository.Queryable.First();
#endregion Arrange
#region Act/Assert
new PersistenceSpecification<MajorCode>(session)
.CheckProperty(c => c.Id, "APRF")
.CheckReference(c => c.College, college)
.CheckProperty(c => c.DisciplineCode, "ENVSC")
.CheckProperty(c => c.Name, "Pre Forestry (C.W.0.) Program")
.CheckReference(c=> c.ConsolidationMajor, majorCode )
.VerifyTheMappings();
#endregion Act/Assert
}
public class MajorCodeEqualityComparer : IEqualityComparer
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object to compare.</param><param name="y">The second object to compare.</param><exception cref="T:System.ArgumentException"><paramref name="x"/> and <paramref name="y"/> are of different types and neither one can handle comparisons with the other.</exception>
bool IEqualityComparer.Equals(object x, object y)
{
if (x is College && y is College)
{
if (((College)x).Name == ((College)y).Name)
{
return true;
}
return false;
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
throw new NotImplementedException();
}
}
#endregion Fluent Mapping Tests
#region Reflection of Database.
/// <summary>
/// Tests all fields in the database have been tested.
/// If this fails and no other tests, it means that a field has been added which has not been tested above.
/// </summary>
[TestMethod]
public void TestAllFieldsInTheDatabaseHaveBeenTested()
{
#region Arrange
var expectedFields = new List<NameAndType>();
expectedFields.Add(new NameAndType("College", "Commencement.Core.Domain.College", new List<string>()));
expectedFields.Add(new NameAndType("ConsolidationMajor", "Commencement.Core.Domain.MajorCode", new List<string>()));
expectedFields.Add(new NameAndType("DisciplineCode", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("Id", "System.String", new List<string>
{
"[Newtonsoft.Json.JsonPropertyAttribute()]",
"[System.Xml.Serialization.XmlIgnoreAttribute()]"
}));
expectedFields.Add(new NameAndType("IsActive", "System.Boolean", new List<string>()));
expectedFields.Add(new NameAndType("Major", "Commencement.Core.Domain.MajorCode", new List<string>()));
expectedFields.Add(new NameAndType("MajorCollege", "Commencement.Core.Domain.College", new List<string>()));
expectedFields.Add(new NameAndType("MajorName", "System.String", new List<string>()));
expectedFields.Add(new NameAndType("Name", "System.String", new List<string>()));
#endregion Arrange
AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(MajorCode));
}
#endregion Reflection of Database.
}
}
| |
using System;
using LanguageExt;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using LanguageExt.DataTypes.Serialisation;
using LanguageExt.TypeClasses;
using LanguageExt.ClassInstances;
using LanguageExt.Common;
using static LanguageExt.Prelude;
namespace LanguageExt
{
public static partial class TryOptionAsyncT
{
static TryOptionAsync<A> ToTry<A>(Func<Task<OptionalResult<A>>> ma) =>
new TryOptionAsync<A>(ma);
//
// Collections
//
public static TryOptionAsync<Arr<B>> Traverse<A, B>(this Arr<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Arr<B>>> Go(Arr<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Arr<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Arr<B>>.None
: new OptionalResult<Arr<B>>(new Arr<B>(rb.Map(d => d.Value.Value)));
}
}
public static TryOptionAsync<HashSet<B>> Traverse<A, B>(this HashSet<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<HashSet<B>>> Go(HashSet<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted)
? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<HashSet<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<HashSet<B>>.None
: new OptionalResult<HashSet<B>>(new HashSet<B>(rb.Map(d => d.Value.Value)));
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static TryOptionAsync<IEnumerable<B>> Traverse<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, f);
public static TryOptionAsync<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<IEnumerable<B>>> Go(IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = new List<B>();
foreach (var a in ma)
{
var mb = await a.Try();
if (mb.IsFaulted) return new OptionalResult<IEnumerable<B>>(mb.Exception);
if (mb.IsNone) return OptionalResult<IEnumerable<B>>.None;
rb.Add(f(mb.Value.Value));
}
return new OptionalResult<IEnumerable<B>>(rb);
};
}
public static TryOptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f);
public static TryOptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryOptionAsync<A>> ma, int windowSize, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<IEnumerable<B>>> Go(IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity);
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<IEnumerable<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<IEnumerable<B>>.None
: new OptionalResult<IEnumerable<B>>(rb.Map(d => d.Value.Value).ToArray());
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static TryOptionAsync<IEnumerable<A>> Sequence<A>(this IEnumerable<TryOptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static TryOptionAsync<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<TryOptionAsync<A>> ma) =>
TraverseSerial(ma, Prelude.identity);
public static TryOptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryOptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static TryOptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryOptionAsync<A>> ma, int windowSize) =>
TraverseParallel(ma, windowSize, Prelude.identity);
public static TryOptionAsync<Lst<B>> Traverse<A, B>(this Lst<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Lst<B>>> Go(Lst<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Lst<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Lst<B>>.None
: new OptionalResult<Lst<B>>(new Lst<B>(rb.Map(d => d.Value.Value)));
}
}
public static TryOptionAsync<Que<B>> Traverse<A, B>(this Que<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Que<B>>> Go(Que<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Que<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Que<B>>.None
: new OptionalResult<Que<B>>(new Que<B>(rb.Map(d => d.Value.Value)));
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static TryOptionAsync<Seq<B>> Traverse<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, f);
public static TryOptionAsync<Seq<B>> TraverseSerial<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Seq<B>>> Go(Seq<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = new List<B>();
foreach (var a in ma)
{
var mb = await a.Try();
if (mb.IsFaulted) return new OptionalResult<Seq<B>>(mb.Exception);
if(mb.IsNone) return OptionalResult<Seq<B>>.None;
rb.Add(f(mb.Value.Value));
}
return new OptionalResult<Seq<B>>(Seq.FromArray(rb.ToArray()));
};
}
public static TryOptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f);
public static TryOptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryOptionAsync<A>> ma, int windowSize, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Seq<B>>> Go(Seq<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity);
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Seq<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Seq<B>>.None
: new OptionalResult<Seq<B>>(Seq.FromArray(rb.Map(d => d.Value.Value).ToArray()));
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static TryOptionAsync<Seq<A>> Sequence<A>(this Seq<TryOptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static TryOptionAsync<Seq<A>> SequenceSerial<A>(this Seq<TryOptionAsync<A>> ma) =>
TraverseSerial(ma, Prelude.identity);
public static TryOptionAsync<Seq<A>> SequenceParallel<A>(this Seq<TryOptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static TryOptionAsync<Seq<A>> SequenceParallel<A>(this Seq<TryOptionAsync<A>> ma, int windowSize) =>
TraverseParallel(ma, windowSize, Prelude.identity);
public static TryOptionAsync<Set<B>> Traverse<A, B>(this Set<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Set<B>>> Go(Set<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Set<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Set<B>>.None
: new OptionalResult<Set<B>>(new Set<B>(rb.Map(d => d.Value.Value)));
}
}
public static TryOptionAsync<Stck<B>> Traverse<A, B>(this Stck<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Stck<B>>> Go(Stck<TryOptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Try()));
return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Stck<B>>(b.Exception)).Head()
: rb.Exists(d => d.IsNone) ? OptionalResult<Stck<B>>.None
: new OptionalResult<Stck<B>>(new Stck<B>(rb.Map(d => d.Value.Value)));
}
}
//
// Async types
//
public static TryOptionAsync<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<EitherAsync<L, B>>> Go(EitherAsync<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
var da = await ma.Data;
if (da.State == EitherStatus.IsBottom) return OptionalResult<EitherAsync<L, B>>.Bottom;
if (da.State == EitherStatus.IsLeft) return new OptionalResult<EitherAsync<L, B>>(EitherAsync<L,B>.Left(da.Left));
var rb = await da.Right.Try();
if (rb.IsFaulted) return new OptionalResult<EitherAsync<L, B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<EitherAsync<L, B>>.None;
return new OptionalResult<EitherAsync<L, B>>(EitherAsync<L, B>.Right(f(rb.Value.Value)));
}
}
public static TryOptionAsync<OptionAsync<B>> Traverse<A, B>(this OptionAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<OptionAsync<B>>> Go(OptionAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
var (isSome, value) = await ma.Data;
if (!isSome) return new OptionalResult<OptionAsync<B>>(OptionAsync<B>.None);
var rb = await value.Try();
if (rb.IsFaulted) return new OptionalResult<OptionAsync<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<OptionAsync<B>>.None;
return new OptionalResult<OptionAsync<B>>(OptionAsync<B>.Some(f(rb.Value.Value)));
}
}
public static TryOptionAsync<TryAsync<B>> Traverse<A, B>(this TryAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<TryAsync<B>>> Go(TryAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
var ra = await ma.Try();
if (ra.IsFaulted) return new OptionalResult<TryAsync<B>>(TryAsync<B>(ra.Exception));
var rb = await ra.Value.Try();
if (rb.IsFaulted) return new OptionalResult<TryAsync<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<TryAsync<B>>.None;
return new OptionalResult<TryAsync<B>>(TryAsync<B>(f(rb.Value.Value)));
}
}
public static TryOptionAsync<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<TryOptionAsync<B>>> Go(TryOptionAsync<TryOptionAsync<A>> ma, Func<A, B> f)
{
var ra = await ma.Try();
if (ra.IsFaulted) return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(ra.Exception));
if (ra.IsNone) return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(None));
var rb = await ra.Value.Value.Try();
if (rb.IsFaulted) return new OptionalResult<TryOptionAsync<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<TryOptionAsync<B>>.None;
return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(f(rb.Value.Value)));
}
}
public static TryOptionAsync<Task<B>> Traverse<A, B>(this Task<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Task<B>>> Go(Task<TryOptionAsync<A>> ma, Func<A, B> f)
{
var ra = await ma;
var rb = await ra.Try();
if (rb.IsFaulted) return new OptionalResult<Task<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Task<B>>.None;
return new OptionalResult<Task<B>>(f(rb.Value.Value).AsTask());
}
}
//
// Sync types
//
public static TryOptionAsync<Either<L, B>> Traverse<L, A, B>(this Either<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Either<L, B>>> Go(Either<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return OptionalResult<Either<L, B>>.Bottom;
if(ma.IsLeft) return new OptionalResult<Either<L, B>>(Left<L, B>(ma.LeftValue));
var rb = await ma.RightValue.Try();
if(rb.IsFaulted) return new OptionalResult<Either<L, B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Either<L, B>>.None;
return OptionalResult<Either<L, B>>.Some(f(rb.Value.Value));
}
}
public static TryOptionAsync<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<EitherUnsafe<L, B>>> Go(EitherUnsafe<L, TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return OptionalResult<EitherUnsafe<L, B>>.Bottom;
if(ma.IsLeft) return new OptionalResult<EitherUnsafe<L, B>>(LeftUnsafe<L, B>(ma.LeftValue));
var rb = await ma.RightValue.Try();
if(rb.IsFaulted) return new OptionalResult<EitherUnsafe<L, B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<EitherUnsafe<L, B>>.None;
return OptionalResult<EitherUnsafe<L, B>>.Some(f(rb.Value.Value));
}
}
public static TryOptionAsync<Identity<B>> Traverse<A, B>(this Identity<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Identity<B>>> Go(Identity<TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return OptionalResult<Identity<B>>.Bottom;
var rb = await ma.Value.Try();
if(rb.IsFaulted) return new OptionalResult<Identity<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Identity<B>>.None;
return OptionalResult<Identity<B>>.Some(new Identity<B>(f(rb.Value.Value)));
}
}
public static TryOptionAsync<Option<B>> Traverse<A, B>(this Option<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Option<B>>> Go(Option<TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsNone) return OptionalResult<Option<B>>.Some(Option<B>.None);
var rb = await ma.Value.Try();
if(rb.IsFaulted) return new OptionalResult<Option<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Option<B>>.None;
return OptionalResult<Option<B>>.Some(Some(f(rb.Value.Value)));
}
}
public static TryOptionAsync<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<OptionUnsafe<B>>> Go(OptionUnsafe<TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsNone) return OptionalResult<OptionUnsafe<B>>.Some(OptionUnsafe<B>.None);
var rb = await ma.Value.Try();
if(rb.IsFaulted) return new OptionalResult<OptionUnsafe<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<OptionUnsafe<B>>.None;
return OptionalResult<OptionUnsafe<B>>.Some(OptionUnsafe<B>.Some(f(rb.Value.Value)));
}
}
public static TryOptionAsync<Try<B>> Traverse<A, B>(this Try<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Try<B>>> Go(Try<TryOptionAsync<A>> ma, Func<A, B> f)
{
var ra = ma.Try();
if (ra.IsFaulted) return new OptionalResult<Try<B>>(TryFail<B>(ra.Exception));
var rb = await ra.Value.Try();
if (rb.IsFaulted) return new OptionalResult<Try<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Try<B>>.None;
return OptionalResult<Try<B>>.Some(Try<B>(f(rb.Value.Value)));
}
}
public static TryOptionAsync<TryOption<B>> Traverse<A, B>(this TryOption<TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<TryOption<B>>> Go(TryOption<TryOptionAsync<A>> ma, Func<A, B> f)
{
var ra = ma.Try();
if (ra.IsBottom) return OptionalResult<TryOption<B>>.Bottom;
if (ra.IsNone) return new OptionalResult<TryOption<B>>(TryOptional<B>(None));
if (ra.IsFaulted) return new OptionalResult<TryOption<B>>(TryOptionFail<B>(ra.Exception));
var rb = await ra.Value.Value.Try();
if (rb.IsFaulted) return new OptionalResult<TryOption<B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<TryOption<B>>.None;
return OptionalResult<TryOption<B>>.Some(TryOption<B>(f(rb.Value.Value)));
}
}
public static TryOptionAsync<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, TryOptionAsync<A>> ma, Func<A, B> f)
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Validation<Fail, B>>> Go(Validation<Fail, TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsFail) return new OptionalResult<Validation<Fail, B>>(Fail<Fail, B>(ma.FailValue));
var rb = await ma.SuccessValue.Try();
if(rb.IsFaulted) return new OptionalResult<Validation<Fail, B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Validation<Fail, B>>.None;
return OptionalResult<Validation<Fail, B>>.Some(f(rb.Value.Value));
}
}
public static TryOptionAsync<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, TryOptionAsync<A>> ma, Func<A, B> f)
where MonoidFail : struct, Monoid<Fail>, Eq<Fail>
{
return ToTry(() => Go(ma, f));
async Task<OptionalResult<Validation<MonoidFail, Fail, B>>> Go(Validation<MonoidFail, Fail, TryOptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsFail) return new OptionalResult<Validation<MonoidFail, Fail, B>>(Fail<MonoidFail, Fail, B>(ma.FailValue));
var rb = await ma.SuccessValue.Try();
if(rb.IsFaulted) return new OptionalResult<Validation<MonoidFail, Fail, B>>(rb.Exception);
if(rb.IsNone) return OptionalResult<Validation<MonoidFail, Fail, B>>.None;
return OptionalResult<Validation<MonoidFail, Fail, B>>.Some(f(rb.Value.Value));
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UMA;
[CustomEditor(typeof(OverlayLibrary))]
[CanEditMultipleObjects]
public class OverlayLibraryEditor : Editor {
private SerializedObject m_Object;
private OverlayLibrary overlayLibrary;
private SerializedProperty m_OverlayDataCount;
private const string kArraySizePath = "overlayElementList.Array.size";
private const string kArrayData = "overlayElementList.Array.data[{0}]";
private bool canUpdate;
private bool isDirty;
public SerializedProperty scaleAdjust;
public SerializedProperty readWrite;
public SerializedProperty compress;
public void OnEnable(){
m_Object = new SerializedObject(target);
overlayLibrary = m_Object.targetObject as OverlayLibrary;
m_OverlayDataCount = m_Object.FindProperty(kArraySizePath);
scaleAdjust = serializedObject.FindProperty ("scaleAdjust");
readWrite = serializedObject.FindProperty ("readWrite");
compress = serializedObject.FindProperty ("compress");
}
private OverlayDataAsset[] GetOverlayDataArray()
{
int arrayCount = m_OverlayDataCount.intValue;
OverlayDataAsset[] OverlayDataArray = new OverlayDataAsset[arrayCount];
for(int i = 0; i < arrayCount; i++){
OverlayDataArray[i] = m_Object.FindProperty(string.Format(kArrayData,i)).objectReferenceValue as OverlayDataAsset;
}
return OverlayDataArray;
}
private void SetOverlayData(int index, OverlayDataAsset overlayElement)
{
m_Object.FindProperty(string.Format(kArrayData,index)).objectReferenceValue = overlayElement;
isDirty = true;
}
private OverlayDataAsset GetOverlayDataAtIndex(int index)
{
return m_Object.FindProperty(string.Format(kArrayData, index)).objectReferenceValue as OverlayDataAsset;
}
private void AddOverlayData(OverlayDataAsset overlayElement)
{
m_OverlayDataCount.intValue ++;
SetOverlayData(m_OverlayDataCount.intValue - 1, overlayElement);
}
private void RemoveOverlayDataAtIndex(int index){
for(int i = index; i < m_OverlayDataCount.intValue - 1; i++){
SetOverlayData(i, GetOverlayDataAtIndex(i + 1));
}
m_OverlayDataCount.intValue --;
}
private void ScaleDownTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*0.5f,tempRect.y*0.5f,tempRect.width*0.5f,tempRect.height*0.5f);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*0.5f);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ScaleUpTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*2,tempRect.y*2,tempRect.width*2,tempRect.height*2);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*2);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ConfigureTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.isReadable = readWrite.boolValue;
if(compress.boolValue){
textureImporter.textureFormat = TextureImporterFormat.AutomaticCompressed;
textureImporter.compressionQuality = (int)TextureCompressionQuality.Best;
}else{
textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
textureImporter.compressionQuality = (int)TextureCompressionQuality.Best;
}
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
Debug.Log(overlayElementList[i].textureList[textureID].name + " isReadable set to " + readWrite.boolValue + " and compression set to " + compress.boolValue);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void DropAreaGUI(Rect dropArea){
var evt = Event.current;
if(evt.type == EventType.DragUpdated){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if(evt.type == EventType.DragPerform){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences;
for(int i = 0; i < draggedObjects.Length; i++){
if (draggedObjects[i])
{
OverlayDataAsset tempOverlayData = draggedObjects[i] as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path);
}
}
}
}
}
}
private void RecursiveScanFoldersForAssets(string path)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempOverlayData = AssetDatabase.LoadAssetAtPath(assetFile, typeof(OverlayDataAsset)) as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'));
}
}
public override void OnInspectorGUI(){
m_Object.Update();
serializedObject.Update();
GUILayout.Label ("overlayList", EditorStyles.boldLabel);
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
GUILayout.Space(30);
GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)");
GUILayout.BeginHorizontal();
if(scaleAdjust.intValue > 0){
if(GUILayout.Button("Resolution +")){
ScaleUpTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue --;
}
}
if(GUILayout.Button("Resolution -")){
ScaleDownTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue ++;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures");
readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write");
if(GUILayout.Button(" Apply")){
ConfigureTextures();
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Order by Name")){
canUpdate = false;
List<OverlayDataAsset> OverlayDataTemp = overlayElementList.ToList();
//Make sure there's no invalid data
for(int i = 0; i < OverlayDataTemp.Count; i++){
if(OverlayDataTemp[i] == null){
OverlayDataTemp.RemoveAt(i);
i--;
}
}
OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name));
for(int i = 0; i < OverlayDataTemp.Count; i++){
SetOverlayData(i,OverlayDataTemp[i]);
}
}
if(GUILayout.Button("Update List")){
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<OverlayDataAsset> Overlays = new HashSet<OverlayDataAsset>();
foreach(OverlayDataAsset oda in overlayElementList)
{
Overlays.Add(oda);
}
m_OverlayDataCount.intValue = Overlays.Count;
for(int i=0;i<Overlays.Count;i++)
{
SetOverlayData(i,Overlays.ElementAt(i));
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea,"Drag Overlays here");
GUILayout.Space(20);
for(int i = 0; i < m_OverlayDataCount.intValue; i ++){
GUILayout.BeginHorizontal();
var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDataAsset), true) as OverlayDataAsset;
if(GUI.changed && canUpdate){
SetOverlayData(i,result);
}
if(GUILayout.Button("-", GUILayout.Width(20.0f))){
canUpdate = false;
RemoveOverlayDataAtIndex(i);
}
GUILayout.EndHorizontal();
if(i == m_OverlayDataCount.intValue -1){
canUpdate = true;
if(isDirty){
overlayLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if(GUILayout.Button("Add OverlayData")){
AddOverlayData(null);
}
if(GUILayout.Button("Clear List")){
m_OverlayDataCount.intValue = 0;
}
m_Object.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.RecommendationEngine.V1Beta1
{
/// <summary>Settings for <see cref="PredictionServiceClient"/> instances.</summary>
public sealed partial class PredictionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="PredictionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="PredictionServiceSettings"/>.</returns>
public static PredictionServiceSettings GetDefault() => new PredictionServiceSettings();
/// <summary>Constructs a new <see cref="PredictionServiceSettings"/> object with default settings.</summary>
public PredictionServiceSettings()
{
}
private PredictionServiceSettings(PredictionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
PredictSettings = existing.PredictSettings;
OnCopy(existing);
}
partial void OnCopy(PredictionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PredictionServiceClient.Predict</c> and <c>PredictionServiceClient.PredictAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings PredictSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="PredictionServiceSettings"/> object.</returns>
public PredictionServiceSettings Clone() => new PredictionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="PredictionServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class PredictionServiceClientBuilder : gaxgrpc::ClientBuilderBase<PredictionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public PredictionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public PredictionServiceClientBuilder()
{
UseJwtAccessWithScopes = PredictionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref PredictionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PredictionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override PredictionServiceClient Build()
{
PredictionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<PredictionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<PredictionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private PredictionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return PredictionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<PredictionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return PredictionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => PredictionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => PredictionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => PredictionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>PredictionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service for making recommendation prediction.
/// </remarks>
public abstract partial class PredictionServiceClient
{
/// <summary>
/// The default endpoint for the PredictionService service, which is a host of
/// "recommendationengine.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "recommendationengine.googleapis.com:443";
/// <summary>The default PredictionService scopes.</summary>
/// <remarks>
/// The default PredictionService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="PredictionServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="PredictionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="PredictionServiceClient"/>.</returns>
public static stt::Task<PredictionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new PredictionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="PredictionServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="PredictionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="PredictionServiceClient"/>.</returns>
public static PredictionServiceClient Create() => new PredictionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="PredictionServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="PredictionServiceSettings"/>.</param>
/// <returns>The created <see cref="PredictionServiceClient"/>.</returns>
internal static PredictionServiceClient Create(grpccore::CallInvoker callInvoker, PredictionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
PredictionService.PredictionServiceClient grpcClient = new PredictionService.PredictionServiceClient(callInvoker);
return new PredictionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC PredictionService client</summary>
public virtual PredictionService.PredictionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.</returns>
public virtual gax::PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> Predict(PredictRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> PredictAsync(PredictRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="name">
/// Required. Full resource name of the format:
/// `{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`
/// The id of the recommendation engine placement. This id is used to identify
/// the set of models that will be used to make the prediction.
///
/// We currently support three placements with the following IDs by default:
///
/// * `shopping_cart`: Predicts items frequently bought together with one or
/// more catalog items in the same shopping session. Commonly displayed after
/// `add-to-cart` events, on product detail pages, or on the shopping cart
/// page.
///
/// * `home_page`: Predicts the next product that a user will most likely
/// engage with or purchase based on the shopping or viewing history of the
/// specified `userId` or `visitorId`. For example - Recommendations for you.
///
/// * `product_detail`: Predicts the next product that a user will most likely
/// engage with or purchase. The prediction is based on the shopping or
/// viewing history of the specified `userId` or `visitorId` and its
/// relevance to a specified `CatalogItem`. Typically used on product detail
/// pages. For example - More items like this.
///
/// * `recently_viewed_default`: Returns up to 75 items recently viewed by the
/// specified `userId` or `visitorId`, most recent ones first. Returns
/// nothing if neither of them has viewed any items yet. For example -
/// Recently viewed.
///
/// The full list of available placements can be seen at
/// https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
/// </param>
/// <param name="userEvent">
/// Required. Context about the user, what they are looking at and what action
/// they took to trigger the predict request. Note that this user event detail
/// won't be ingested to userEvent logs. Thus, a separate userEvent write
/// request is required for event logging.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.</returns>
public virtual gax::PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> Predict(string name, UserEvent userEvent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
Predict(new PredictRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
UserEvent = gax::GaxPreconditions.CheckNotNull(userEvent, nameof(userEvent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="name">
/// Required. Full resource name of the format:
/// `{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`
/// The id of the recommendation engine placement. This id is used to identify
/// the set of models that will be used to make the prediction.
///
/// We currently support three placements with the following IDs by default:
///
/// * `shopping_cart`: Predicts items frequently bought together with one or
/// more catalog items in the same shopping session. Commonly displayed after
/// `add-to-cart` events, on product detail pages, or on the shopping cart
/// page.
///
/// * `home_page`: Predicts the next product that a user will most likely
/// engage with or purchase based on the shopping or viewing history of the
/// specified `userId` or `visitorId`. For example - Recommendations for you.
///
/// * `product_detail`: Predicts the next product that a user will most likely
/// engage with or purchase. The prediction is based on the shopping or
/// viewing history of the specified `userId` or `visitorId` and its
/// relevance to a specified `CatalogItem`. Typically used on product detail
/// pages. For example - More items like this.
///
/// * `recently_viewed_default`: Returns up to 75 items recently viewed by the
/// specified `userId` or `visitorId`, most recent ones first. Returns
/// nothing if neither of them has viewed any items yet. For example -
/// Recently viewed.
///
/// The full list of available placements can be seen at
/// https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
/// </param>
/// <param name="userEvent">
/// Required. Context about the user, what they are looking at and what action
/// they took to trigger the predict request. Note that this user event detail
/// won't be ingested to userEvent logs. Thus, a separate userEvent write
/// request is required for event logging.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> PredictAsync(string name, UserEvent userEvent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
PredictAsync(new PredictRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
UserEvent = gax::GaxPreconditions.CheckNotNull(userEvent, nameof(userEvent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="name">
/// Required. Full resource name of the format:
/// `{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`
/// The id of the recommendation engine placement. This id is used to identify
/// the set of models that will be used to make the prediction.
///
/// We currently support three placements with the following IDs by default:
///
/// * `shopping_cart`: Predicts items frequently bought together with one or
/// more catalog items in the same shopping session. Commonly displayed after
/// `add-to-cart` events, on product detail pages, or on the shopping cart
/// page.
///
/// * `home_page`: Predicts the next product that a user will most likely
/// engage with or purchase based on the shopping or viewing history of the
/// specified `userId` or `visitorId`. For example - Recommendations for you.
///
/// * `product_detail`: Predicts the next product that a user will most likely
/// engage with or purchase. The prediction is based on the shopping or
/// viewing history of the specified `userId` or `visitorId` and its
/// relevance to a specified `CatalogItem`. Typically used on product detail
/// pages. For example - More items like this.
///
/// * `recently_viewed_default`: Returns up to 75 items recently viewed by the
/// specified `userId` or `visitorId`, most recent ones first. Returns
/// nothing if neither of them has viewed any items yet. For example -
/// Recently viewed.
///
/// The full list of available placements can be seen at
/// https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
/// </param>
/// <param name="userEvent">
/// Required. Context about the user, what they are looking at and what action
/// they took to trigger the predict request. Note that this user event detail
/// won't be ingested to userEvent logs. Thus, a separate userEvent write
/// request is required for event logging.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.</returns>
public virtual gax::PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> Predict(PlacementName name, UserEvent userEvent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
Predict(new PredictRequest
{
PlacementName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
UserEvent = gax::GaxPreconditions.CheckNotNull(userEvent, nameof(userEvent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="name">
/// Required. Full resource name of the format:
/// `{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`
/// The id of the recommendation engine placement. This id is used to identify
/// the set of models that will be used to make the prediction.
///
/// We currently support three placements with the following IDs by default:
///
/// * `shopping_cart`: Predicts items frequently bought together with one or
/// more catalog items in the same shopping session. Commonly displayed after
/// `add-to-cart` events, on product detail pages, or on the shopping cart
/// page.
///
/// * `home_page`: Predicts the next product that a user will most likely
/// engage with or purchase based on the shopping or viewing history of the
/// specified `userId` or `visitorId`. For example - Recommendations for you.
///
/// * `product_detail`: Predicts the next product that a user will most likely
/// engage with or purchase. The prediction is based on the shopping or
/// viewing history of the specified `userId` or `visitorId` and its
/// relevance to a specified `CatalogItem`. Typically used on product detail
/// pages. For example - More items like this.
///
/// * `recently_viewed_default`: Returns up to 75 items recently viewed by the
/// specified `userId` or `visitorId`, most recent ones first. Returns
/// nothing if neither of them has viewed any items yet. For example -
/// Recently viewed.
///
/// The full list of available placements can be seen at
/// https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
/// </param>
/// <param name="userEvent">
/// Required. Context about the user, what they are looking at and what action
/// they took to trigger the predict request. Note that this user event detail
/// won't be ingested to userEvent logs. Thus, a separate userEvent write
/// request is required for event logging.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> PredictAsync(PlacementName name, UserEvent userEvent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
PredictAsync(new PredictRequest
{
PlacementName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
UserEvent = gax::GaxPreconditions.CheckNotNull(userEvent, nameof(userEvent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>PredictionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service for making recommendation prediction.
/// </remarks>
public sealed partial class PredictionServiceClientImpl : PredictionServiceClient
{
private readonly gaxgrpc::ApiCall<PredictRequest, PredictResponse> _callPredict;
/// <summary>
/// Constructs a client wrapper for the PredictionService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="PredictionServiceSettings"/> used within this client.</param>
public PredictionServiceClientImpl(PredictionService.PredictionServiceClient grpcClient, PredictionServiceSettings settings)
{
GrpcClient = grpcClient;
PredictionServiceSettings effectiveSettings = settings ?? PredictionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callPredict = clientHelper.BuildApiCall<PredictRequest, PredictResponse>(grpcClient.PredictAsync, grpcClient.Predict, effectiveSettings.PredictSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callPredict);
Modify_PredictApiCall(ref _callPredict);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_PredictApiCall(ref gaxgrpc::ApiCall<PredictRequest, PredictResponse> call);
partial void OnConstruction(PredictionService.PredictionServiceClient grpcClient, PredictionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC PredictionService client</summary>
public override PredictionService.PredictionServiceClient GrpcClient { get; }
partial void Modify_PredictRequest(ref PredictRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.</returns>
public override gax::PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> Predict(PredictRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_PredictRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<PredictRequest, PredictResponse, PredictResponse.Types.PredictionResult>(_callPredict, request, callSettings);
}
/// <summary>
/// Makes a recommendation prediction. If using API Key based authentication,
/// the API Key must be registered using the
/// [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry]
/// service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="PredictResponse.Types.PredictionResult"/> resources.
/// </returns>
public override gax::PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> PredictAsync(PredictRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_PredictRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<PredictRequest, PredictResponse, PredictResponse.Types.PredictionResult>(_callPredict, request, callSettings);
}
}
public partial class PredictRequest : gaxgrpc::IPageRequest
{
}
public partial class PredictResponse : gaxgrpc::IPageResponse<PredictResponse.Types.PredictionResult>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Types.PredictionResult> GetEnumerator() => Results.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
//
// CompositeUtils.cs
//
// Author:
// Larry Ewing <lewing@novell.com>
//
// Copyright (C) 2006 Novell, Inc.
// Copyright (C) 2006 Larry Ewing
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using Gdk;
using Gtk;
using FSpot.Utils;
using Hyena;
namespace FSpot.Gui
{
public class CompositeUtils
{
[DllImport("libgdk-2.0-0.dll")]
static extern bool gdk_screen_is_composited (IntPtr screen);
[DllImport("libgdk-2.0-0.dll")]
static extern bool gdk_x11_screen_supports_net_wm_hint (IntPtr screen,
IntPtr property);
[DllImport("libgdk-2.0-0.dll")]
static extern IntPtr gdk_screen_get_rgba_colormap (IntPtr screen);
[DllImport("libgdk-2.0-0.dll")]
static extern IntPtr gdk_screen_get_rgba_visual (IntPtr screen);
[DllImport ("libgtk-win32-2.0-0.dll")]
static extern void gtk_widget_input_shape_combine_mask (IntPtr raw, IntPtr shape_mask, int offset_x, int offset_y);
[DllImport("libgdk-2.0-0.dll")]
static extern void gdk_property_change(IntPtr window, IntPtr property, IntPtr type, int format, int mode, uint [] data, int nelements);
[DllImport("libgdk-2.0-0.dll")]
static extern void gdk_property_change(IntPtr window, IntPtr property, IntPtr type, int format, int mode, byte [] data, int nelements);
public static Colormap GetRgbaColormap (Screen screen)
{
try {
IntPtr raw_ret = gdk_screen_get_rgba_colormap (screen.Handle);
Gdk.Colormap ret = GLib.Object.GetObject(raw_ret) as Gdk.Colormap;
return ret;
} catch {
Gdk.Visual visual = Gdk.Visual.GetBestWithDepth (32);
if (visual != null) {
Gdk.Colormap cmap = new Gdk.Colormap (visual, false);
Log.Debug ("fallback");
return cmap;
}
}
return null;
}
public static void ChangeProperty (Gdk.Window win, Atom property, Atom type, PropMode mode, uint [] data)
{
gdk_property_change (win.Handle, property.Handle, type.Handle, 32, (int)mode, data, data.Length * 4);
}
public static void ChangeProperty (Gdk.Window win, Atom property, Atom type, PropMode mode, byte [] data)
{
gdk_property_change (win.Handle, property.Handle, type.Handle, 8, (int)mode, data, data.Length);
}
public static bool SupportsHint (Screen screen, string name)
{
try {
Atom atom = Atom.Intern (name, false);
return gdk_x11_screen_supports_net_wm_hint (screen.Handle, atom.Handle);
} catch {
return false;
}
}
public static bool SetRgbaColormap (Widget w)
{
Gdk.Colormap cmap = GetRgbaColormap (w.Screen);
if (cmap != null) {
w.Colormap = cmap;
return true;
}
return false;
}
public static Visual GetRgbaVisual (Screen screen)
{
try {
IntPtr raw_ret = gdk_screen_get_rgba_visual (screen.Handle);
Gdk.Visual ret = GLib.Object.GetObject(raw_ret) as Gdk.Visual;
return ret;
} catch {
Gdk.Visual visual = Gdk.Visual.GetBestWithDepth (32);
if (visual != null) {
return visual;
}
}
return null;
}
public static bool IsComposited (Screen screen) {
bool composited;
try {
composited = gdk_screen_is_composited (screen.Handle);
} catch (EntryPointNotFoundException) {
Log.Debug ("query composite manager locally");
Atom atom = Atom.Intern (string.Format ("_NET_WM_CM_S{0}", screen.Number), false);
composited = Gdk.Selection.OwnerGetForDisplay (screen.Display, atom) != null;
}
// FIXME check for WINDOW_OPACITY so that we support compositing on older composite manager
// versions before they started supporting the real check given above
if (!composited)
composited = CompositeUtils.SupportsHint (screen, "_NET_WM_WINDOW_OPACITY");
return composited;
}
public static void InputShapeCombineMask (Widget w, Pixmap shape_mask, int offset_x, int offset_y)
{
gtk_widget_input_shape_combine_mask (w.Handle, shape_mask == null ? IntPtr.Zero : shape_mask.Handle, offset_x, offset_y);
}
[DllImport("libXcomposite.dll")]
static extern void XCompositeRedirectWindow (IntPtr display, uint window, CompositeRedirect update);
public enum CompositeRedirect {
Automatic = 0,
Manual = 1
};
public static void RedirectDrawable (Drawable d)
{
uint xid = GdkUtils.GetXid (d);
Log.DebugFormat ("xid = {0} d.handle = {1}, d.Display.Handle = {2}", xid, d.Handle, d.Display.Handle);
XCompositeRedirectWindow (GdkUtils.GetXDisplay (d.Display), GdkUtils.GetXid (d), CompositeRedirect.Manual);
}
public static void SetWinOpacity (Gtk.Window win, double opacity)
{
CompositeUtils.ChangeProperty (win.GdkWindow,
Atom.Intern ("_NET_WM_WINDOW_OPACITY", false),
Atom.Intern ("CARDINAL", false),
PropMode.Replace,
new uint [] { (uint) (0xffffffff * opacity) });
}
public static Cms.Profile GetScreenProfile (Screen screen)
{
Atom atype;
int aformat;
int alength;
byte [] data;
if (Gdk.Property.Get (screen.RootWindow,
Atom.Intern ("_ICC_PROFILE", false),
Atom.Intern ("CARDINAL", false),
0,
Int32.MaxValue,
0, // FIXME in gtk# should be a bool
out atype,
out aformat,
out alength,
out data)) {
return new Cms.Profile (data);
}
return null;
}
public static void SetScreenProfile (Screen screen, Cms.Profile profile)
{
byte [] data = profile.Save ();
ChangeProperty (screen.RootWindow,
Atom.Intern ("_ICC_PROFILE", false),
Atom.Intern ("CARDINAL", false),
PropMode.Replace,
data);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AssuredWorkloads.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAssuredWorkloadsServiceClientTest
{
[xunit::FactAttribute]
public void UpdateWorkloadRequestObject()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new wkt::FieldMask(),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.UpdateWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload response = client.UpdateWorkload(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateWorkloadRequestObjectAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new wkt::FieldMask(),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.UpdateWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workload>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload responseCallSettings = await client.UpdateWorkloadAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workload responseCancellationToken = await client.UpdateWorkloadAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateWorkload()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new wkt::FieldMask(),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.UpdateWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload response = client.UpdateWorkload(request.Workload, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateWorkloadAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new wkt::FieldMask(),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.UpdateWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workload>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload responseCallSettings = await client.UpdateWorkloadAsync(request.Workload, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workload responseCancellationToken = await client.UpdateWorkloadAsync(request.Workload, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkloadRequestObject()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkload(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkloadRequestObjectAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkloadAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkloadAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkload()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkload(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkloadAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkloadAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkloadAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkloadResourceNames()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkload(request.WorkloadName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkloadResourceNamesAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkloadAsync(request.WorkloadName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkloadAsync(request.WorkloadName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkloadRequestObject()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload response = client.GetWorkload(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkloadRequestObjectAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workload>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload responseCallSettings = await client.GetWorkloadAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workload responseCancellationToken = await client.GetWorkloadAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkload()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload response = client.GetWorkload(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkloadAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workload>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload responseCallSettings = await client.GetWorkloadAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workload responseCancellationToken = await client.GetWorkloadAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkloadResourceNames()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkload(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload response = client.GetWorkload(request.WorkloadName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkloadResourceNamesAsync()
{
moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient> mockGrpcClient = new moq::Mock<AssuredWorkloadsService.AssuredWorkloadsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
Workload expectedResponse = new Workload
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
DisplayName = "display_name137f65c2",
Resources =
{
new Workload.Types.ResourceInfo(),
},
ComplianceRegime = Workload.Types.ComplianceRegime.FedrampHigh,
CreateTime = new wkt::Timestamp(),
BillingAccount = "billing_account2062abb6",
#pragma warning disable CS0612
Il4Settings = new Workload.Types.IL4Settings(),
CjisSettings = new Workload.Types.CJISSettings(),
#pragma warning restore CS0612
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
#pragma warning disable CS0612
FedrampHighSettings = new Workload.Types.FedrampHighSettings(),
FedrampModerateSettings = new Workload.Types.FedrampModerateSettings(),
#pragma warning restore CS0612
ProvisionedResourcesParent = "provisioned_resources_parent4d000dc9",
KmsSettings = new Workload.Types.KMSSettings(),
ResourceSettings =
{
new Workload.Types.ResourceSettings(),
},
};
mockGrpcClient.Setup(x => x.GetWorkloadAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workload>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssuredWorkloadsServiceClient client = new AssuredWorkloadsServiceClientImpl(mockGrpcClient.Object, null);
Workload responseCallSettings = await client.GetWorkloadAsync(request.WorkloadName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workload responseCancellationToken = await client.GetWorkloadAsync(request.WorkloadName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using J2N.Numerics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Class that Posting and PostingVector use to write byte
/// streams into shared fixed-size <see cref="T:byte[]"/> arrays. The idea
/// is to allocate slices of increasing lengths. For
/// example, the first slice is 5 bytes, the next slice is
/// 14, etc. We start by writing our bytes into the first
/// 5 bytes. When we hit the end of the slice, we allocate
/// the next slice and then write the address of the new
/// slice into the last 4 bytes of the previous slice (the
/// "forwarding address").
/// <para/>
/// Each slice is filled with 0's initially, and we mark
/// the end with a non-zero byte. This way the methods
/// that are writing into the slice don't need to record
/// its length and instead allocate a new slice once they
/// hit a non-zero byte.
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class ByteBlockPool
{
public static readonly int BYTE_BLOCK_SHIFT = 15;
public static readonly int BYTE_BLOCK_SIZE = 1 << BYTE_BLOCK_SHIFT;
public static readonly int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1;
/// <summary>
/// Abstract class for allocating and freeing byte
/// blocks.
/// </summary>
public abstract class Allocator
{
protected readonly int m_blockSize;
protected Allocator(int blockSize)
{
this.m_blockSize = blockSize;
}
public abstract void RecycleByteBlocks(byte[][] blocks, int start, int end); // LUCENENT TODO: API - Change to use IList<byte[]>
public virtual void RecycleByteBlocks(IList<byte[]> blocks)
{
var b = blocks.ToArray();
RecycleByteBlocks(b, 0, b.Length);
}
public virtual byte[] GetByteBlock()
{
return new byte[m_blockSize];
}
}
/// <summary>
/// A simple <see cref="Allocator"/> that never recycles. </summary>
public sealed class DirectAllocator : Allocator
{
public DirectAllocator()
: this(BYTE_BLOCK_SIZE)
{
}
public DirectAllocator(int blockSize)
: base(blockSize)
{
}
public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
{
}
}
/// <summary>
/// A simple <see cref="Allocator"/> that never recycles, but
/// tracks how much total RAM is in use.
/// </summary>
public class DirectTrackingAllocator : Allocator
{
private readonly Counter bytesUsed;
public DirectTrackingAllocator(Counter bytesUsed)
: this(BYTE_BLOCK_SIZE, bytesUsed)
{
}
public DirectTrackingAllocator(int blockSize, Counter bytesUsed)
: base(blockSize)
{
this.bytesUsed = bytesUsed;
}
public override byte[] GetByteBlock()
{
bytesUsed.AddAndGet(m_blockSize);
return new byte[m_blockSize];
}
public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
{
bytesUsed.AddAndGet(-((end - start) * m_blockSize));
for (var i = start; i < end; i++)
{
blocks[i] = null;
}
}
}
/// <summary>
/// Array of buffers currently used in the pool. Buffers are allocated if
/// needed don't modify this outside of this class.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[][] Buffers
{
get => buffers;
set => buffers = value;
}
private byte[][] buffers = new byte[10][];
/// <summary>
/// index into the buffers array pointing to the current buffer used as the head </summary>
private int bufferUpto = -1; // Which buffer we are upto
/// <summary>
/// Where we are in head buffer </summary>
public int ByteUpto { get; set; }
/// <summary>
/// Current head buffer
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[] Buffer
{
get => buffer;
set => buffer = value;
}
private byte[] buffer;
/// <summary>
/// Current head offset </summary>
public int ByteOffset { get; set; }
private readonly Allocator allocator;
public ByteBlockPool(Allocator allocator)
{
// set defaults
ByteUpto = BYTE_BLOCK_SIZE;
ByteOffset = -BYTE_BLOCK_SIZE;
this.allocator = allocator;
}
/// <summary>
/// Resets the pool to its initial state reusing the first buffer and fills all
/// buffers with <c>0</c> bytes before they reused or passed to
/// <see cref="Allocator.RecycleByteBlocks(byte[][], int, int)"/>. Calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset.
/// </summary>
public void Reset()
{
Reset(true, true);
}
/// <summary>
/// Expert: Resets the pool to its initial state reusing the first buffer. Calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset. </summary>
/// <param name="zeroFillBuffers"> if <c>true</c> the buffers are filled with <tt>0</tt>.
/// this should be set to <c>true</c> if this pool is used with slices. </param>
/// <param name="reuseFirst"> if <c>true</c> the first buffer will be reused and calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset if the
/// block pool was used before ie. <see cref="ByteBlockPool.NextBuffer()"/> was called before. </param>
public void Reset(bool zeroFillBuffers, bool reuseFirst)
{
if (bufferUpto != -1)
{
// We allocated at least one buffer
if (zeroFillBuffers)
{
for (int i = 0; i < bufferUpto; i++)
{
// Fully zero fill buffers that we fully used
Arrays.Fill(buffers[i], (byte)0);
}
// Partial zero fill the final buffer
Arrays.Fill(buffers[bufferUpto], 0, ByteUpto, (byte)0);
}
if (bufferUpto > 0 || !reuseFirst)
{
int offset = reuseFirst ? 1 : 0;
// Recycle all but the first buffer
allocator.RecycleByteBlocks(buffers, offset, 1 + bufferUpto);
Arrays.Fill(buffers, offset, 1 + bufferUpto, null);
}
if (reuseFirst)
{
// Re-use the first buffer
bufferUpto = 0;
ByteUpto = 0;
ByteOffset = 0;
buffer = buffers[0];
}
else
{
bufferUpto = -1;
ByteUpto = BYTE_BLOCK_SIZE;
ByteOffset = -BYTE_BLOCK_SIZE;
buffer = null;
}
}
}
/// <summary>
/// Advances the pool to its next buffer. This method should be called once
/// after the constructor to initialize the pool. In contrast to the
/// constructor a <see cref="ByteBlockPool.Reset()"/> call will advance the pool to
/// its first buffer immediately.
/// </summary>
public void NextBuffer()
{
if (1 + bufferUpto == buffers.Length)
{
var newBuffers = new byte[ArrayUtil.Oversize(buffers.Length + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][];
Array.Copy(buffers, 0, newBuffers, 0, buffers.Length);
buffers = newBuffers;
}
buffer = buffers[1 + bufferUpto] = allocator.GetByteBlock();
bufferUpto++;
ByteUpto = 0;
ByteOffset += BYTE_BLOCK_SIZE;
}
/// <summary>
/// Allocates a new slice with the given size.</summary>
/// <seealso cref="ByteBlockPool.FIRST_LEVEL_SIZE"/>
public int NewSlice(int size)
{
if (ByteUpto > BYTE_BLOCK_SIZE - size)
{
NextBuffer();
}
int upto = ByteUpto;
ByteUpto += size;
buffer[ByteUpto - 1] = 16;
return upto;
}
// Size of each slice. These arrays should be at most 16
// elements (index is encoded with 4 bits). First array
// is just a compact way to encode X+1 with a max. Second
// array is the length of each slice, ie first slice is 5
// bytes, next slice is 14 bytes, etc.
/// <summary>
/// An array holding the offset into the <see cref="ByteBlockPool.LEVEL_SIZE_ARRAY"/>
/// to quickly navigate to the next slice level.
/// </summary>
public static readonly int[] NEXT_LEVEL_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 };
/// <summary>
/// An array holding the level sizes for byte slices.
/// </summary>
public static readonly int[] LEVEL_SIZE_ARRAY = new int[] { 5, 14, 20, 30, 40, 40, 80, 80, 120, 200 };
/// <summary>
/// The first level size for new slices </summary>
/// <seealso cref="ByteBlockPool.NewSlice(int)"/>
public static readonly int FIRST_LEVEL_SIZE = LEVEL_SIZE_ARRAY[0];
/// <summary>
/// Creates a new byte slice with the given starting size and
/// returns the slices offset in the pool.
/// </summary>
public int AllocSlice(byte[] slice, int upto)
{
int level = slice[upto] & 15;
int newLevel = NEXT_LEVEL_ARRAY[level];
int newSize = LEVEL_SIZE_ARRAY[newLevel];
// Maybe allocate another block
if (ByteUpto > BYTE_BLOCK_SIZE - newSize)
{
NextBuffer();
}
int newUpto = ByteUpto;
int offset = newUpto + ByteOffset;
ByteUpto += newSize;
// Copy forward the past 3 bytes (which we are about
// to overwrite with the forwarding address):
buffer[newUpto] = slice[upto - 3];
buffer[newUpto + 1] = slice[upto - 2];
buffer[newUpto + 2] = slice[upto - 1];
// Write forwarding address at end of last slice:
slice[upto - 3] = (byte)offset.TripleShift(24);
slice[upto - 2] = (byte)offset.TripleShift(16);
slice[upto - 1] = (byte)offset.TripleShift(8);
slice[upto] = (byte)offset;
// Write new level:
buffer[ByteUpto - 1] = (byte)(16 | newLevel);
return newUpto + 3;
}
// Fill in a BytesRef from term's length & bytes encoded in
// byte block
public void SetBytesRef(BytesRef term, int textStart)
{
var bytes = term.Bytes = buffers[textStart >> BYTE_BLOCK_SHIFT];
var pos = textStart & BYTE_BLOCK_MASK;
if ((bytes[pos] & 0x80) == 0)
{
// length is 1 byte
term.Length = bytes[pos];
term.Offset = pos + 1;
}
else
{
// length is 2 bytes
term.Length = (bytes[pos] & 0x7f) + ((bytes[pos + 1] & 0xff) << 7);
term.Offset = pos + 2;
}
Debug.Assert(term.Length >= 0);
}
/// <summary>
/// Appends the bytes in the provided <see cref="BytesRef"/> at
/// the current position.
/// </summary>
public void Append(BytesRef bytes)
{
var length = bytes.Length;
if (length == 0)
{
return;
}
int offset = bytes.Offset;
int overflow = (length + ByteUpto) - BYTE_BLOCK_SIZE;
do
{
if (overflow <= 0)
{
Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, length);
ByteUpto += length;
break;
}
else
{
int bytesToCopy = length - overflow;
if (bytesToCopy > 0)
{
Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, bytesToCopy);
offset += bytesToCopy;
length -= bytesToCopy;
}
NextBuffer();
overflow = overflow - BYTE_BLOCK_SIZE;
}
} while (true);
}
/// <summary>
/// Reads bytes bytes out of the pool starting at the given offset with the given
/// length into the given byte array at offset <c>off</c>.
/// <para>Note: this method allows to copy across block boundaries.</para>
/// </summary>
public void ReadBytes(long offset, byte[] bytes, int off, int length)
{
if (length == 0)
{
return;
}
var bytesOffset = off;
var bytesLength = length;
var bufferIndex = (int)(offset >> BYTE_BLOCK_SHIFT);
var buffer = buffers[bufferIndex];
var pos = (int)(offset & BYTE_BLOCK_MASK);
var overflow = (pos + length) - BYTE_BLOCK_SIZE;
do
{
if (overflow <= 0)
{
Array.Copy(buffer, pos, bytes, bytesOffset, bytesLength);
break;
}
else
{
int bytesToCopy = length - overflow;
Array.Copy(buffer, pos, bytes, bytesOffset, bytesToCopy);
pos = 0;
bytesLength -= bytesToCopy;
bytesOffset += bytesToCopy;
buffer = buffers[++bufferIndex];
overflow = overflow - BYTE_BLOCK_SIZE;
}
} while (true);
}
}
}
| |
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Orleans.Reminders.DynamoDB
{
/// <summary>
/// Implementation for IReminderTable using DynamoDB as underlying storage.
/// </summary>
internal class DynamoDBReminderTable : IReminderTable
{
private const string GRAIN_REFERENCE_PROPERTY_NAME = "GrainReference";
private const string REMINDER_NAME_PROPERTY_NAME = "ReminderName";
private const string SERVICE_ID_PROPERTY_NAME = "ServiceId";
private const string START_TIME_PROPERTY_NAME = "StartTime";
private const string PERIOD_PROPERTY_NAME = "Period";
private const string GRAIN_HASH_PROPERTY_NAME = "GrainHash";
private const string REMINDER_ID_PROPERTY_NAME = "ReminderId";
private const string ETAG_PROPERTY_NAME = "ETag";
private const string CURRENT_ETAG_ALIAS = ":currentETag";
private const string SERVICE_ID_INDEX = "ServiceIdIndex";
private SafeRandom _random = new SafeRandom();
private readonly ILogger logger;
private readonly IGrainReferenceConverter grainReferenceConverter;
private readonly ILoggerFactory loggerFactory;
private readonly DynamoDBReminderStorageOptions options;
private readonly string serviceId;
private DynamoDBStorage storage;
/// <summary>Initializes a new instance of the <see cref="DynamoDBReminderTable"/> class.</summary>
/// <param name="grainReferenceConverter">The grain factory.</param>
/// <param name="loggerFactory">logger factory to use</param>
/// <param name="clusterOptions"></param>
/// <param name="storageOptions"></param>
public DynamoDBReminderTable(
IGrainReferenceConverter grainReferenceConverter,
ILoggerFactory loggerFactory,
IOptions<ClusterOptions> clusterOptions,
IOptions<DynamoDBReminderStorageOptions> storageOptions)
{
this.grainReferenceConverter = grainReferenceConverter;
this.logger = loggerFactory.CreateLogger<DynamoDBReminderTable>();
this.loggerFactory = loggerFactory;
this.serviceId = clusterOptions.Value.ServiceId;
this.options = storageOptions.Value;
}
/// <summary>Initialize current instance with specific global configuration and logger</summary>
public Task Init()
{
this.storage = new DynamoDBStorage(this.loggerFactory, this.options.Service, this.options.AccessKey, this.options.SecretKey,
this.options.ReadCapacityUnits, this.options.WriteCapacityUnits);
this.logger.Info(ErrorCode.ReminderServiceBase, "Initializing AWS DynamoDB Reminders Table");
var secondaryIndex = new GlobalSecondaryIndex
{
IndexName = SERVICE_ID_INDEX,
Projection = new Projection { ProjectionType = ProjectionType.ALL },
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement { AttributeName = SERVICE_ID_PROPERTY_NAME, KeyType = KeyType.HASH},
new KeySchemaElement { AttributeName = GRAIN_HASH_PROPERTY_NAME, KeyType = KeyType.RANGE }
}
};
return this.storage.InitializeTable(this.options.TableName,
new List<KeySchemaElement>
{
new KeySchemaElement { AttributeName = REMINDER_ID_PROPERTY_NAME, KeyType = KeyType.HASH },
new KeySchemaElement { AttributeName = GRAIN_HASH_PROPERTY_NAME, KeyType = KeyType.RANGE }
},
new List<AttributeDefinition>
{
new AttributeDefinition { AttributeName = REMINDER_ID_PROPERTY_NAME, AttributeType = ScalarAttributeType.S },
new AttributeDefinition { AttributeName = GRAIN_HASH_PROPERTY_NAME, AttributeType = ScalarAttributeType.N },
new AttributeDefinition { AttributeName = SERVICE_ID_PROPERTY_NAME, AttributeType = ScalarAttributeType.S }
},
new List<GlobalSecondaryIndex> { secondaryIndex });
}
/// <summary>
/// Reads a reminder for a grain reference by reminder name.
/// Read a row from the reminder table
/// </summary>
/// <param name="grainRef"> grain ref to locate the row </param>
/// <param name="reminderName"> reminder name to locate the row </param>
/// <returns> Return the ReminderTableData if the rows were read successfully </returns>
public async Task<ReminderEntry> ReadRow(GrainReference grainRef, string reminderName)
{
var reminderId = ConstructReminderId(this.serviceId, grainRef, reminderName);
var keys = new Dictionary<string, AttributeValue>
{
{ $"{REMINDER_ID_PROPERTY_NAME}", new AttributeValue(reminderId) },
{ $"{GRAIN_HASH_PROPERTY_NAME}", new AttributeValue { N = grainRef.GetUniformHashCode().ToString() } }
};
try
{
return await this.storage.ReadSingleEntryAsync(this.options.TableName, keys, this.Resolve).ConfigureAwait(false);
}
catch (Exception exc)
{
this.logger.Warn(ErrorCode.ReminderServiceBase,
$"Intermediate error reading reminder entry {Utils.DictionaryToString(keys)} from table {this.options.TableName}.", exc);
throw;
}
}
/// <summary>
/// Read one row from the reminder table
/// </summary>
/// <param name="grainRef">grain ref to locate the row </param>
/// <returns> Return the ReminderTableData if the rows were read successfully </returns>
public async Task<ReminderTableData> ReadRows(GrainReference grainRef)
{
var expressionValues = new Dictionary<string, AttributeValue>
{
{ $":{SERVICE_ID_PROPERTY_NAME}", new AttributeValue(this.serviceId) },
{ $":{GRAIN_REFERENCE_PROPERTY_NAME}", new AttributeValue(grainRef.ToKeyString()) }
};
try
{
var expression = $"{SERVICE_ID_PROPERTY_NAME} = :{SERVICE_ID_PROPERTY_NAME} AND {GRAIN_REFERENCE_PROPERTY_NAME} = :{GRAIN_REFERENCE_PROPERTY_NAME}";
var records = await this.storage.ScanAsync(this.options.TableName, expressionValues, expression, this.Resolve).ConfigureAwait(false);
return new ReminderTableData(records);
}
catch (Exception exc)
{
this.logger.Warn(ErrorCode.ReminderServiceBase,
$"Intermediate error reading reminder entry {Utils.DictionaryToString(expressionValues)} from table {this.options.TableName}.", exc);
throw;
}
}
/// <summary>
/// Reads reminder table data for a given hash range.
/// </summary>
/// <param name="beginHash"></param>
/// <param name="endHash"></param>
/// <returns> Return the RemiderTableData if the rows were read successfully </returns>
public async Task<ReminderTableData> ReadRows(uint beginHash, uint endHash)
{
var expressionValues = new Dictionary<string, AttributeValue>
{
{ $":{SERVICE_ID_PROPERTY_NAME}", new AttributeValue(this.serviceId) },
{ $":Begin{GRAIN_HASH_PROPERTY_NAME}", new AttributeValue { N = beginHash.ToString() } },
{ $":End{GRAIN_HASH_PROPERTY_NAME}", new AttributeValue { N = endHash.ToString() } }
};
try
{
string expression = string.Empty;
if (beginHash < endHash)
{
expression = $"{SERVICE_ID_PROPERTY_NAME} = :{SERVICE_ID_PROPERTY_NAME} AND {GRAIN_HASH_PROPERTY_NAME} > :Begin{GRAIN_HASH_PROPERTY_NAME} AND {GRAIN_HASH_PROPERTY_NAME} <= :End{GRAIN_HASH_PROPERTY_NAME}";
}
else
{
expression = $"{SERVICE_ID_PROPERTY_NAME} = :{SERVICE_ID_PROPERTY_NAME} AND ({GRAIN_HASH_PROPERTY_NAME} > :Begin{GRAIN_HASH_PROPERTY_NAME} OR {GRAIN_HASH_PROPERTY_NAME} <= :End{GRAIN_HASH_PROPERTY_NAME})";
}
var records = await this.storage.ScanAsync(this.options.TableName, expressionValues, expression, this.Resolve).ConfigureAwait(false);
return new ReminderTableData(records);
}
catch (Exception exc)
{
this.logger.Warn(ErrorCode.ReminderServiceBase,
$"Intermediate error reading reminder entry {Utils.DictionaryToString(expressionValues)} from table {this.options.TableName}.", exc);
throw;
}
}
private ReminderEntry Resolve(Dictionary<string, AttributeValue> item)
{
return new ReminderEntry
{
ETag = item[ETAG_PROPERTY_NAME].N,
GrainRef = this.grainReferenceConverter.GetGrainFromKeyString(item[GRAIN_REFERENCE_PROPERTY_NAME].S),
Period = TimeSpan.Parse(item[PERIOD_PROPERTY_NAME].S),
ReminderName = item[REMINDER_NAME_PROPERTY_NAME].S,
StartAt = DateTime.Parse(item[START_TIME_PROPERTY_NAME].S)
};
}
/// <summary>
/// Remove one row from the reminder table
/// </summary>
/// <param name="grainRef"> specific grain ref to locate the row </param>
/// <param name="reminderName"> reminder name to locate the row </param>
/// <param name="eTag"> e tag </param>
/// <returns> Return true if the row was removed </returns>
public async Task<bool> RemoveRow(GrainReference grainRef, string reminderName, string eTag)
{
var reminderId = ConstructReminderId(this.serviceId, grainRef, reminderName);
var keys = new Dictionary<string, AttributeValue>
{
{ $"{REMINDER_ID_PROPERTY_NAME}", new AttributeValue(reminderId) },
{ $"{GRAIN_HASH_PROPERTY_NAME}", new AttributeValue { N = grainRef.GetUniformHashCode().ToString() } }
};
try
{
var conditionalValues = new Dictionary<string, AttributeValue> { { CURRENT_ETAG_ALIAS, new AttributeValue { N = eTag } } };
var expression = $"{ETAG_PROPERTY_NAME} = {CURRENT_ETAG_ALIAS}";
await this.storage.DeleteEntryAsync(this.options.TableName, keys, expression, conditionalValues).ConfigureAwait(false);
return true;
}
catch (ConditionalCheckFailedException)
{
return false;
}
}
/// <summary>
/// Test hook to clear reminder table data.
/// </summary>
/// <returns></returns>
public async Task TestOnlyClearTable()
{
var expressionValues = new Dictionary<string, AttributeValue>
{
{ $":{SERVICE_ID_PROPERTY_NAME}", new AttributeValue(this.serviceId) }
};
try
{
var expression = $"{SERVICE_ID_PROPERTY_NAME} = :{SERVICE_ID_PROPERTY_NAME}";
var records = await this.storage.ScanAsync(this.options.TableName, expressionValues, expression,
item => new Dictionary<string, AttributeValue>
{
{ REMINDER_ID_PROPERTY_NAME, item[REMINDER_ID_PROPERTY_NAME] },
{ GRAIN_HASH_PROPERTY_NAME, item[GRAIN_HASH_PROPERTY_NAME] }
}).ConfigureAwait(false);
if (records.Count <= 25)
{
await this.storage.DeleteEntriesAsync(this.options.TableName, records);
}
else
{
List<Task> tasks = new List<Task>();
foreach (var batch in records.BatchIEnumerable(25))
{
tasks.Add(this.storage.DeleteEntriesAsync(this.options.TableName, batch));
}
await Task.WhenAll(tasks);
}
}
catch (Exception exc)
{
this.logger.Warn(ErrorCode.ReminderServiceBase,
$"Intermediate error removing reminder entries {Utils.DictionaryToString(expressionValues)} from table {this.options.TableName}.", exc);
throw;
}
}
/// <summary>
/// Async method to put an entry into the reminder table
/// </summary>
/// <param name="entry"> The entry to put </param>
/// <returns> Return the entry ETag if entry was upsert successfully </returns>
public async Task<string> UpsertRow(ReminderEntry entry)
{
var reminderId = ConstructReminderId(this.serviceId, entry.GrainRef, entry.ReminderName);
var fields = new Dictionary<string, AttributeValue>
{
{ REMINDER_ID_PROPERTY_NAME, new AttributeValue(reminderId) },
{ GRAIN_HASH_PROPERTY_NAME, new AttributeValue { N = entry.GrainRef.GetUniformHashCode().ToString() } },
{ SERVICE_ID_PROPERTY_NAME, new AttributeValue(this.serviceId) },
{ GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue( entry.GrainRef.ToKeyString()) },
{ PERIOD_PROPERTY_NAME, new AttributeValue(entry.Period.ToString()) },
{ START_TIME_PROPERTY_NAME, new AttributeValue(entry.StartAt.ToString()) },
{ REMINDER_NAME_PROPERTY_NAME, new AttributeValue(entry.ReminderName) },
{ ETAG_PROPERTY_NAME, new AttributeValue { N = this._random.Next(int.MaxValue).ToString() } }
};
try
{
if (this.logger.IsEnabled(LogLevel.Debug)) this.logger.Debug("UpsertRow entry = {0}, etag = {1}", entry.ToString(), entry.ETag);
await this.storage.PutEntryAsync(this.options.TableName, fields);
entry.ETag = fields[ETAG_PROPERTY_NAME].N;
return entry.ETag;
}
catch (Exception exc)
{
this.logger.Warn(ErrorCode.ReminderServiceBase,
$"Intermediate error updating entry {entry.ToString()} to the table {this.options.TableName}.", exc);
throw;
}
}
private static string ConstructReminderId(string serviceId, GrainReference grainRef, string reminderName)
{
return $"{serviceId}_{grainRef.ToKeyString()}_{reminderName}";
}
}
}
| |
/*
* TokenStringDFA.cs
*/
using System;
using System.Text;
namespace Core.Library {
/**
* A deterministic finite state automaton for matching exact strings.
* It uses a sorted binary tree representation of the state
* transitions in order to enable quick matches with a minimal memory
* footprint. It only supports a single character transition between
* states, but may be run in an all case-insensitive mode.
*
*
*
*/
internal class TokenStringDFA {
/**
* The lookup table for root states, indexed by the first ASCII
* character. This array is used to for speed optimizing the
* first step in the match.
*/
private DFAState[] ascii = new DFAState[128];
/**
* The automaton state transition tree for non-ASCII characters.
* Each transition from one state to another is added to the tree
* with the corresponding character.
*/
private DFAState nonAscii = new DFAState();
/**
* Creates a new empty string automaton.
*/
public TokenStringDFA() {
}
/**
* Adds a string match to this automaton. New states and
* transitions will be added to extend this automaton to
* support the specified string.
*
* @param str the string to match
* @param caseInsensitive the case-insensitive flag
* @param value the match value
*/
public void AddMatch(string str, bool caseInsensitive, TokenPattern value) {
DFAState state;
DFAState next;
char c = str[0];
int start = 0;
if (caseInsensitive) {
c = Char.ToLower(c);
}
if (c < 128) {
state = ascii[c];
if (state == null) {
state = ascii[c] = new DFAState();
}
start++;
} else {
state = nonAscii;
}
for (int i = start; i < str.Length; i++) {
next = state.tree.Find(str[i], caseInsensitive);
if (next == null) {
next = new DFAState();
state.tree.Add(str[i], caseInsensitive, next);
}
state = next;
}
state.value = value;
}
/**
* Checks if the automaton matches an input stream. The
* matching will be performed from a specified position. This
* method will not read any characters from the stream, just
* peek ahead. The comparison can be done either in
* case-sensitive or case-insensitive mode.
*
* @param input the input stream to check
* @param pos the starting position
* @param caseInsensitive the case-insensitive flag
*
* @return the match value, or
* null if no match was found
*
* @throws IOException if an I/O error occurred
*/
public TokenPattern Match(ReaderBuffer buffer, bool caseInsensitive) {
TokenPattern result = null;
DFAState state;
int pos = 0;
int c;
c = buffer.Peek(0);
if (c < 0) {
return null;
}
if (caseInsensitive) {
c = Char.ToLower((char) c);
}
if (c < 128) {
state = ascii[c];
if (state == null) {
return null;
} else if (state.value != null) {
result = state.value;
}
pos++;
} else {
state = nonAscii;
}
while ((c = buffer.Peek(pos)) >= 0) {
state = state.tree.Find((char) c, caseInsensitive);
if (state == null) {
break;
} else if (state.value != null) {
result = state.value;
}
pos++;
}
return result;
}
/**
* Returns a detailed string representation of this automaton.
*
* @return a detailed string representation of this automaton
*/
public override string ToString() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < ascii.Length; i++) {
if (ascii[i] != null) {
buffer.Append((char) i);
if (ascii[i].value != null) {
buffer.Append(": ");
buffer.Append(ascii[i].value);
buffer.Append("\n");
}
ascii[i].tree.PrintTo(buffer, " ");
}
}
nonAscii.tree.PrintTo(buffer, "");
return buffer.ToString();
}
}
/**
* An automaton state. This class represents a state in the DFA
* graph.
*
*
*
*/
internal class DFAState {
/**
* The token pattern matched at this state.
*/
internal TokenPattern value = null;
/**
* The automaton state transition tree. Each transition from one
* state to another is added to the tree with the corresponding
* character.
*/
internal TransitionTree tree = new TransitionTree();
}
/**
* An automaton state transition tree. This class contains a
* binary search tree for the automaton transitions from one
* state to another. All transitions are linked to a single
* character.
*
*
*
*/
internal class TransitionTree {
/**
* The transition character. If this value is set to the zero
* character ('\0'), this tree is empty.
*/
private char value = '\0';
/**
* The transition target state.
*/
private DFAState state = null;
/**
* The left subtree.
*/
private TransitionTree left = null;
/**
* The right subtree.
*/
private TransitionTree right = null;
/**
* Creates a new empty automaton transition tree.
*/
public TransitionTree() {
}
/**
* Finds an automaton state from the specified transition
* character. This method searches this transition tree for a
* matching transition. The comparison can optionally be done
* with a lower-case conversion of the character.
*
* @param c the character to search for
* @param lowerCase the lower-case conversion flag
*
* @return the automaton state found, or
* null if no transition exists
*/
public DFAState Find(char c, bool lowerCase) {
if (lowerCase) {
c = Char.ToLower(c);
}
if (value == '\0' || value == c) {
return state;
} else if (value > c) {
return left.Find(c, false);
} else {
return right.Find(c, false);
}
}
/**
* Adds a transition to this tree. If the lower-case flag is
* set, the character will be converted to lower-case before
* being added.
*
* @param c the character to transition for
* @param lowerCase the lower-case conversion flag
* @param state the state to transition to
*/
public void Add(char c, bool lowerCase, DFAState state) {
if (lowerCase) {
c = Char.ToLower(c);
}
if (value == '\0') {
this.value = c;
this.state = state;
this.left = new TransitionTree();
this.right = new TransitionTree();
} else if (value > c) {
left.Add(c, false, state);
} else {
right.Add(c, false, state);
}
}
/**
* Prints the automaton tree to the specified string buffer.
*
* @param buffer the string buffer
* @param indent the current indentation
*/
public void PrintTo(StringBuilder buffer, String indent) {
if (this.left != null) {
this.left.PrintTo(buffer, indent);
}
if (this.value != '\0') {
if (buffer.Length > 0 && buffer[buffer.Length - 1] == '\n') {
buffer.Append(indent);
}
buffer.Append(this.value);
if (this.state.value != null) {
buffer.Append(": ");
buffer.Append(this.state.value);
buffer.Append("\n");
}
this.state.tree.PrintTo(buffer, indent + " ");
}
if (this.right != null) {
this.right.PrintTo(buffer, indent);
}
}
}
}
| |
using System;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Markup.Data;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Markup.Xaml.Templates;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Styling;
using Avalonia.UnitTests;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Xml;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests.Xaml
{
public class BasicTests : XamlTestBase
{
[Fact]
public void Simple_Property_Is_Set()
{
var xaml = @"<ContentControl xmlns='https://github.com/avaloniaui' Content='Foo'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Foo", target.Content);
}
[Fact]
public void Default_Content_Property_Is_Set()
{
var xaml = @"<ContentControl xmlns='https://github.com/avaloniaui'>Foo</ContentControl>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Foo", target.Content);
}
[Fact]
public void Attached_Property_Is_Set()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' TextBlock.FontSize='21'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal(21.0, TextBlock.GetFontSize(target));
}
[Fact]
public void Attached_Property_Is_Set_On_Control_Outside_Avalonia_Namspace()
{
// Test for issue #1548
var xaml =
@"<UserControl xmlns='https://github.com/avaloniaui'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:TestControl Grid.Column='2' />
</UserControl>";
var target = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
Assert.Equal(2, Grid.GetColumn((TestControl)target.Content));
}
[Fact]
public void Attached_Property_With_Namespace_Is_Set()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'
xmlns:test='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'
test:BasicTestsAttachedPropertyHolder.Foo='Bar'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target);
Assert.Equal("Bar", BasicTestsAttachedPropertyHolder.GetFoo(target));
}
[Fact]
public void Attached_Property_Supports_Binding()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' TextBlock.FontSize='{Binding}'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
target.DataContext = 21.0;
Assert.Equal(21.0, TextBlock.GetFontSize(target));
}
}
[Fact]
public void Attached_Property_In_Panel_Is_Set()
{
var xaml = @"
<Panel xmlns='https://github.com/avaloniaui'>
<ToolTip.Tip>Foo</ToolTip.Tip>
</Panel>";
var target = AvaloniaRuntimeXamlLoader.Parse<Panel>(xaml);
Assert.Empty(target.Children);
Assert.Equal("Foo", ToolTip.GetTip(target));
}
[Fact]
public void NonExistent_Property_Throws()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui' DoesntExist='foo'/>";
XamlTestHelpers.AssertThrowsXamlException(() => AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml));
}
[Fact]
public void ContentControl_ContentTemplate_Is_Functional()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'>
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Text='Foo' />
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>";
var contentControl = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
var target = contentControl.ContentTemplate;
Assert.NotNull(target);
var txt = (TextBlock)target.Build(null);
Assert.Equal("Foo", txt.Text);
}
[Fact]
public void Named_Control_Is_Added_To_NameScope_Simple()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'>
<Button Name='button'>Foo</Button>
</UserControl>";
var control = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
var button = control.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
[Fact]
public void Direct_Content_In_ItemsControl_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ItemsControl Name='items'>
<ContentControl>Foo</ContentControl>
<ContentControl>Bar</ContentControl>
</ItemsControl>
</Window>";
var control = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var itemsControl = control.FindControl<ItemsControl>("items");
Assert.NotNull(itemsControl);
var items = itemsControl.Items.Cast<ContentControl>().ToArray();
Assert.Equal("Foo", items[0].Content);
Assert.Equal("Bar", items[1].Content);
}
}
[Fact]
public void Panel_Children_Are_Added()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'>
<Panel Name='panel'>
<ContentControl Name='Foo' />
<ContentControl Name='Bar' />
</Panel>
</UserControl>";
var control = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
var panel = control.FindControl<Panel>("panel");
Assert.Equal(2, panel.Children.Count);
var foo = control.FindControl<ContentControl>("Foo");
var bar = control.FindControl<ContentControl>("Bar");
Assert.Contains(foo, panel.Children);
Assert.Contains(bar, panel.Children);
}
[Fact]
public void Grid_Row_Col_Definitions_Are_Built()
{
var xaml = @"
<Grid xmlns='https://github.com/avaloniaui'>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='100' />
<ColumnDefinition Width='Auto' />
<ColumnDefinition Width='*' />
<ColumnDefinition Width='100*' />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='100' />
<RowDefinition Height='Auto' />
<RowDefinition Height='*' />
<RowDefinition Height='100*' />
</Grid.RowDefinitions>
</Grid>";
var grid = AvaloniaRuntimeXamlLoader.Parse<Grid>(xaml);
Assert.Equal(4, grid.ColumnDefinitions.Count);
Assert.Equal(4, grid.RowDefinitions.Count);
var expected1 = new GridLength(100);
var expected2 = GridLength.Auto;
var expected3 = new GridLength(1, GridUnitType.Star);
var expected4 = new GridLength(100, GridUnitType.Star);
Assert.Equal(expected1, grid.ColumnDefinitions[0].Width);
Assert.Equal(expected2, grid.ColumnDefinitions[1].Width);
Assert.Equal(expected3, grid.ColumnDefinitions[2].Width);
Assert.Equal(expected4, grid.ColumnDefinitions[3].Width);
Assert.Equal(expected1, grid.RowDefinitions[0].Height);
Assert.Equal(expected2, grid.RowDefinitions[1].Height);
Assert.Equal(expected3, grid.RowDefinitions[2].Height);
Assert.Equal(expected4, grid.RowDefinitions[3].Height);
}
[Fact]
public void Grid_Row_Col_Definitions_Are_Parsed()
{
var xaml = @"
<Grid xmlns='https://github.com/avaloniaui'
ColumnDefinitions='100,Auto,*,100*'
RowDefinitions='100,Auto,*,100*'>
</Grid>";
var grid = AvaloniaRuntimeXamlLoader.Parse<Grid>(xaml);
Assert.Equal(4, grid.ColumnDefinitions.Count);
Assert.Equal(4, grid.RowDefinitions.Count);
var expected1 = new GridLength(100);
var expected2 = GridLength.Auto;
var expected3 = new GridLength(1, GridUnitType.Star);
var expected4 = new GridLength(100, GridUnitType.Star);
Assert.Equal(expected1, grid.ColumnDefinitions[0].Width);
Assert.Equal(expected2, grid.ColumnDefinitions[1].Width);
Assert.Equal(expected3, grid.ColumnDefinitions[2].Width);
Assert.Equal(expected4, grid.ColumnDefinitions[3].Width);
Assert.Equal(expected1, grid.RowDefinitions[0].Height);
Assert.Equal(expected2, grid.RowDefinitions[1].Height);
Assert.Equal(expected3, grid.RowDefinitions[2].Height);
Assert.Equal(expected4, grid.RowDefinitions[3].Height);
}
[Fact]
public void ControlTemplate_With_Nested_Child_Is_Operational()
{
var xaml = @"
<ControlTemplate xmlns='https://github.com/avaloniaui'>
<ContentControl Name='parent'>
<ContentControl Name='child' />
</ContentControl>
</ControlTemplate>
";
var template = AvaloniaRuntimeXamlLoader.Parse<ControlTemplate>(xaml);
var parent = (ContentControl)template.Build(new ContentControl()).Control;
Assert.Equal("parent", parent.Name);
var child = parent.Content as ContentControl;
Assert.NotNull(child);
Assert.Equal("child", child.Name);
}
[Fact]
public void ControlTemplate_With_TargetType_Is_Operational()
{
var xaml = @"
<ControlTemplate xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
TargetType='{x:Type ContentControl}'>
<ContentPresenter Content='{TemplateBinding Content}' />
</ControlTemplate>
";
var template = AvaloniaRuntimeXamlLoader.Parse<ControlTemplate>(xaml);
Assert.Equal(typeof(ContentControl), template.TargetType);
Assert.IsType(typeof(ContentPresenter), template.Build(new ContentControl()).Control);
}
[Fact]
public void ControlTemplate_With_Panel_Children_Are_Added()
{
var xaml = @"
<ControlTemplate xmlns='https://github.com/avaloniaui'>
<Panel Name='panel'>
<ContentControl Name='Foo' />
<ContentControl Name='Bar' />
</Panel>
</ControlTemplate>
";
var template = AvaloniaRuntimeXamlLoader.Parse<ControlTemplate>(xaml);
var panel = (Panel)template.Build(new ContentControl()).Control;
Assert.Equal(2, panel.Children.Count);
var foo = panel.Children[0];
var bar = panel.Children[1];
Assert.Equal("Foo", foo.Name);
Assert.Equal("Bar", bar.Name);
}
[Fact]
public void Named_x_Control_Is_Added_To_NameScope_Simple()
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Button x:Name='button'>Foo</Button>
</UserControl>";
var control = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
var button = control.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
[Fact]
public void Standart_TypeConverter_Is_Used()
{
var xaml = @"<UserControl xmlns='https://github.com/avaloniaui' Width='200.5' />";
var control = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
Assert.Equal(200.5, control.Width);
}
[Fact]
public void Avalonia_TypeConverter_Is_Used()
{
var xaml = @"<UserControl xmlns='https://github.com/avaloniaui' Background='White' />";
var control = AvaloniaRuntimeXamlLoader.Parse<UserControl>(xaml);
var bk = control.Background;
Assert.IsType<ImmutableSolidColorBrush>(bk);
Assert.Equal(Colors.White, (bk as ISolidColorBrush).Color);
}
[Fact]
public void Simple_Style_Is_Parsed()
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Style Selector='TextBlock'>
<Setter Property='Background' Value='White'/>
<Setter Property='Width' Value='100'/>
</Style>
</Styles>";
var styles = AvaloniaRuntimeXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Equal(2, setters.Length);
Assert.Equal(TextBlock.BackgroundProperty, setters[0].Property);
Assert.Equal(Brushes.White.Color, ((ISolidColorBrush)setters[0].Value).Color);
Assert.Equal(TextBlock.WidthProperty, setters[1].Property);
Assert.Equal(100.0, setters[1].Value);
}
[Fact]
public void Style_Setter_With_AttachedProperty_Is_Parsed()
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Style Selector='ContentControl'>
<Setter Property='TextBlock.FontSize' Value='21'/>
</Style>
</Styles>";
var styles = AvaloniaRuntimeXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Single(setters);
Assert.Equal(TextBlock.FontSizeProperty, setters[0].Property);
Assert.Equal(21.0, setters[0].Value);
}
[Fact]
public void Complex_Style_Is_Parsed()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'>
<Style Selector='CheckBox'>
<Setter Property='BorderBrush' Value='{DynamicResource ThemeBorderMidBrush}'/>
<Setter Property='BorderThickness' Value='{DynamicResource ThemeBorderThickness}'/>
<Setter Property='Template'>
<ControlTemplate>
<Grid ColumnDefinitions='Auto,*'>
<Border Name='border'
BorderBrush='{TemplateBinding BorderBrush}'
BorderThickness='{TemplateBinding BorderThickness}'
Width='18'
Height='18'
VerticalAlignment='Center'>
<Path Name='checkMark'
Fill='{StaticResource HighlightBrush}'
Width='11'
Height='10'
Stretch='Uniform'
HorizontalAlignment='Center'
VerticalAlignment='Center'
Data='M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z'/>
</Border>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'
ContentTemplate='{TemplateBinding ContentTemplate}'
Margin='4,0,0,0'
VerticalAlignment='Center'
Grid.Column='1'/>
</Grid>
</ControlTemplate>
</Setter>
</Style>
</Styles>
";
var styles = AvaloniaRuntimeXamlLoader.Parse<Styles>(xaml);
Assert.Single(styles);
var style = (Style)styles[0];
var setters = style.Setters.Cast<Setter>().ToArray();
Assert.Equal(3, setters.Length);
Assert.Equal(CheckBox.BorderBrushProperty, setters[0].Property);
Assert.Equal(CheckBox.BorderThicknessProperty, setters[1].Property);
Assert.Equal(CheckBox.TemplateProperty, setters[2].Property);
Assert.IsType<ControlTemplate>(setters[2].Value);
}
}
[Fact]
public void Style_Resources_Are_Built()
{
var xaml = @"
<Style xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:sys='clr-namespace:System;assembly=netstandard'>
<Style.Resources>
<SolidColorBrush x:Key='Brush'>White</SolidColorBrush>
<sys:Double x:Key='Double'>10</sys:Double>
</Style.Resources>
</Style>";
var style = AvaloniaRuntimeXamlLoader.Parse<Style>(xaml);
Assert.True(style.Resources.Count > 0);
style.TryGetResource("Brush", out var brush);
Assert.NotNull(brush);
Assert.IsAssignableFrom<ISolidColorBrush>(brush);
Assert.Equal(Colors.White, ((ISolidColorBrush)brush).Color);
style.TryGetResource("Double", out var d);
Assert.Equal(10.0, d);
}
[Fact]
public void StyleInclude_Is_Built()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<StyleInclude Source='resm:Avalonia.Themes.Default.ContextMenu.xaml?assembly=Avalonia.Themes.Default'/>
</Styles>";
var styles = AvaloniaRuntimeXamlLoader.Parse<Styles>(xaml);
Assert.True(styles.Count == 1);
var styleInclude = styles.First() as StyleInclude;
Assert.NotNull(styleInclude);
var style = styleInclude.Loaded;
Assert.NotNull(style);
}
}
[Fact]
public void Simple_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' Content='{Binding}'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.Null(target.Content);
target.DataContext = "Foo";
Assert.Equal("Foo", target.Content);
}
}
[Fact]
public void Double_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml =
@"<Window xmlns='https://github.com/avaloniaui' Width='{Binding}'/>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.Null(target.Content);
target.DataContext = 55.0;
Assert.Equal(55.0, target.Width);
}
}
[Fact]
public void Collection_Xaml_Binding_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ItemsControl Name='itemsControl' Items='{Binding}'>
</ItemsControl>
</Window>
";
var target = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
Assert.NotNull(target.Content);
var itemsControl = target.FindControl<ItemsControl>("itemsControl");
var items = new string[] { "Foo", "Bar" };
//DelayedBinding.ApplyBindings(itemsControl);
target.DataContext = items;
Assert.Equal(items, itemsControl.Items);
}
}
[Fact]
public void Multi_Xaml_Binding_Is_Parsed()
{
var xaml =
@"<MultiBinding xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
Converter ='{x:Static BoolConverters.And}'>
<Binding Path='Foo' />
<Binding Path='Bar' />
</MultiBinding>";
var target = AvaloniaRuntimeXamlLoader.Parse<MultiBinding>(xaml);
Assert.Equal(2, target.Bindings.Count);
Assert.Equal(BoolConverters.And, target.Converter);
var bindings = target.Bindings.Cast<Binding>().ToArray();
Assert.Equal("Foo", bindings[0].Path);
Assert.Equal("Bar", bindings[1].Path);
}
[Fact]
public void Control_Template_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper
.With(windowingPlatform: new MockWindowingPlatform())))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Template>
<ControlTemplate TargetType='Window'>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'/>
</ControlTemplate>
</Window.Template>
</Window>";
var target = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.NotNull(target.Template);
Assert.Null(target.Presenter);
target.ApplyTemplate();
Assert.NotNull(target.Presenter);
target.Content = "Foo";
Assert.Equal("Foo", target.Presenter.Content);
}
}
[Fact]
public void Style_ControlTemplate_Is_Built()
{
var xaml = @"
<Style xmlns='https://github.com/avaloniaui' Selector='ContentControl'>
<Setter Property='Template'>
<ControlTemplate>
<ContentPresenter Name='PART_ContentPresenter'
Content='{TemplateBinding Content}'
ContentTemplate='{TemplateBinding ContentTemplate}' />
</ControlTemplate>
</Setter>
</Style> ";
var style = AvaloniaRuntimeXamlLoader.Parse<Style>(xaml);
Assert.Single(style.Setters);
var setter = (Setter)style.Setters.First();
Assert.Equal(ContentControl.TemplateProperty, setter.Property);
Assert.IsType<ControlTemplate>(setter.Value);
var template = (ControlTemplate)setter.Value;
var control = new ContentControl();
var result = (ContentPresenter)template.Build(control).Control;
Assert.NotNull(result);
}
[Fact]
public void Named_Control_Is_Added_To_NameScope()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Button Name='button'>Foo</Button>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var button = window.FindControl<Button>("button");
Assert.Equal("Foo", button.Content);
}
}
[Fact]
public void Control_Is_Added_To_Parent_Before_Properties_Are_Set()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100'/>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
var attached = tracker.Order.IndexOf("AttachedToLogicalTree");
var widthChanged = tracker.Order.IndexOf("Property Width Changed");
Assert.NotEqual(-1, attached);
Assert.NotEqual(-1, widthChanged);
Assert.True(attached < widthChanged);
}
}
[Fact]
public void Control_Is_Added_To_Parent_Before_Final_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100'/>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
var attached = tracker.Order.IndexOf("AttachedToLogicalTree");
var endInit = tracker.Order.IndexOf("EndInit 0");
Assert.NotEqual(-1, attached);
Assert.NotEqual(-1, endInit);
Assert.True(attached < endInit);
}
}
[Fact]
public void All_Properties_Are_Set_Before_Final_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker Width='100' Height='100'
Tag='{Binding Height, RelativeSource={RelativeSource Self}}' />
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
//ensure binding is set and operational first
Assert.Equal(100.0, tracker.Tag);
Assert.Equal("EndInit 0", tracker.Order.Last());
}
}
[Fact]
public void BeginInit_Matches_EndInit()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<local:InitializationOrderTracker />
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var tracker = (InitializationOrderTracker)window.Content;
Assert.Equal(0, tracker.InitState);
}
}
[Fact]
public void DeferedXamlLoader_Should_Preserve_NamespacesContext()
{
var xaml =
@"<ContentControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Tag='{x:Static local:NonControl.StringProperty}'/>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>";
var contentControl = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
var template = contentControl.ContentTemplate;
Assert.NotNull(template);
var txt = (TextBlock)template.Build(null);
Assert.Equal((object)NonControl.StringProperty, txt.Tag);
}
[Fact]
public void Binding_To_List_AvaloniaProperty_Is_Operational()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<ListBox Items='{Binding Items}' SelectedItems='{Binding SelectedItems}'/>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var listBox = (ListBox)window.Content;
var vm = new SelectedItemsViewModel()
{
Items = new string[] { "foo", "bar", "baz" }
};
window.DataContext = vm;
Assert.Equal(vm.Items, listBox.Items);
Assert.Equal(vm.SelectedItems, listBox.SelectedItems);
}
}
[Fact]
public void Element_Whitespace_Should_Be_Trimmed()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<TextBlock>
Hello World!
</TextBlock>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var textBlock = (TextBlock)window.Content;
Assert.Equal("Hello World!", textBlock.Text);
}
}
[Fact]
public void Design_Mode_Properties_Should_Be_Ignored_At_Runtime_And_Set_In_Design_Mode()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DataContext='data-context'
d:DesignWidth='123'
d:DesignHeight='321'
>
</Window>";
foreach (var designMode in new[] {true, false})
{
var obj = (Window)AvaloniaRuntimeXamlLoader.Load(xaml, designMode: designMode);
var context = Design.GetDataContext(obj);
var width = Design.GetWidth(obj);
var height = Design.GetHeight(obj);
if (designMode)
{
Assert.Equal("data-context", context);
Assert.Equal(123, width);
Assert.Equal(321, height);
}
else
{
Assert.False(obj.IsSet(Design.DataContextProperty));
Assert.False(obj.IsSet(Design.WidthProperty));
Assert.False(obj.IsSet(Design.HeightProperty));
}
}
}
}
[Fact]
public void Slider_Properties_Can_Be_Set_In_Any_Order()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'>
<Slider Width='400' Value='500' Minimum='0' Maximum='1000'/>
</Window>";
var window = AvaloniaRuntimeXamlLoader.Parse<Window>(xaml);
var slider = (Slider)window.Content;
Assert.Equal(0, slider.Minimum);
Assert.Equal(1000, slider.Maximum);
Assert.Equal(500, slider.Value);
}
}
private class SelectedItemsViewModel : INotifyPropertyChanged
{
public string[] Items { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private IList _selectedItems = new AvaloniaList<string>();
public IList SelectedItems
{
get { return _selectedItems; }
set
{
_selectedItems = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItems)));
}
}
}
}
public class BasicTestsAttachedPropertyHolder
{
public static AvaloniaProperty<string> FooProperty =
AvaloniaProperty.RegisterAttached<BasicTestsAttachedPropertyHolder, AvaloniaObject, string>("Foo");
public static void SetFoo(AvaloniaObject target, string value) => target.SetValue(FooProperty, value);
public static string GetFoo(AvaloniaObject target) => (string)target.GetValue(FooProperty);
}
}
| |
using System;
using Gtk;
namespace Moscrif.IDE.Controls
{
public class MessageDialog : Dialog
{
public MessageDialog()
{
InicializeComponent();
}
public MessageDialog(DialogButtonType buttons, string primaryLabel, string secondaryLabel, MessageType messageType,Gtk.Window parent)
{
InicializeComponent();
//if (parent == null) parent =MainClass.MainWindow;
if (parent != null)
TransientFor =parent;
Buttons = buttons;
PrimaryText = primaryLabel;
SecondaryText = secondaryLabel;
MessageType = messageType;
}
public MessageDialog(DialogButtonType buttons, string primaryLabel, string secondaryLabel, MessageType messageType)
{
InicializeComponent();
TransientFor = MainClass.MainWindow;
Buttons = buttons;
PrimaryText = primaryLabel;
SecondaryText = secondaryLabel;
MessageType = messageType;
}
public MessageDialog(string[] labelButtons, string primaryLabel, string secondaryLabel, MessageType messageType,Gtk.Window parent)
{
InicializeComponent();
if (parent != null)
TransientFor =parent;
else
TransientFor = MainClass.MainWindow;
Buttons = buttons;
PrimaryText = primaryLabel;
SecondaryText = secondaryLabel;
MessageType = messageType;
Widget[] oldButtons = ActionArea.Children;
foreach (Widget w in oldButtons)
ActionArea.Remove(w);
int i =1;
foreach (string s in labelButtons){
AddButton(s,-i);
i++;
}
}
public int ShowDialog(){
int result = this.Run();
this.Destroy();
return result;
}
private void InicializeComponent()
{
Resizable = false;
HasSeparator = false;
BorderWidth = 12;
//Modal = true;
label = new Label();
label.LineWrap = true;
label.Selectable = true;
label.UseMarkup = true;
label.SetAlignment(0.0f, 0.0f);
secondaryLabel = new Label();
secondaryLabel.LineWrap = true;
secondaryLabel.Selectable = true;
secondaryLabel.UseMarkup = true;
secondaryLabel.SetAlignment(0.0f, 0.0f);
icon = new Image(Stock.DialogInfo, IconSize.Dialog);
icon.SetAlignment(0.5f, 0.0f);
StockItem item = Stock.Lookup(icon.Stock);
Title = item.Label;
HBox hbox = new HBox(false, 12);
VBox vbox = new VBox(false, 12);
vbox.PackStart(label, false, false, 0);
vbox.PackStart(secondaryLabel, true, true, 0);
hbox.PackStart(icon, false, false, 0);
hbox.PackStart(vbox, true, true, 0);
VBox.PackStart(hbox, false, false, 0);
hbox.ShowAll();
Buttons = MessageDialog.DialogButtonType.OkCancel;
}
Label label, secondaryLabel;
Image icon;
public MessageType MessageType
{
get {
if (icon.Stock == Stock.DialogInfo)
return MessageType.Info; else if (icon.Stock == Stock.DialogQuestion)
return MessageType.Question; else if (icon.Stock == Stock.DialogWarning)
return MessageType.Warning;
else
return MessageType.Error;
}
set {
StockItem item = Stock.Lookup(icon.Stock);
bool setTitle = (Title == "") || (Title == item.Label);
if (value == MessageType.Info)
icon.Stock = Stock.DialogInfo; else if (value == MessageType.Question)
icon.Stock = Stock.DialogQuestion; else if (value == MessageType.Warning)
icon.Stock = Stock.DialogWarning;
else
icon.Stock = Stock.DialogError;
if (setTitle) {
item = Stock.Lookup(icon.Stock);
Title = item.Label;
}
}
}
public string primaryText;
public string PrimaryText
{
get { return primaryText; }
set {
primaryText = value;
label.Markup = "<b>" + value + "</b>";
}
}
public string SecondaryText
{
get { return secondaryLabel.Text; }
set { secondaryLabel.Markup = value; }
}
DialogButtonType buttons;
public DialogButtonType Buttons
{
get { return buttons; }
set {
Widget[] oldButtons = ActionArea.Children;
foreach (Widget w in oldButtons)
ActionArea.Remove(w);
buttons = value;
switch (buttons) {
case DialogButtonType.None:
// nothing
break;
case DialogButtonType.Ok:
AddButton(Stock.Ok, ResponseType.Ok);
break;
case DialogButtonType.Close:
AddButton(Stock.Close, ResponseType.Close);
break;
case DialogButtonType.Cancel:
AddButton(Stock.Cancel, ResponseType.Cancel);
break;
case DialogButtonType.YesNo:
AddButton(Stock.No, ResponseType.No);
AddButton(Stock.Yes, ResponseType.Yes);
break;
case DialogButtonType.OkCancel:
AddButton(Stock.Cancel, ResponseType.Cancel);
AddButton(Stock.Ok, ResponseType.Ok);
break;
case DialogButtonType.YesNoCancel:
AddButton(Stock.Cancel, ResponseType.Cancel);
AddButton(Stock.No, ResponseType.No);
AddButton(Stock.Yes, ResponseType.Yes);
break;
}
}
}
public enum DialogButtonType
{
None,
Ok,
Close,
Cancel,
YesNo,
OkCancel,
YesNoCancel
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.XPath
{
/// <summary>
/// Reader that traverses the subtree rooted at the current position of the specified navigator.
/// </summary>
internal class XPathNavigatorReader : XmlReader, IXmlNamespaceResolver
{
enum State
{
Initial,
Content,
EndElement,
Attribute,
AttrVal,
InReadBinary,
EOF,
Closed,
Error,
}
private XPathNavigator _nav;
private XPathNavigator _navToRead;
private int _depth;
private State _state;
private XmlNodeType _nodeType;
private int _attrCount;
private bool _readEntireDocument;
private ReadContentAsBinaryHelper _readBinaryHelper;
private State _savedState;
internal const string space = "space";
internal static XmlNodeType[] convertFromXPathNodeType = {
XmlNodeType.Document, // XPathNodeType.Root
XmlNodeType.Element, // XPathNodeType.Element
XmlNodeType.Attribute, // XPathNodeType.Attribute
XmlNodeType.Attribute, // XPathNodeType.Namespace
XmlNodeType.Text, // XPathNodeType.Text
XmlNodeType.SignificantWhitespace, // XPathNodeType.SignificantWhitespace
XmlNodeType.Whitespace, // XPathNodeType.Whitespace
XmlNodeType.ProcessingInstruction, // XPathNodeType.ProcessingInstruction
XmlNodeType.Comment, // XPathNodeType.Comment
XmlNodeType.None // XPathNodeType.All
};
/// <summary>
/// Translates an XPathNodeType value into the corresponding XmlNodeType value.
/// XPathNodeType.Whitespace and XPathNodeType.SignificantWhitespace are mapped into XmlNodeType.Text.
/// </summary>
internal static XmlNodeType ToXmlNodeType(XPathNodeType typ)
{
return XPathNavigatorReader.convertFromXPathNodeType[(int)typ];
}
static public XPathNavigatorReader Create(XPathNavigator navToRead)
{
XPathNavigator nav = navToRead.Clone();
return new XPathNavigatorReader(nav);
}
protected XPathNavigatorReader(XPathNavigator navToRead)
{
// Need clone that can be moved independently of original navigator
_navToRead = navToRead;
_nav = XmlEmptyNavigator.Singleton;
_state = State.Initial;
_depth = 0;
_nodeType = XPathNavigatorReader.ToXmlNodeType(_nav.NodeType);
}
//-----------------------------------------------
// IXmlNamespaceResolver -- pass through to Navigator
//-----------------------------------------------
public override XmlNameTable NameTable
{
get
{
return _navToRead.NameTable;
}
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _nav.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _nav.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _nav.LookupPrefix(namespaceName);
}
//-----------------------------------------------
// XmlReader -- pass through to Navigator
//-----------------------------------------------
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.NameTable = this.NameTable;
rs.ConformanceLevel = ConformanceLevel.Fragment;
rs.CheckCharacters = false;
return rs;
}
}
public override System.Type ValueType
{
get { return _nav.ValueType; }
}
public override XmlNodeType NodeType
{
get { return _nodeType; }
}
public override string NamespaceURI
{
get
{
//NamespaceUri for namespace nodes is different in case of XPathNavigator and Reader
if (_nav.NodeType == XPathNodeType.Namespace)
return this.NameTable.Add(XmlConst.ReservedNsXmlNs);
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.NamespaceURI;
}
}
public override string LocalName
{
get
{
//Default namespace in case of reader has a local name value of 'xmlns'
if (_nav.NodeType == XPathNodeType.Namespace && _nav.LocalName.Length == 0)
return this.NameTable.Add("xmlns");
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.LocalName;
}
}
public override string Prefix
{
get
{
//Prefix for namespace nodes is different in case of XPathNavigator and Reader
if (_nav.NodeType == XPathNodeType.Namespace && _nav.LocalName.Length != 0)
return this.NameTable.Add("xmlns");
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.Prefix;
}
}
public override string BaseURI
{
get
{
//reader returns BaseUri even before read method is called.
if (_state == State.Initial)
return _navToRead.BaseURI;
return _nav.BaseURI;
}
}
public override bool IsEmptyElement
{
get
{
return _nav.IsEmptyElement;
}
}
public override XmlSpace XmlSpace
{
get
{
XPathNavigator tempNav = _nav.Clone();
do
{
if (tempNav.MoveToAttribute(XPathNavigatorReader.space, XmlConst.ReservedNsXml))
{
switch (XmlConvertEx.TrimString(tempNav.Value))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
break;
}
tempNav.MoveToParent();
}
}
while (tempNav.MoveToParent());
return XmlSpace.None;
}
}
public override string XmlLang
{
get
{
return _nav.XmlLang;
}
}
public override bool HasValue
{
get
{
if ((_nodeType != XmlNodeType.Element)
&& (_nodeType != XmlNodeType.Document)
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.None))
return true;
return false;
}
}
public override string Value
{
get
{
if ((_nodeType != XmlNodeType.Element)
&& (_nodeType != XmlNodeType.Document)
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.None))
return _nav.Value;
return string.Empty;
}
}
private XPathNavigator GetElemNav()
{
XPathNavigator tempNav;
switch (_state)
{
case State.Content:
return _nav.Clone();
case State.Attribute:
case State.AttrVal:
tempNav = _nav.Clone();
if (tempNav.MoveToParent())
return tempNav;
break;
case State.InReadBinary:
_state = _savedState;
XPathNavigator nav = GetElemNav();
_state = State.InReadBinary;
return nav;
}
return null;
}
private XPathNavigator GetElemNav(out int depth)
{
XPathNavigator nav = null;
switch (_state)
{
case State.Content:
if (_nodeType == XmlNodeType.Element)
nav = _nav.Clone();
depth = _depth;
break;
case State.Attribute:
nav = _nav.Clone();
nav.MoveToParent();
depth = _depth - 1;
break;
case State.AttrVal:
nav = _nav.Clone();
nav.MoveToParent();
depth = _depth - 2;
break;
case State.InReadBinary:
_state = _savedState;
nav = GetElemNav(out depth);
_state = State.InReadBinary;
break;
default:
depth = _depth;
break;
}
return nav;
}
private void MoveToAttr(XPathNavigator nav, int depth)
{
_nav.MoveTo(nav);
_depth = depth;
_nodeType = XmlNodeType.Attribute;
_state = State.Attribute;
}
public override int AttributeCount
{
get
{
if (_attrCount < 0)
{
// attribute count works for element, regardless of where you are in start tag
XPathNavigator tempNav = GetElemNav();
int count = 0;
if (null != tempNav)
{
if (tempNav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
count++;
} while (tempNav.MoveToNextNamespace((XPathNamespaceScope.Local)));
tempNav.MoveToParent();
}
if (tempNav.MoveToFirstAttribute())
{
do
{
count++;
} while (tempNav.MoveToNextAttribute());
}
}
_attrCount = count;
}
return _attrCount;
}
}
public override string GetAttribute(string name)
{
// reader allows calling GetAttribute, even when positioned inside attributes
XPathNavigator nav = _nav;
switch (nav.NodeType)
{
case XPathNodeType.Element:
break;
case XPathNodeType.Attribute:
nav = nav.Clone();
if (!nav.MoveToParent())
return null;
break;
default:
return null;
}
string prefix, localname;
ValidateNames.SplitQName(name, out prefix, out localname);
if (0 == prefix.Length)
{
if (localname == "xmlns")
return nav.GetNamespace(string.Empty);
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToAttribute(localname, string.Empty))
return nav.Value;
}
else
{
if (prefix == "xmlns")
return nav.GetNamespace(localname);
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToFirstAttribute())
{
do
{
if (nav.LocalName == localname && nav.Prefix == prefix)
return nav.Value;
} while (nav.MoveToNextAttribute());
}
}
return null;
}
public override string GetAttribute(string localName, string namespaceURI)
{
if (null == localName)
throw new ArgumentNullException("localName");
// reader allows calling GetAttribute, even when positioned inside attributes
XPathNavigator nav = _nav;
switch (nav.NodeType)
{
case XPathNodeType.Element:
break;
case XPathNodeType.Attribute:
nav = nav.Clone();
if (!nav.MoveToParent())
return null;
break;
default:
return null;
}
// are they really looking for a namespace-decl?
if (namespaceURI == XmlConst.ReservedNsXmlNs)
{
if (localName == "xmlns")
localName = string.Empty;
return nav.GetNamespace(localName);
}
if (null == namespaceURI)
namespaceURI = string.Empty;
// We need to clone the navigator and move the clone to the attribute to see whether the attribute exists,
// because XPathNavigator.GetAttribute return string.Empty for both when the the attribute is not there or when
// it has an empty value. XmlReader.GetAttribute must return null if the attribute does not exist.
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToAttribute(localName, namespaceURI))
{
return nav.Value;
}
else
{
return null;
}
}
private static string GetNamespaceByIndex(XPathNavigator nav, int index, out int count)
{
string thisValue = nav.Value;
string value = null;
if (nav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
value = GetNamespaceByIndex(nav, index, out count);
}
else
{
count = 0;
}
if (count == index)
{
Debug.Assert(value == null);
value = thisValue;
}
count++;
return value;
}
public override string GetAttribute(int index)
{
if (index < 0)
goto Error;
XPathNavigator nav = GetElemNav();
if (null == nav)
goto Error;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
// namespaces are returned in reverse order,
// but we want to return them in the correct order,
// so first count the namespaces
int nsCount;
string value = GetNamespaceByIndex(nav, index, out nsCount);
if (null != value)
{
return value;
}
index -= nsCount;
nav.MoveToParent();
}
if (nav.MoveToFirstAttribute())
{
do
{
if (index == 0)
return nav.Value;
index--;
} while (nav.MoveToNextAttribute());
}
// can't find it... error
Error:
throw new ArgumentOutOfRangeException("index");
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
if (null == localName)
throw new ArgumentNullException("localName");
int depth = _depth;
XPathNavigator nav = GetElemNav(out depth);
if (null != nav)
{
if (namespaceName == XmlConst.ReservedNsXmlNs)
{
if (localName == "xmlns")
localName = string.Empty;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
if (nav.LocalName == localName)
goto FoundMatch;
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
else
{
if (null == namespaceName)
namespaceName = string.Empty;
if (nav.MoveToAttribute(localName, namespaceName))
goto FoundMatch;
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToFirstAttribute()
{
int depth;
XPathNavigator nav = GetElemNav(out depth);
if (null != nav)
{
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
// attributes are in reverse order
while (nav.MoveToNextNamespace(XPathNamespaceScope.Local))
;
goto FoundMatch;
}
if (nav.MoveToFirstAttribute())
{
goto FoundMatch;
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToNextAttribute()
{
switch (_state)
{
case State.Content:
return MoveToFirstAttribute();
case State.Attribute:
{
if (XPathNodeType.Attribute == _nav.NodeType)
return _nav.MoveToNextAttribute();
// otherwise it is on a namespace... namespace are in reverse order
Debug.Assert(XPathNodeType.Namespace == _nav.NodeType);
XPathNavigator nav = _nav.Clone();
if (!nav.MoveToParent())
return false; // shouldn't happen
if (!nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
return false; // shouldn't happen
if (nav.IsSamePosition(_nav))
{
// this was the last one... start walking attributes
nav.MoveToParent();
if (!nav.MoveToFirstAttribute())
return false;
// otherwise we are there
_nav.MoveTo(nav);
return true;
}
else
{
XPathNavigator prev = nav.Clone();
for (; ;)
{
if (!nav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
Debug.Assert(false, "Couldn't find Namespace Node! Should not happen!");
return false;
}
if (nav.IsSamePosition(_nav))
{
_nav.MoveTo(prev);
return true;
}
prev.MoveTo(nav);
}
// found previous namespace position
}
}
case State.AttrVal:
_depth--;
_state = State.Attribute;
if (!MoveToNextAttribute())
{
_depth++;
_state = State.AttrVal;
return false;
}
_nodeType = XmlNodeType.Attribute;
return true;
case State.InReadBinary:
_state = _savedState;
if (!MoveToNextAttribute())
{
_state = State.InReadBinary;
return false;
}
_readBinaryHelper.Finish();
return true;
default:
return false;
}
}
public override bool MoveToAttribute(string name)
{
int depth;
XPathNavigator nav = GetElemNav(out depth);
if (null == nav)
return false;
string prefix, localname;
ValidateNames.SplitQName(name, out prefix, out localname);
// watch for a namespace name
bool IsXmlnsNoPrefix = false;
if ((IsXmlnsNoPrefix = (0 == prefix.Length && localname == "xmlns"))
|| (prefix == "xmlns"))
{
if (IsXmlnsNoPrefix)
localname = string.Empty;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
if (nav.LocalName == localname)
goto FoundMatch;
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
else if (0 == prefix.Length)
{
// the empty prefix always means empty namespaceUri for attributes
if (nav.MoveToAttribute(localname, string.Empty))
goto FoundMatch;
}
else
{
if (nav.MoveToFirstAttribute())
{
do
{
if (nav.LocalName == localname && nav.Prefix == prefix)
goto FoundMatch;
} while (nav.MoveToNextAttribute());
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToElement()
{
switch (_state)
{
case State.Attribute:
case State.AttrVal:
if (!_nav.MoveToParent())
return false;
_depth--;
if (_state == State.AttrVal)
_depth--;
_state = State.Content;
_nodeType = XmlNodeType.Element;
return true;
case State.InReadBinary:
_state = _savedState;
if (!MoveToElement())
{
_state = State.InReadBinary;
return false;
}
_readBinaryHelper.Finish();
break;
}
return false;
}
public override bool EOF
{
get
{
return _state == State.EOF;
}
}
public override ReadState ReadState
{
get
{
switch (_state)
{
case State.Initial:
return ReadState.Initial;
case State.Content:
case State.EndElement:
case State.Attribute:
case State.AttrVal:
case State.InReadBinary:
return ReadState.Interactive;
case State.EOF:
return ReadState.EndOfFile;
case State.Closed:
return ReadState.Closed;
default:
return ReadState.Error;
}
}
}
public override void ResolveEntity()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override bool ReadAttributeValue()
{
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
if (_state == State.Attribute)
{
_state = State.AttrVal;
_nodeType = XmlNodeType.Text;
_depth++;
return true;
}
return false;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override string LookupNamespace(string prefix)
{
return _nav.LookupNamespace(prefix);
}
/// <summary>
/// Current depth in subtree.
/// </summary>
public override int Depth
{
get { return _depth; }
}
/// <summary>
/// Move to the next reader state. Return false if that is ReaderState.Closed.
/// </summary>
public override bool Read()
{
_attrCount = -1;
switch (_state)
{
case State.Error:
case State.Closed:
case State.EOF:
return false;
case State.Initial:
// Starting state depends on the navigator's item type
_nav = _navToRead;
_state = State.Content;
if (XPathNodeType.Root == _nav.NodeType)
{
if (!_nav.MoveToFirstChild())
{
SetEOF();
return false;
}
_readEntireDocument = true;
}
else if (XPathNodeType.Attribute == _nav.NodeType)
{
_state = State.Attribute;
}
_nodeType = ToXmlNodeType(_nav.NodeType);
break;
case State.Content:
if (_nav.MoveToFirstChild())
{
_nodeType = ToXmlNodeType(_nav.NodeType);
_depth++;
_state = State.Content;
}
else if (_nodeType == XmlNodeType.Element
&& !_nav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
_state = State.EndElement;
}
else
goto case State.EndElement;
break;
case State.EndElement:
if (0 == _depth && !_readEntireDocument)
{
SetEOF();
return false;
}
else if (_nav.MoveToNext())
{
_nodeType = ToXmlNodeType(_nav.NodeType);
_state = State.Content;
}
else if (_depth > 0 && _nav.MoveToParent())
{
Debug.Assert(_nav.NodeType == XPathNodeType.Element, _nav.NodeType.ToString() + " == XPathNodeType.Element");
_nodeType = XmlNodeType.EndElement;
_state = State.EndElement;
_depth--;
}
else
{
SetEOF();
return false;
}
break;
case State.Attribute:
case State.AttrVal:
if (!_nav.MoveToParent())
{
SetEOF();
return false;
}
_nodeType = ToXmlNodeType(_nav.NodeType);
_depth--;
if (_state == State.AttrVal)
_depth--;
goto case State.Content;
case State.InReadBinary:
_state = _savedState;
_readBinaryHelper.Finish();
return Read();
}
return true;
}
/// <summary>
/// set reader to EOF state
/// </summary>
private void SetEOF()
{
_nav = XmlEmptyNavigator.Singleton;
_nodeType = XmlNodeType.None;
_state = State.EOF;
_depth = 0;
}
}
/// <summary>
/// The XmlEmptyNavigator exposes a document node with no children.
/// Only one XmlEmptyNavigator exists per AppDomain (Singleton). That's why the constructor is private.
/// Use the Singleton property to get the EmptyNavigator.
/// </summary>
internal class XmlEmptyNavigator : XPathNavigator
{
private static volatile XmlEmptyNavigator s_singleton;
private XmlEmptyNavigator()
{
}
public static XmlEmptyNavigator Singleton
{
get
{
if (XmlEmptyNavigator.s_singleton == null)
XmlEmptyNavigator.s_singleton = new XmlEmptyNavigator();
return XmlEmptyNavigator.s_singleton;
}
}
//-----------------------------------------------
// XmlReader
//-----------------------------------------------
public override XPathNodeType NodeType
{
get { return XPathNodeType.All; }
}
public override string NamespaceURI
{
get { return string.Empty; }
}
public override string LocalName
{
get { return string.Empty; }
}
public override string Name
{
get { return string.Empty; }
}
public override string Prefix
{
get { return string.Empty; }
}
public override string BaseURI
{
get { return string.Empty; }
}
public override string Value
{
get { return string.Empty; }
}
public override bool IsEmptyElement
{
get { return false; }
}
public override string XmlLang
{
get { return string.Empty; }
}
public override bool HasAttributes
{
get { return false; }
}
public override bool HasChildren
{
get { return false; }
}
//-----------------------------------------------
// IXmlNamespaceResolver
//-----------------------------------------------
public override XmlNameTable NameTable
{
get { return new NameTable(); }
}
public override bool MoveToFirstChild()
{
return false;
}
public override void MoveToRoot()
{
//always on root
return;
}
public override bool MoveToNext()
{
return false;
}
public override bool MoveToPrevious()
{
return false;
}
public override bool MoveToFirst()
{
return false;
}
public override bool MoveToFirstAttribute()
{
return false;
}
public override bool MoveToNextAttribute()
{
return false;
}
public override bool MoveToId(string id)
{
return false;
}
public override string GetAttribute(string localName, string namespaceName)
{
return null;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
return false;
}
public override string GetNamespace(string name)
{
return null;
}
public override bool MoveToNamespace(string prefix)
{
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
return false;
}
public override bool MoveToParent()
{
return false;
}
public override bool MoveTo(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return (object)this == (object)other;
}
public override XmlNodeOrder ComparePosition(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return ((object)this == (object)other) ? XmlNodeOrder.Same : XmlNodeOrder.Unknown;
}
public override bool IsSamePosition(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return (object)this == (object)other;
}
//-----------------------------------------------
// XPathNavigator2
//-----------------------------------------------
public override XPathNavigator Clone()
{
// Singleton, so clone just returns this
return this;
}
}
}
| |
using System;
using NUnit.Framework;
using Whois.Parsers;
namespace Whois.Parsing.Whois.Sgnic.Sg.Sg
{
[TestFixture]
public class SgParsingTests : ParsingTests
{
private WhoisParser parser;
[SetUp]
public void SetUp()
{
SerilogConfig.Init();
parser = new WhoisParser();
}
[Test]
public void Test_found()
{
var sample = SampleReader.Read("whois.sgnic.sg", "sg", "found.txt");
var response = parser.Parse("whois.sgnic.sg", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.sgnic.sg/sg/Found01", response.TemplateName);
Assert.AreEqual("google.sg", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("MARKMONITOR INC", response.Registrar.Name);
Assert.AreEqual(new DateTime(2005, 01, 03, 12, 00, 00, 000, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2011, 01, 03, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("GOOGLE INC.", response.Registrant.Name);
Assert.AreEqual("+1.6503300100", response.Registrant.TelephoneNumber);
Assert.AreEqual("+1.6506181434", response.Registrant.FaxNumber);
Assert.AreEqual("dns-admin@google.com", response.Registrant.Email);
// Registrant Address
Assert.AreEqual(4, response.Registrant.Address.Count);
Assert.AreEqual("1600 AMPHITHEATRE PARKWAY", response.Registrant.Address[0]);
Assert.AreEqual("CA", response.Registrant.Address[1]);
Assert.AreEqual("US", response.Registrant.Address[2]);
Assert.AreEqual("94043", response.Registrant.Address[3]);
// Domain Status
Assert.AreEqual(4, response.DomainStatus.Count);
Assert.AreEqual("OK", response.DomainStatus[0]);
Assert.AreEqual("CLIENT UPDATE PROHIBITED", response.DomainStatus[1]);
Assert.AreEqual("CLIENT TRANSFER PROHIBITED", response.DomainStatus[2]);
Assert.AreEqual("CLIENT DELETE PROHIBITED", response.DomainStatus[3]);
Assert.AreEqual(18, response.FieldsParsed);
}
[Test]
public void Test_found_nameservers_schema_1_with_ip()
{
var sample = SampleReader.Read("whois.sgnic.sg", "sg", "found_nameservers_schema_1_with_ip.txt");
var response = parser.Parse("whois.sgnic.sg", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
AssertWriter.Write(response);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.sgnic.sg/sg/Found01", response.TemplateName);
Assert.AreEqual("canon.com.sg", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("SINGNET PTE LTD", response.Registrar.Name);
Assert.AreEqual(new DateTime(1996, 01, 09, 00, 00, 00, 000, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2012, 01, 09, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("CANON SINGAPORE PTE. LTD.", response.Registrant.Name);
Assert.AreEqual("67845922", response.Registrant.TelephoneNumber);
Assert.AreEqual("64753273", response.Registrant.FaxNumber);
Assert.AreEqual("hostmaster@singnet.com.sg", response.Registrant.Email);
// Registrant Address
Assert.AreEqual(3, response.Registrant.Address.Count);
Assert.AreEqual("1 HarbourFront Avenue", response.Registrant.Address[0]);
Assert.AreEqual("SG", response.Registrant.Address[1]);
Assert.AreEqual("098632", response.Registrant.Address[2]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("OK", response.DomainStatus[0]);
Assert.AreEqual(14, response.FieldsParsed);
}
[Test]
public void Test_found_nameservers_schema_2()
{
var sample = SampleReader.Read("whois.sgnic.sg", "sg", "found_nameservers_schema_2.txt");
var response = parser.Parse("whois.sgnic.sg", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.sgnic.sg/sg/Found01", response.TemplateName);
Assert.AreEqual("google.sg", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("MARKMONITOR INC", response.Registrar.Name);
Assert.AreEqual(new DateTime(2005, 01, 03, 12, 00, 00, 000, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2012, 01, 03, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("GOOGLE INC.", response.Registrant.Name);
Assert.AreEqual("+1.6502530000", response.Registrant.TelephoneNumber);
Assert.AreEqual("+1.6502530001", response.Registrant.FaxNumber);
Assert.AreEqual("dns-admin@google.com", response.Registrant.Email);
// Registrant Address
Assert.AreEqual(4, response.Registrant.Address.Count);
Assert.AreEqual("1600 AMPHITHEATRE PARKWAY", response.Registrant.Address[0]);
Assert.AreEqual("CA", response.Registrant.Address[1]);
Assert.AreEqual("US", response.Registrant.Address[2]);
Assert.AreEqual("94043", response.Registrant.Address[3]);
// Domain Status
Assert.AreEqual(4, response.DomainStatus.Count);
Assert.AreEqual("OK", response.DomainStatus[0]);
Assert.AreEqual("CLIENT UPDATE PROHIBITED", response.DomainStatus[1]);
Assert.AreEqual("CLIENT TRANSFER PROHIBITED", response.DomainStatus[2]);
Assert.AreEqual("CLIENT DELETE PROHIBITED", response.DomainStatus[3]);
Assert.AreEqual(18, response.FieldsParsed);
}
[Test]
public void Test_not_found()
{
var sample = SampleReader.Read("whois.sgnic.sg", "sg", "not_found.txt");
var response = parser.Parse("whois.sgnic.sg", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("generic/tld/NotFound002", response.TemplateName);
Assert.AreEqual(1, response.FieldsParsed);
}
[Test]
public void Test_found_status_registered()
{
var sample = SampleReader.Read("whois.sgnic.sg", "sg", "found_status_registered.txt");
var response = parser.Parse("whois.sgnic.sg", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.sgnic.sg/sg/Found02", response.TemplateName);
Assert.AreEqual("google.sg", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("MARKMONITOR INC", response.Registrar.Name);
Assert.AreEqual(new DateTime(2005, 01, 03, 12, 00, 00, 000, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2020, 01, 03, 00, 00, 00, 000, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("GOOGLE LLC", response.Registrant.Name);
// AdminContact Details
Assert.AreEqual("MARKMONITOR INC.", response.AdminContact.Name);
// TechnicalContact Details
Assert.AreEqual("GOOGLE LLC", response.TechnicalContact.Name);
// Nameservers
Assert.AreEqual(4, response.NameServers.Count);
Assert.AreEqual("ns1.google.com", response.NameServers[0]);
Assert.AreEqual("ns2.google.com", response.NameServers[1]);
Assert.AreEqual("ns3.google.com", response.NameServers[2]);
Assert.AreEqual("ns4.google.com", response.NameServers[3]);
// Domain Status
Assert.AreEqual(5, response.DomainStatus.Count);
Assert.AreEqual("OK", response.DomainStatus[0]);
Assert.AreEqual("CLIENT UPDATE PROHIBITED", response.DomainStatus[1]);
Assert.AreEqual("CLIENT TRANSFER PROHIBITED", response.DomainStatus[2]);
Assert.AreEqual("CLIENT DELETE PROHIBITED", response.DomainStatus[3]);
Assert.AreEqual("VerifiedID@SG-Not Required", response.DomainStatus[4]);
Assert.AreEqual(17, response.FieldsParsed);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace MS.Internal.ValueConverter {
using System;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.CodeDom.Compiler; // for IndentedTextWriter
public class Generator {
private IndentedTextWriter w;
public static Type[] InterfaceTypes = {typeof(Boolean), typeof(DateTime), typeof(Decimal), typeof(Double), typeof(Int32), typeof(Int64), typeof(Single), typeof(String), typeof(Object)};
// xs:decimal and derived types
public static ConversionRuleGroup Numeric10RuleGroup =
new ConversionRuleGroup("XmlNumeric10Converter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "Decimal", "Decimal", "((decimal) value)"},
new string[] {"*", "Int32", "Decimal", "((decimal) (int) value)"},
new string[] {"*", "Int64", "Decimal", "((decimal) (long) value)"},
new string[] {"*", "String", "Decimal", "XmlConvert.ToInteger((string) value)"},
new string[] {"xs:decimal", "String", "Decimal", "XmlConvert.ToDecimal((string) value)"},
new string[] {"*", "XmlAtomicValue", "Decimal", "((decimal) ((XmlAtomicValue) value).ValueAs(DecimalType))"},
new string[] {"*", "Decimal", "Int32", "DecimalToInt32((decimal) value)"},
new string[] {"*", "Int32", "Int32", "((int) value)"},
new string[] {"*", "Int64", "Int32", "Int64ToInt32((long) value)"},
new string[] {"*", "String", "Int32", "XmlConvert.ToInt32((string) value)"},
new string[] {"xs:decimal", "String", "Int32", "DecimalToInt32(XmlConvert.ToDecimal((string) value))"},
new string[] {"*", "XmlAtomicValue", "Int32", "((XmlAtomicValue) value).ValueAsInt"},
new string[] {"*", "Decimal", "Int64", "DecimalToInt64((decimal) value)"},
new string[] {"*", "Int32", "Int64", "((long) (int) value)"},
new string[] {"*", "Int64", "Int64", "((long) value)"},
new string[] {"*", "String", "Int64", "XmlConvert.ToInt64((string) value)"},
new string[] {"xs:decimal", "String", "Int64", "DecimalToInt64(XmlConvert.ToDecimal((string) value))"},
new string[] {"*", "XmlAtomicValue", "Int64", "((XmlAtomicValue) value).ValueAsLong"},
new string[] {"*", "Decimal", "String", "XmlConvert.ToString(decimal.Truncate((decimal) value))"},
new string[] {"xs:decimal", "Decimal", "String", "XmlConvert.ToString((decimal) value)"},
new string[] {"*", "Int32", "String", "XmlConvert.ToString((int) value)"},
new string[] {"*", "Int64", "String", "XmlConvert.ToString((long) value)"},
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((XmlAtomicValue) value).Value"},
new string[] {"*", "Decimal", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "Int32", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (int) value))"},
new string[] {"*", "Int64", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (long) value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "Decimal", "XPathItem", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "Int32", "XPathItem", "(new XmlAtomicValue(SchemaType, (int) value))"},
new string[] {"*", "Int64", "XPathItem", "(new XmlAtomicValue(SchemaType, (long) value))"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
new string[] {"*", "*", "Byte", "Int32ToByte(this.ToInt32(value))"},
new string[] {"*", "*", "Int16", "Int32ToInt16(this.ToInt32(value))"},
new string[] {"*", "*", "SByte", "Int32ToSByte(this.ToInt32(value))"},
new string[] {"*", "*", "UInt16", "Int32ToUInt16(this.ToInt32(value))"},
new string[] {"*", "*", "UInt32", "Int64ToUInt32(this.ToInt64(value))"},
new string[] {"*", "*", "UInt64", "DecimalToUInt64(this.ToDecimal(value))"},
new string[] {"*", "Byte", "*", "this.ChangeType((int) (byte) value, destinationType)"},
new string[] {"*", "Int16", "*", "this.ChangeType((int) (short) value, destinationType)"},
new string[] {"*", "SByte", "*", "this.ChangeType((int) (sbyte) value, destinationType)"},
new string[] {"*", "UInt16", "*", "this.ChangeType((int) (ushort) value, destinationType)"},
new string[] {"*", "UInt32", "*", "this.ChangeType((long) (uint) value, destinationType)"},
new string[] {"*", "UInt64", "*", "this.ChangeType((decimal) (ulong) value, destinationType)"},
});
// xs:double, xs:float, and derived types
public static ConversionRuleGroup Numeric2RuleGroup =
new ConversionRuleGroup("XmlNumeric2Converter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "Double", "Double", "((double) value)"},
new string[] {"*", "Single", "Double", "((double) (float) value)"},
new string[] {"*", "String", "Double", "XmlConvert.ToDouble((string) value)"},
new string[] {"xs:float", "String", "Double", "((double) XmlConvert.ToSingle((string) value))"},
new string[] {"*", "XmlAtomicValue", "Double", "((XmlAtomicValue) value).ValueAsDouble"},
new string[] {"*", "Double", "Single", "((float) (double) value)"},
new string[] {"*", "Single", "Single", "((float) value)"},
new string[] {"*", "String", "Single", "((float) XmlConvert.ToDouble((string) value))"},
new string[] {"xs:float", "String", "Single", "XmlConvert.ToSingle((string) value)"},
new string[] {"*", "XmlAtomicValue", "Single", "((float) ((XmlAtomicValue) value).ValueAs(SingleType))"},
new string[] {"*", "Double", "String", "XmlConvert.ToString((double) value)"},
new string[] {"xs:float", "Double", "String", "XmlConvert.ToString(ToSingle((double) value))"},
new string[] {"*", "Single", "String", "XmlConvert.ToString((double) (float) value)"},
new string[] {"xs:float", "Single", "String", "XmlConvert.ToString((float) value)"},
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((XmlAtomicValue) value).Value"},
new string[] {"*", "Double", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (double) value))"},
new string[] {"*", "Single", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "Double", "XPathItem", "(new XmlAtomicValue(SchemaType, (double) value))"},
new string[] {"*", "Single", "XPathItem", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
});
// xs:dateTime, xs:date, xs:time, xs:gDay, xs:gMonth, xs:gMOnthDay, xs:gYear, xs:gYearMonth, and derived types
public static ConversionRuleGroup DateTimeRuleGroup =
new ConversionRuleGroup("XmlDateTimeConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "DateTime", "DateTime", "((DateTime) value)"},
new string[] {"*", "String", "DateTime", "StringToDateTime((string) value)"},
new string[] {"xs:date", "String", "DateTime", "StringToDate((string) value)"},
new string[] {"xs:time", "String", "DateTime", "StringToTime((string) value)"},
new string[] {"xs:gDay", "String", "DateTime", "StringToGDay((string) value)"},
new string[] {"xs:gMonth", "String", "DateTime", "StringToGMonth((string) value)"},
new string[] {"xs:gMonthDay", "String", "DateTime", "StringToGMonthDay((string) value)"},
new string[] {"xs:gYear", "String", "DateTime", "StringToGYear((string) value)"},
new string[] {"xs:gYearMonth", "String", "DateTime", "StringToGYearMonth((string) value)"},
new string[] {"*", "XmlAtomicValue", "DateTime", "((XmlAtomicValue) value).ValueAsDateTime"},
new string[] {"*", "DateTime", "String", "DateTimeToString((DateTime) value)"},
new string[] {"xs:date", "DateTime", "String", "DateToString((DateTime) value)"},
new string[] {"xs:time", "DateTime", "String", "TimeToString((DateTime) value)"},
new string[] {"xs:gDay", "DateTime", "String", "GDayToString((DateTime) value)"},
new string[] {"xs:gMonth", "DateTime", "String", "GMonthToString((DateTime) value)"},
new string[] {"xs:gMonthDay", "DateTime", "String", "GMonthDayToString((DateTime) value)"},
new string[] {"xs:gYear", "DateTime", "String", "GYearToString((DateTime) value)"},
new string[] {"xs:gYearMonth", "DateTime", "String", "GYearMonthToString((DateTime) value)"},
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((XmlAtomicValue) value).Value"},
new string[] {"*", "DateTime", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (DateTime) value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "DateTime", "XPathItem", "(new XmlAtomicValue(SchemaType, (DateTime) value))"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
});
// xs:boolean and derived types
public static ConversionRuleGroup BooleanRuleGroup =
new ConversionRuleGroup("XmlBooleanConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "Boolean", "Boolean", "((bool) value)"},
new string[] {"*", "String", "Boolean", "XmlConvert.ToBoolean((string) value)"},
new string[] {"*", "XmlAtomicValue", "Boolean", "((XmlAtomicValue) value).ValueAsBoolean"},
new string[] {"*", "Boolean", "String", "XmlConvert.ToString((bool) value)"},
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((XmlAtomicValue) value).Value"},
new string[] {"*", "Boolean", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (bool) value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "Boolean", "XPathItem", "(new XmlAtomicValue(SchemaType, (bool) value))"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
});
// xs:base64Binary, xs:hexBinary, xs:NOTATION, xs:QName, xs:anyUri, xs:duration, and derived types
public static ConversionRuleGroup MiscRuleGroup =
new ConversionRuleGroup("XmlMiscConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"xs:base64Binary", "ByteArray", "ByteArray", "((byte[]) value)"},
new string[] {"xs:hexBinary", "ByteArray", "ByteArray", "((byte[]) value)"},
new string[] {"xs:base64Binary", "String", "ByteArray", "StringToBase64Binary((string) value)"},
new string[] {"xs:hexBinary", "String", "ByteArray", "StringToHexBinary((string) value)"},
new string[] {"xs:NOTATION", "String", "XmlQualifiedName", "StringToQName((string) value, nsResolver)"},
new string[] {"xs:QName", "String", "XmlQualifiedName", "StringToQName((string) value, nsResolver)"},
new string[] {"xs:NOTATION", "XmlQualifiedName", "XmlQualifiedName", "((XmlQualifiedName) value)"},
new string[] {"xs:QName", "XmlQualifiedName", "XmlQualifiedName", "((XmlQualifiedName) value)"},
new string[] {"xs:base64Binary", "ByteArray", "String", "Base64BinaryToString((byte[]) value)"},
new string[] {"xs:hexBinary", "ByteArray", "String", "XmlConvert.ToBinHexString((byte[]) value)"},
new string[] {"*", "String", "String", "(string) value"},
new string[] {"xs:anyURI", "Uri", "String", "AnyUriToString((Uri) value)"},
new string[] {"xs:dayTimeDuration", "TimeSpan", "String", "DayTimeDurationToString((TimeSpan) value)"},
new string[] {"xs:duration", "TimeSpan", "String", "DurationToString((TimeSpan) value)"},
new string[] {"xs:yearMonthDuration", "TimeSpan", "String", "YearMonthDurationToString((TimeSpan) value)"},
new string[] {"xs:NOTATION", "XmlQualifiedName", "String", "QNameToString((XmlQualifiedName) value, nsResolver)"},
new string[] {"xs:QName", "XmlQualifiedName", "String", "QNameToString((XmlQualifiedName) value, nsResolver)"},
new string[] {"xs:dayTimeDuration", "String", "TimeSpan", "StringToDayTimeDuration((string) value)"},
new string[] {"xs:duration", "String", "TimeSpan", "StringToDuration((string) value)"},
new string[] {"xs:yearMonthDuration", "String", "TimeSpan", "StringToYearMonthDuration((string) value)"},
new string[] {"xs:dayTimeDuration", "TimeSpan", "TimeSpan", "((TimeSpan) value)"},
new string[] {"xs:duration", "TimeSpan", "TimeSpan", "((TimeSpan) value)"},
new string[] {"xs:yearMonthDuration", "TimeSpan", "TimeSpan", "((TimeSpan) value)"},
new string[] {"xs:anyURI", "String", "Uri", "XmlConvert.ToUri((string) value)"},
new string[] {"xs:anyURI", "Uri", "Uri", "((Uri) value)"},
new string[] {"xs:base64Binary", "ByteArray", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"xs:hexBinary", "ByteArray", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string)value, nsResolver))"},
new string[] {"xs:dayTimeDuration", "TimeSpan", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"xs:duration", "TimeSpan", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"xs:yearMonthDuration", "TimeSpan", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"xs:anyURI", "Uri", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"xs:NOTATION", "XmlQualifiedName", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value, nsResolver))"},
new string[] {"xs:QName", "XmlQualifiedName", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, value, nsResolver))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
new string[] {"*", "*", "XPathItem", "((XPathItem) this.ChangeType(value, XmlAtomicValueType, nsResolver))"},
new string[] {"*", "XmlAtomicValue", "*", "((XmlAtomicValue) value).ValueAs(destinationType, nsResolver)"},
});
// xs:string and derived types
public static ConversionRuleGroup StringRuleGroup =
new ConversionRuleGroup("XmlStringConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((XmlAtomicValue) value).Value"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
});
// xs:untypedAtomic
public static ConversionRuleGroup UntypedRuleGroup =
new ConversionRuleGroup("XmlUntypedConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "String", "Boolean", "XmlConvert.ToBoolean((string) value)"},
new string[] {"*", "String", "Byte", "Int32ToByte(XmlConvert.ToInt32((string) value))"},
new string[] {"*", "String", "ByteArray", "StringToBase64Binary((string) value)"},
new string[] {"*", "String", "DateTime", "UntypedAtomicToDateTime((string) value)"},
new string[] {"*", "String", "Decimal", "XmlConvert.ToDecimal((string) value)"},
new string[] {"*", "String", "Double", "XmlConvert.ToDouble((string) value)"},
new string[] {"*", "String", "Int16", "Int32ToInt16(XmlConvert.ToInt32((string) value))"},
new string[] {"*", "String", "Int32", "XmlConvert.ToInt32((string) value)"},
new string[] {"*", "String", "Int64", "XmlConvert.ToInt64((string) value)"},
new string[] {"*", "String", "SByte", "Int32ToSByte(XmlConvert.ToInt32((string) value))"},
new string[] {"*", "String", "Single", "XmlConvert.ToSingle((string) value)"},
new string[] {"*", "String", "TimeSpan", "StringToDuration((string) value)"},
new string[] {"*", "String", "UInt16", "Int32ToUInt16(XmlConvert.ToInt32((string) value))"},
new string[] {"*", "String", "UInt32", "Int64ToUInt32(XmlConvert.ToInt64((string) value))"},
new string[] {"*", "String", "UInt64", "DecimalToUInt64(XmlConvert.ToDecimal((string) value))"},
new string[] {"*", "String", "Uri", "XmlConvert.ToUri((string) value)"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "String", "XmlQualifiedName", "StringToQName((string) value, nsResolver)"},
new string[] {"*", "String", "XPathItem", "(new XmlAtomicValue(SchemaType, (string) value))"},
new string[] {"*", "Boolean", "String", "XmlConvert.ToString((bool) value)"},
new string[] {"*", "Byte", "String", "XmlConvert.ToString((byte) value)"},
new string[] {"*", "ByteArray", "String", "Base64BinaryToString((byte[]) value)"},
new string[] {"*", "DateTime", "String", "DateTimeToString((DateTime) value)"},
new string[] {"*", "Decimal", "String", "XmlConvert.ToString((decimal) value)"},
new string[] {"*", "Double", "String", "XmlConvert.ToString((double) value)"},
new string[] {"*", "Int16", "String", "XmlConvert.ToString((short) value)"},
new string[] {"*", "Int32", "String", "XmlConvert.ToString((int) value)"},
new string[] {"*", "Int64", "String", "XmlConvert.ToString((long) value)"},
new string[] {"*", "SByte", "String", "XmlConvert.ToString((sbyte) value)"},
new string[] {"*", "Single", "String", "XmlConvert.ToString((float) value)"},
new string[] {"*", "String", "String", "((string) value)"},
new string[] {"*", "TimeSpan", "String", "DurationToString((TimeSpan) value)"},
new string[] {"*", "UInt16", "String", "XmlConvert.ToString((ushort) value)"},
new string[] {"*", "UInt32", "String", "XmlConvert.ToString((uint) value)"},
new string[] {"*", "UInt64", "String", "XmlConvert.ToString((ulong) value)"},
new string[] {"*", "Uri", "String", "AnyUriToString((Uri) value)"},
new string[] {"*", "XmlAtomicValue", "String", "((string) ((XmlAtomicValue) value).ValueAs(StringType, nsResolver))"},
new string[] {"*", "XmlQualifiedName", "String", "QNameToString((XmlQualifiedName) value, nsResolver)"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
new string[] {"*", "*", "XmlAtomicValue", "(new XmlAtomicValue(SchemaType, this.ToString(value, nsResolver)))"},
new string[] {"*", "*", "XPathItem", "(new XmlAtomicValue(SchemaType, this.ToString(value, nsResolver)))"},
new string[] {"*", "XmlAtomicValue", "*", "((XmlAtomicValue) value).ValueAs(destinationType, nsResolver)"},
});
// node
public static ConversionRuleGroup NodeRuleGroup =
new ConversionRuleGroup("XmlNodeConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "XPathNavigator", "XPathNavigator", "((XPathNavigator) value)"},
new string[] {"*", "XPathNavigator", "XPathItem", "((XPathItem) value)"},
});
// item, xs:anyAtomicType
public static ConversionRuleGroup AnyRuleGroup =
new ConversionRuleGroup("XmlAnyConverter", new string[][]
{
// Xml Type Source Clr Type Destination Clr Type Conversion Logic
// =====================================================================================================
new string[] {"*", "XmlAtomicValue", "Boolean", "((XmlAtomicValue) value).ValueAsBoolean"},
new string[] {"*", "XmlAtomicValue", "DateTime", "((XmlAtomicValue) value).ValueAsDateTime"},
new string[] {"*", "XmlAtomicValue", "Decimal", "((decimal) ((XmlAtomicValue) value).ValueAs(DecimalType))"},
new string[] {"*", "XmlAtomicValue", "Double", "((XmlAtomicValue) value).ValueAsDouble"},
new string[] {"*", "XmlAtomicValue", "Int32", "((XmlAtomicValue) value).ValueAsInt"},
new string[] {"*", "XmlAtomicValue", "Int64", "((XmlAtomicValue) value).ValueAsLong"},
new string[] {"*", "XmlAtomicValue", "Single", "((float) ((XmlAtomicValue) value).ValueAs(SingleType))"},
new string[] {"*", "XmlAtomicValue", "XmlAtomicValue", "((XmlAtomicValue) value)"},
new string[] {"*", "Boolean", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool) value))"},
new string[] {"*", "Byte", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedByte), value))"},
new string[] {"*", "ByteArray", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Base64Binary), value))"},
new string[] {"*", "DateTime", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime) value))"},
new string[] {"*", "Decimal", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value))"},
new string[] {"*", "Double", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double) value))"},
new string[] {"*", "Int16", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Short), value))"},
new string[] {"*", "Int32", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int) value))"},
new string[] {"*", "Int64", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long) value))"},
new string[] {"*", "SByte", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Byte), value))"},
new string[] {"*", "Single", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Float), value))"},
new string[] {"*", "String", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string) value))"},
new string[] {"*", "TimeSpan", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Duration), value))"},
new string[] {"*", "UInt16", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedShort), value))"},
new string[] {"*", "UInt32", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedInt), value))"},
new string[] {"*", "UInt64", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedLong), value))"},
new string[] {"*", "Uri", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri), value))"},
new string[] {"*", "XmlQualifiedName", "XmlAtomicValue", "(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.QName), value, nsResolver))"},
new string[] {"*", "XmlAtomicValue", "XPathItem", "((XmlAtomicValue) value)"},
new string[] {"*", "XPathNavigator", "XPathItem", "((XPathNavigator) value)"},
new string[] {"*", "XPathNavigator", "XPathNavigator", "ToNavigator((XPathNavigator) value)"},
new string[] {"*", "XmlAtomicValue", "*", "((XmlAtomicValue) value).ValueAs(destinationType, nsResolver)"},
new string[] {"*", "*", "XPathItem", "((XPathItem) this.ChangeType(value, XmlAtomicValueType, nsResolver))"},
});
public static ConversionRuleGroup[] ConversionsRules = {
Numeric10RuleGroup,
Numeric2RuleGroup,
DateTimeRuleGroup,
BooleanRuleGroup,
MiscRuleGroup,
StringRuleGroup,
UntypedRuleGroup,
NodeRuleGroup,
AnyRuleGroup,
};
public static void Main() {
(new Generator()).Generate();
}
public void Generate() {
AutoGenWriter autoGenWriter;
//-----------------------------------------------
// XmlBaseConverter
//-----------------------------------------------
// Output list of all CLR types used by the generated code
autoGenWriter = new AutoGenWriter("XmlValueConverter.cs", "AUTOGENERATED_XMLBASECONVERTER");
this.w = autoGenWriter.OpenIndented();
List<Type> uniqueTypes = new List<Type>();
foreach (ConversionRuleGroup group in ConversionsRules) {
foreach (Type tSrc in group.FindUniqueSourceTypes(null))
if (!uniqueTypes.Contains(tSrc)) uniqueTypes.Add(tSrc);
foreach (Type tDst in group.FindUniqueDestinationTypes(null))
if (!uniqueTypes.Contains(tDst)) uniqueTypes.Add(tDst);
}
foreach (Type t in uniqueTypes)
this.w.WriteLine("protected static readonly Type " + ClrTypeName(t) + "Type = typeof(" + ClrTypeToCSharpName(t) + ");");
this.w.WriteLine();
// Output default methods which call ChangeType
foreach (Type tDst in InterfaceTypes) {
foreach (Type tSrc in InterfaceTypes) {
if (tDst == typeof(object) && tSrc == typeof(object))
continue;
StartMethodSignature(tSrc, tDst);
this.w.Write("return (" + ClrTypeToCSharpName(tDst) + ") ChangeType((object) value, ");
if (tDst == typeof(object))
this.w.Write("destinationType");
else
this.w.Write(ClrTypeName(tDst) + "Type");
this.w.WriteLine(", " + (MethodHasResolver(tSrc, tDst) ? "nsResolver" : "null") + "); }");
}
if (tDst == typeof(string)) {
this.w.WriteLine("public override string ToString(string value) {return this.ToString(value, null); }");
this.w.WriteLine("public override string ToString(object value) {return this.ToString(value, null); }");
}
if (tDst == typeof(object)) {
this.w.WriteLine("public override object ChangeType(string value, Type destinationType) {return this.ChangeType(value, destinationType, null); }");
this.w.WriteLine("public override object ChangeType(object value, Type destinationType) {return this.ChangeType(value, destinationType, null); }");
}
this.w.WriteLine();
}
autoGenWriter.Close();
//-----------------------------------------------
// Other Converters
//-----------------------------------------------
foreach (ConversionRuleGroup group in ConversionsRules) {
IList<Type> uniqueSourceTypes, uniqueDestTypes;
autoGenWriter = new AutoGenWriter("XmlValueConverter.cs", "AUTOGENERATED_" + group.Name.ToUpper());
this.w = autoGenWriter.OpenIndented();
foreach (Type tDst in InterfaceTypes) {
// Handle ChangeType methods later
if (tDst == typeof(object))
continue;
this.w.WriteLine();
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine("// To" + ClrTypeName(tDst));
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine();
// Create strongly-typed ToXXX methods
foreach (Type tSrc in InterfaceTypes) {
// Handle ToXXX(object value) method later
if (tSrc == typeof(object))
continue;
IList<ConversionRule> rules = group.Find(XmlTypeCode.None, tSrc, tDst);
if (rules.Count > 0) {
ConversionRule defaultRule = FindDefaultRule(rules);
if (defaultRule == null)
throw new Exception("If conversion from " + tSrc.Name + " to " + tDst.Name + " exists, a default conversion should also be defined.");
// ToXXX(T value)
StartMethod(tSrc, tDst);
GenerateConversions(defaultRule, rules);
EndMethod();
}
}
// Gather all unique source types which have destination type "tDst"
uniqueSourceTypes = group.FindUniqueSourceTypes(tDst);
if (uniqueSourceTypes.Count > 0) {
// ToXXX(object value);
StartMethod(typeof(object), tDst);
this.w.WriteLine("Type sourceType = value.GetType();");
this.w.WriteLine();
foreach (Type tSrc in uniqueSourceTypes)
GenerateConversionsTo(group.Find(XmlTypeCode.None, tSrc, tDst));
// If wildcard destination conversions exist, then delegate to ChangeTypeWildcardDestination method to handle them
this.w.WriteLine();
this.w.Write("return (" + ClrTypeToCSharpName(tDst) + ") ");
this.w.Write(group.FindUniqueSourceTypes(typeof(object)).Count > 0 ? "ChangeTypeWildcardDestination" : "ChangeListType");
this.w.WriteLine("(value, " + ClrTypeName(tDst) + "Type, " + (MethodHasResolver(typeof(object), tDst) ? "nsResolver);" : "null);"));
EndMethod();
}
else {
this.w.WriteLine("// This converter does not support conversions to " + ClrTypeName(tDst) + ".");
}
this.w.WriteLine();
}
this.w.WriteLine();
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine("// ChangeType");
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine();
foreach (Type tSrc in InterfaceTypes) {
// Handle ChangeType(object) later
if (tSrc == typeof(object))
continue;
// Gather all unique destination types which have source type "tSrc"
uniqueDestTypes = group.FindUniqueDestinationTypes(tSrc);
if (uniqueDestTypes.Count > 0) {
// ChangeType(T value, Type destinationType);
StartMethod(tSrc, typeof(object));
this.w.WriteLine("if (destinationType == ObjectType) destinationType = DefaultClrType;");
foreach (Type tDst in uniqueDestTypes)
GenerateConversionsFrom(group.Find(XmlTypeCode.None, tSrc, tDst));
// If wildcard source conversions exist, then delegate to ChangeTypeWildcardSource method to handle them
this.w.WriteLine();
if (group.FindUniqueDestinationTypes(typeof(object)).Count > 0)
this.w.Write("return ChangeTypeWildcardSource(value, destinationType, ");
else
this.w.Write("return ChangeListType(value, destinationType, ");
this.w.WriteLine(MethodHasResolver(typeof(object), tSrc) ? "nsResolver);" : "null);");
EndMethod();
this.w.WriteLine();
}
}
// object ChangeType(object value, Type destinationType, IXmlNamespaceResolver resolver);
StartMethod(typeof(object), typeof(object));
this.w.WriteLine("Type sourceType = value.GetType();");
this.w.WriteLine();
// Generate conversions to destinationType
this.w.WriteLine("if (destinationType == ObjectType) destinationType = DefaultClrType;");
// Strongly-typed destinations
foreach (Type tDst in group.FindUniqueDestinationTypes(null)) {
// Only output conversions if the destination is not a wildcard
if (tDst == typeof(object))
continue;
// Get source types that can be converted to the destination type
uniqueSourceTypes = group.FindUniqueSourceTypes(tDst);
// Remove wildcard source rules, as they are handled later
int i = 0;
while (i < uniqueSourceTypes.Count) {
if (uniqueSourceTypes[i] == typeof(object))
uniqueSourceTypes.RemoveAt(i);
else
i++;
}
if (uniqueSourceTypes.Count != 0) {
if (IsInterfaceMethod(tDst) && uniqueSourceTypes.Count > 1) {
this.w.Write("if (destinationType == " + ClrTypeName(tDst) + "Type) ");
this.w.WriteLine("return this.To" + ClrTypeName(tDst) + "(value" + (MethodHasResolver(tDst, tDst) ? ", nsResolver);" : ");"));
}
else {
this.w.WriteLine("if (destinationType == " + ClrTypeName(tDst) + "Type) {");
this.w.Indent++;
foreach (Type tSrc in uniqueSourceTypes) {
GenerateConversionsTo(group.Find(XmlTypeCode.None, tSrc, tDst));
}
this.w.Indent--;
this.w.WriteLine("}");
}
}
}
// Generate conversions from wildcard source types
foreach (Type tDst in group.FindUniqueDestinationTypes(typeof(object)))
GenerateConversionsFrom(group.Find(XmlTypeCode.None, typeof(object), tDst));
// Generate conversions to wildcard destination types
foreach (Type tSrc in group.FindUniqueSourceTypes(typeof(object)))
GenerateConversionsTo(group.Find(XmlTypeCode.None, tSrc, typeof(object)));
this.w.WriteLine();
this.w.WriteLine("return ChangeListType(value, destinationType, nsResolver);");
EndMethod();
uniqueSourceTypes = group.FindUniqueSourceTypes(typeof(object));
uniqueDestTypes = group.FindUniqueDestinationTypes(typeof(object));
if (uniqueSourceTypes.Count != 0 || uniqueDestTypes.Count != 0) {
this.w.WriteLine();
this.w.WriteLine();
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine("// Helpers");
this.w.WriteLine("//-----------------------------------------------");
this.w.WriteLine();
// Generate ChangeTypeWildcardDestination method, which performs conversions that are the same no matter what the destination type is
if (uniqueSourceTypes.Count != 0) {
this.w.WriteLine("private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver nsResolver) {");
this.w.Indent++;
this.w.WriteLine("Type sourceType = value.GetType();");
this.w.WriteLine();
foreach (Type tSrc in uniqueSourceTypes)
GenerateConversionsTo(group.Find(XmlTypeCode.None, tSrc, typeof(object)));
this.w.WriteLine();
this.w.WriteLine("return ChangeListType(value, destinationType, nsResolver);");
this.w.Indent--;
this.w.WriteLine("}");
}
// Generate ChangeTypeWildcardSource method, which performs conversions that are the same no matter what the source type is
if (uniqueDestTypes.Count != 0) {
this.w.WriteLine("private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver nsResolver) {");
this.w.Indent++;
foreach (Type tDst in uniqueDestTypes)
GenerateConversionsFrom(group.Find(XmlTypeCode.None, typeof(object), tDst));
this.w.WriteLine();
this.w.WriteLine("return ChangeListType(value, destinationType, nsResolver);");
this.w.Indent--;
this.w.WriteLine("}");
}
}
autoGenWriter.Close();
}
}
private void StartMethod(Type typeSrc, Type typeDst) {
StartMethodSignature(typeSrc, typeDst);
this.w.WriteLine();
this.w.Indent++;
if (!typeSrc.IsValueType) {
this.w.WriteLine("if (value == null) throw new ArgumentNullException(\"value\");");
if (typeDst != typeof(object))
this.w.WriteLine();
}
if (typeDst == typeof(object)) {
this.w.WriteLine("if (destinationType == null) throw new ArgumentNullException(\"destinationType\");");
this.w.WriteLine();
}
}
private void StartMethodSignature(Type typeSrc, Type typeDst) {
string methName, methSig;
methSig = ClrTypeToCSharpName(typeSrc) + " value";
if (typeDst == typeof(object)) {
methName = "ChangeType";
methSig += ", Type destinationType";
}
else {
methName = "To" + ClrTypeName(typeDst);
}
if (MethodHasResolver(typeSrc, typeDst))
methSig += ", IXmlNamespaceResolver nsResolver";
this.w.Write("public override " + ClrTypeToCSharpName(typeDst) + " " + methName + "(" + methSig + ") {");
}
private void EndMethod() {
this.w.Indent--;
this.w.WriteLine("}");
}
private bool MethodHasResolver(Type typeSrc, Type typeDst) {
if (typeSrc == typeof(object) || typeSrc == typeof(string)) {
if (typeDst == typeof(object) || typeDst == typeof(string))
return true;
}
return false;
}
private ConversionRule FindDefaultRule(IList<ConversionRule> rules) {
foreach (ConversionRule rule in rules) {
if (rule.XmlType == XmlTypeCode.Item)
return rule;
}
return null;
}
private void GenerateConversions(ConversionRule defaultRule, IList<ConversionRule> rulesSwitch) {
int cnt = rulesSwitch.Count;
// Don't need to test TypeCode for default rule
if (defaultRule != null)
cnt--;
if (cnt > 0) {
if (cnt > 1) {
this.w.WriteLine("switch (TypeCode) {");
}
foreach (ConversionRule ruleSwitch in rulesSwitch) {
if (ruleSwitch != defaultRule) {
if (cnt > 1) {
this.w.Indent++;
this.w.WriteLine("case XmlTypeCode." + ruleSwitch.XmlType + ": return " + ruleSwitch.ConversionExpression + ";");
this.w.Indent--;
}
else {
this.w.WriteLine("if (TypeCode == XmlTypeCode." + ruleSwitch.XmlType + ") return " + ruleSwitch.ConversionExpression + ";");
}
}
}
if (cnt > 1) {
this.w.WriteLine("}");
}
}
if (defaultRule != null)
this.w.WriteLine("return " + defaultRule.ConversionExpression + ";");
}
private void GenerateConversionsTo(IList<ConversionRule> rules) {
GenerateConversionsToFrom(rules, false);
}
private void GenerateConversionsFrom(IList<ConversionRule> rules) {
GenerateConversionsToFrom(rules, true);
}
private void GenerateConversionsToFrom(IList<ConversionRule> rules, bool isFrom) {
ConversionRule defaultRule = FindDefaultRule(rules);
Type tSrc, tDst;
// If no conversions exist, then don't generate anything
if (rules.Count == 0)
return;
tSrc = rules[0].SourceType;
tDst = rules[0].DestinationType;
if (isFrom)
this.w.Write("if (destinationType == " + ClrTypeName(tDst) + "Type) ");
else
this.w.Write("if (" + GenerateSourceTypeMatch(tSrc) + ") ");
if (rules.Count > 1 && IsInterfaceMethod(tSrc) && IsInterfaceMethod(tDst)) {
// There exists an interface method already which performs switch, so call it
this.w.Write("return this.To" + ClrTypeName(tDst) + "((" + ClrTypeToCSharpName(tSrc) + ") value");
this.w.WriteLine(MethodHasResolver(tSrc, tDst) ? ", nsResolver);" : ");");
}
else {
// Inline the conversion
if (rules.Count == 1) {
GenerateConversions(defaultRule, rules);
}
else {
this.w.WriteLine("{");
this.w.Indent++;
GenerateConversions(defaultRule, rules);
this.w.Indent--;
this.w.WriteLine("}");
}
}
}
private string GenerateSourceTypeMatch(Type type) {
if (type.IsValueType || type.IsSealed)
return "sourceType == " + ClrTypeName(type) + "Type";
if (type.IsInterface)
return ClrTypeName(type) + "Type.IsAssignableFrom(sourceType)";
return "IsDerivedFrom(sourceType, " + ClrTypeName(type) + "Type)";
}
private static string ClrTypeName(Type type) {
if (type.IsArray)
return type.GetElementType().Name + "Array";
return type.Name;
}
private static string ClrTypeToCSharpName(Type type) {
if (type == typeof(String)) return "string";
if (type == typeof(SByte)) return "sbyte";
if (type == typeof(Int16)) return "short";
if (type == typeof(Int32)) return "int";
if (type == typeof(Int64)) return "long";
if (type == typeof(Byte)) return "byte";
if (type == typeof(UInt16)) return "ushort";
if (type == typeof(UInt32)) return "uint";
if (type == typeof(UInt64)) return "ulong";
if (type == typeof(Double)) return "double";
if (type == typeof(Single)) return "float";
if (type == typeof(Decimal)) return "decimal";
if (type == typeof(Object)) return "object";
if (type == typeof(Boolean)) return "bool";
return type.Name;
}
private static bool IsInterfaceMethod(Type type) {
return ((IList) InterfaceTypes).Contains(type);
}
}
public class ConversionRuleGroup {
private string groupName;
private List<ConversionRule> rules;
public ConversionRuleGroup(string groupName, string[][] rules) {
this.groupName = groupName;
this.rules = new List<ConversionRule>();
foreach (string[] rule in rules) {
XmlTypeCode xmlType = XmlTypeNameToTypeCode(rule[0]);
Type clrTypeSrc = ClrTypeNameToType(rule[1]);
Type clrTypeDst = ClrTypeNameToType(rule[2]);
string convExpr = rule[3];
AddRule(new ConversionRule(xmlType, clrTypeSrc, clrTypeDst, convExpr));
}
}
public string Name {
get { return this.groupName; }
}
public IList<Type> FindUniqueSourceTypes(Type tDst) {
List<Type> types = new List<Type>();
foreach (ConversionRule rule in Find(XmlTypeCode.None, null, tDst)) {
if (!types.Contains(rule.SourceType))
types.Add(rule.SourceType);
}
return types;
}
public IList<Type> FindUniqueDestinationTypes(Type tSrc) {
List<Type> types = new List<Type>();
foreach (ConversionRule rule in Find(XmlTypeCode.None, tSrc, null)) {
if (!types.Contains(rule.DestinationType))
types.Add(rule.DestinationType);
}
return types;
}
public IList<ConversionRule> Find(XmlTypeCode code, Type tSrc, Type tDst) {
List<ConversionRule> subset = new List<ConversionRule>();
foreach (ConversionRule rule in this.rules) {
if (code == XmlTypeCode.None || code == rule.XmlType) {
if (tSrc == null || tSrc == rule.SourceType) {
if (tDst == null || tDst == rule.DestinationType) {
subset.Add(rule);
}
}
}
}
return subset;
}
private void AddRule(ConversionRule ruleAdd) {
for (int i = 0; i < this.rules.Count; i++) {
ConversionRule rule = this.rules[i];
if (rule.XmlType == ruleAdd.XmlType) {
if (rule.SourceType == ruleAdd.SourceType) {
if (rule.DestinationType == ruleAdd.DestinationType) {
// Override previous rule with new rule
this.rules[i] = ruleAdd;
return;
}
}
}
}
this.rules.Add(ruleAdd);
}
private static XmlTypeCode XmlTypeNameToTypeCode(string name) {
int idx;
if (name == "*")
return XmlTypeCode.Item;
idx = name.IndexOf(':');
if (idx != -1)
name = name.Substring(idx + 1);
return (XmlTypeCode) Enum.Parse(typeof(XmlTypeCode), name, true);
}
private static Type ClrTypeNameToType(string name) {
Type type = Type.GetType("System." + name);
if (type != null) return type;
type = Type.GetType("System.IO." + name);
if (type != null) return type;
if (name == "*") return typeof(object);
if (name == "ByteArray") return typeof(byte[]);
if (name == "XmlQualifiedName") return typeof(XmlQualifiedName);
if (name == "XmlAtomicValue") return typeof(XmlAtomicValue);
if (name == "XPathNavigator") return typeof(XPathNavigator);
if (name == "XPathItem") return typeof(XPathItem);
if (name == "Uri") return typeof(Uri);
if (name == "IEnumerable") return typeof(IEnumerable);
throw new Exception("Unknown type " + name);
}
}
public class ConversionRule {
private XmlTypeCode xmlType;
private Type clrTypeSrc, clrTypeDst;
private string convExpr;
public ConversionRule(XmlTypeCode xmlType, Type clrTypeSrc, Type clrTypeDst, string convExpr) {
this.xmlType = xmlType;
this.clrTypeSrc = clrTypeSrc;
this.clrTypeDst = clrTypeDst;
this.convExpr = convExpr;
}
public XmlTypeCode XmlType {
get { return this.xmlType; }
}
public Type SourceType {
get { return this.clrTypeSrc; }
}
public Type DestinationType {
get { return this.clrTypeDst; }
}
public string ConversionExpression {
get { return this.convExpr; }
}
}
public class AutoGenWriter {
private static char[] Whitespace = { ' ' };
private FileStream fs;
private StreamReader r;
private StringWriter sw;
private string regionName;
private int indent;
public AutoGenWriter(string fileName, string regionName) : this(File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite), regionName) {
}
public AutoGenWriter(FileStream fs, string regionName) {
if (!fs.CanSeek || !fs.CanRead || !fs.CanWrite)
throw new Exception("Internal error: Unable to seek/read/write this filestream");
this.fs = fs;
this.r = new StreamReader(fs);
this.sw = new StringWriter();
this.regionName = regionName;
}
public int Indent { get { return this.indent; } }
public TextWriter Open() {
// Seek to the autogenerated region within the file
for (string s = this.r.ReadLine(); s != null; s = this.r.ReadLine()) {
this.sw.WriteLine(s);
if (s.Trim(Whitespace).StartsWith("#region " + this.regionName)) {
if (s[0] != '#')
this.indent = s.IndexOf('#') / 4;
break;
}
}
return this.sw;
}
internal IndentedTextWriter OpenIndented() {
TextWriter w = Open();
IndentedTextWriter iw = new IndentedTextWriter(w);
iw.Indent = this.indent;
for (int i = 0; i < this.indent; i++)
w.Write(" ");
return iw;
}
internal void Close() {
// End the autogenerated region
for (string s = this.r.ReadLine(); s != null; s = this.r.ReadLine()) {
string ss = s.Trim(Whitespace);
if (ss.StartsWith("#endregion")) {
this.sw.WriteLine(s);
break;
}
}
for (string s = r.ReadLine(); s != null; s = this.r.ReadLine()) {
this.sw.WriteLine(s);
}
this.fs.SetLength(0);
this.fs.Seek(0, SeekOrigin.Begin);
StreamWriter w = new StreamWriter(fs);
w.Write(this.sw.ToString());
w.Close();
this.sw.Close();
}
}
}
| |
// <copyright file="EnigmaSymmetric.cs" company="APH Software">
// Copyright (c) Andrew Hawkins. All rights reserved.
// </copyright>
namespace Useful.Security.Cryptography
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Simulates the Enigma encoding machine.
/// </summary>
public sealed class EnigmaSymmetric : SymmetricAlgorithm
{
/// <summary>
/// The seperator between values in a key field.
/// </summary>
internal const char KeyDelimiter = ' ';
/// <summary>
/// The number of fields in the key.
/// </summary>
private const int KeyParts = 4;
/// <summary>
/// The seperator between key fields.
/// </summary>
private const char KeySeperator = '|';
private readonly Enigma _algorithm;
/// <summary>
/// Initializes a new instance of the <see cref="EnigmaSymmetric"/> class.
/// </summary>
public EnigmaSymmetric()
{
_algorithm = new Enigma(new EnigmaSettings());
Reset();
}
/// <inheritdoc />
public override byte[] Key
{
// Example:
// "reflector|rotors|ring|plugboard"
// "B|III II I|03 02 01|DN GR IS KC QX TM PV HY FW BJ"
get
{
StringBuilder key = new();
// Reflector
key.Append(_algorithm.Settings.Reflector.ReflectorNumber.ToString());
key.Append(KeySeperator);
// Rotor order
key.Append(RotorOrderString(_algorithm.Settings.Rotors));
key.Append(KeySeperator);
// Ring setting
key.Append(RotorRingString(_algorithm.Settings.Rotors));
key.Append(KeySeperator);
// Plugboard
key.Append(PlugboardString(_algorithm.Settings.Plugboard));
return Encoding.Unicode.GetBytes(key.ToString());
}
set
{
try
{
_algorithm.Settings = GetSettingsKey(value);
}
catch (Exception ex)
{
throw new ArgumentException("Error parsing Key.", nameof(Key), ex);
}
base.Key = value;
}
}
/// <inheritdoc />
public override byte[] IV
{
get
{
// Example:
// G M Y
byte[] result = Encoding.Unicode.GetBytes(RotorSettingString(_algorithm.Settings.Rotors));
return result;
}
set
{
try
{
_algorithm.Settings = GetSettingsIv(_algorithm.Settings, value);
}
catch (Exception ex)
{
throw new ArgumentException("Error parsing IV.", nameof(IV), ex);
}
base.IV = value;
}
}
/// <inheritdoc />
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
Key = rgbKey;
IV = rgbIV ?? Array.Empty<byte>();
return new ClassicalSymmetricTransform(_algorithm, CipherTransformMode.Decrypt);
}
/// <inheritdoc />
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
Key = rgbKey;
IV = rgbIV ?? Array.Empty<byte>();
return new ClassicalSymmetricTransform(_algorithm, CipherTransformMode.Encrypt);
}
/// <inheritdoc />
public override void GenerateIV()
{
_algorithm.Settings.Rotors[EnigmaRotorPosition.Fastest].CurrentSetting = GetRandomRotorCurrentSetting();
_algorithm.Settings.Rotors[EnigmaRotorPosition.Second].CurrentSetting = GetRandomRotorCurrentSetting();
_algorithm.Settings.Rotors[EnigmaRotorPosition.Third].CurrentSetting = GetRandomRotorCurrentSetting();
IVValue = IV;
}
/// <inheritdoc />
public override void GenerateKey()
{
_algorithm.GenerateSettings();
KeyValue = Key;
}
/// <inheritdoc/>
public override string ToString() => _algorithm.CipherName;
private static IEnigmaSettings GetSettingsKey(byte[] key)
{
string keyString = Encoding.Unicode.GetString(key);
string[] parts = keyString.Split(new char[] { KeySeperator }, StringSplitOptions.None);
if (parts.Length != KeyParts)
{
throw new ArgumentException("Incorrect number of key parts.", nameof(key));
}
IEnigmaReflector reflector = ParseEnigmaReflectorNumber(parts[0]);
IDictionary<EnigmaRotorPosition, EnigmaRotorNumber> rotorNumbers = ParseEnigmaRotorNumbers(parts[1]);
IDictionary<EnigmaRotorPosition, int> rings = ParseEnigmaRings(parts[2]);
IReadOnlyDictionary<EnigmaRotorPosition, IEnigmaRotor> list = new Dictionary<EnigmaRotorPosition, IEnigmaRotor>
{
{ EnigmaRotorPosition.Fastest, new EnigmaRotor() { RotorNumber = rotorNumbers[EnigmaRotorPosition.Fastest], RingPosition = rings[EnigmaRotorPosition.Fastest] } },
{ EnigmaRotorPosition.Second, new EnigmaRotor() { RotorNumber = rotorNumbers[EnigmaRotorPosition.Second], RingPosition = rings[EnigmaRotorPosition.Second] } },
{ EnigmaRotorPosition.Third, new EnigmaRotor() { RotorNumber = rotorNumbers[EnigmaRotorPosition.Third], RingPosition = rings[EnigmaRotorPosition.Third] } },
};
EnigmaRotors rotors = new(list);
EnigmaPlugboard plugboard = ParsePlugboard(parts[3]);
return new EnigmaSettings() { Reflector = reflector, Rotors = rotors, Plugboard = plugboard };
}
private static IEnigmaSettings GetSettingsIv(IEnigmaSettings settings, byte[] iv)
{
string ivString = iv != null ? Encoding.Unicode.GetString(iv) : string.Empty;
IDictionary<EnigmaRotorPosition, char> rotorSettings = ParseEnigmaRotorSettings(ivString);
settings.Rotors[EnigmaRotorPosition.Fastest].CurrentSetting = rotorSettings[EnigmaRotorPosition.Fastest];
settings.Rotors[EnigmaRotorPosition.Second].CurrentSetting = rotorSettings[EnigmaRotorPosition.Second];
settings.Rotors[EnigmaRotorPosition.Third].CurrentSetting = rotorSettings[EnigmaRotorPosition.Third];
return settings;
}
private static IEnigmaReflector ParseEnigmaReflectorNumber(string reflector)
{
if (reflector.Length > 1 ||
!char.IsLetter(reflector[0]) ||
!Enum.TryParse(reflector, out EnigmaReflectorNumber reflectorNumber))
{
throw new ArgumentException("Incorrect reflector.", nameof(reflector));
}
return new EnigmaReflector() { ReflectorNumber = reflectorNumber };
}
private static IDictionary<EnigmaRotorPosition, EnigmaRotorNumber> ParseEnigmaRotorNumbers(string rotorNumbers)
{
int rotorPositionsCount = 3;
string[] rotors = rotorNumbers.Split(new char[] { ' ' });
Dictionary<EnigmaRotorPosition, EnigmaRotorNumber> newRotors = new();
if (rotors.Length <= 0)
{
throw new ArgumentException("No rotors specified.", nameof(rotorNumbers));
}
if (rotors.Length > rotorPositionsCount)
{
throw new ArgumentException("Too many rotors specified.", nameof(rotorNumbers));
}
if (rotors.Length < rotorPositionsCount)
{
throw new ArgumentException("Too few rotors specified.", nameof(rotorNumbers));
}
for (int i = 0; i < rotors.Length; i++)
{
string rotor = rotors.Reverse().ToList()[i];
if (string.IsNullOrEmpty(rotor) || rotor.Contains("\0"))
{
throw new ArgumentException("Null or empty rotor specified.", nameof(rotorNumbers));
}
if (!Enum.TryParse(rotor, out EnigmaRotorNumber rotorNumber)
|| rotorNumber.ToString() != rotor)
{
throw new ArgumentException($"Invalid rotor number {rotor}.", nameof(rotorNumbers));
}
newRotors.Add((EnigmaRotorPosition)i, rotorNumber);
}
return newRotors;
}
private static IDictionary<EnigmaRotorPosition, int> ParseEnigmaRings(string ringSettings)
{
int rotorPositionsCount = 3;
string[] rings = ringSettings.Split(new char[] { ' ' });
if (rings.Length <= 0)
{
throw new ArgumentException("No rings specified.", nameof(ringSettings));
}
if (rings.Length > rotorPositionsCount)
{
throw new ArgumentException("Too many rings specified.", nameof(ringSettings));
}
if (rings.Length < rotorPositionsCount)
{
throw new ArgumentException("Too few rings specified.", nameof(ringSettings));
}
if (rings[0].Length == 0)
{
throw new ArgumentException("No rings specified.", nameof(ringSettings));
}
for (int i = 0; i < rings.Length; i++)
{
if (rings[i].Length != 2)
{
throw new ArgumentException("Ring number format incorrect.", nameof(ringSettings));
}
if (!int.TryParse(rings[i], out _))
{
throw new ArgumentException("Ring number is not a number.", nameof(ringSettings));
}
}
return new Dictionary<EnigmaRotorPosition, int>
{
{ EnigmaRotorPosition.Fastest, int.Parse(rings[2]) },
{ EnigmaRotorPosition.Second, int.Parse(rings[1]) },
{ EnigmaRotorPosition.Third, int.Parse(rings[0]) },
};
}
private static IDictionary<EnigmaRotorPosition, char> ParseEnigmaRotorSettings(string rotorSettings)
{
int rotorPositionsCount = 3;
string[] rotorSetting = rotorSettings.Split(new char[] { ' ' });
if (rotorSetting.Length <= 0)
{
throw new ArgumentException("No rotor settings specified.", nameof(rotorSettings));
}
if (rotorSetting.Length > rotorPositionsCount)
{
throw new ArgumentException("Too many rotor settings specified.", nameof(rotorSettings));
}
if (rotorSetting.Length < rotorPositionsCount)
{
throw new ArgumentException("Too few rotor settings specified.", nameof(rotorSettings));
}
if (rotorSetting[0].Length == 0)
{
throw new ArgumentException("No rotor settings specified.", nameof(rotorSettings));
}
return new Dictionary<EnigmaRotorPosition, char>
{
{ EnigmaRotorPosition.Fastest, rotorSetting[2][0] },
{ EnigmaRotorPosition.Second, rotorSetting[1][0] },
{ EnigmaRotorPosition.Third, rotorSetting[0][0] },
};
}
private static EnigmaPlugboard ParsePlugboard(string plugboard)
{
IList<EnigmaPlugboardPair> pairs = new List<EnigmaPlugboardPair>();
string[] rawPairs = plugboard.Split(new char[] { KeyDelimiter });
// No plugs specified
if (rawPairs.Length == 1 && rawPairs[0].Length == 0)
{
return new EnigmaPlugboard(pairs);
}
// Check for plugs made up of pairs
foreach (string rawPair in rawPairs)
{
if (rawPair.Length != 2)
{
throw new ArgumentException("Setting must be a pair.", nameof(plugboard));
}
if (pairs.Any(pair => pair.From == rawPair[0]))
{
throw new ArgumentException("Setting already set.", nameof(plugboard));
}
pairs.Add(new() { From = rawPair[0], To = rawPair[1] });
}
return new EnigmaPlugboard(pairs);
}
private static string RotorSettingString(IEnigmaRotors settings)
{
StringBuilder key = new();
foreach (KeyValuePair<EnigmaRotorPosition, IEnigmaRotor> position in settings.Rotors.Reverse().ToArray())
{
key.Append(position.Value.CurrentSetting);
key.Append(KeyDelimiter);
}
if (settings.Rotors.Count > 0)
{
key.Remove(key.Length - 1, 1);
}
return key.ToString();
}
private static string RotorOrderString(IEnigmaRotors settings)
{
StringBuilder key = new();
foreach (KeyValuePair<EnigmaRotorPosition, IEnigmaRotor> position in settings.Rotors.Reverse().ToArray())
{
key.Append(position.Value.RotorNumber);
key.Append(KeyDelimiter);
}
if (settings.Rotors.Count > 0)
{
key.Remove(key.Length - 1, 1);
}
return key.ToString();
}
private static string RotorRingString(IEnigmaRotors settings)
{
StringBuilder key = new();
foreach (KeyValuePair<EnigmaRotorPosition, IEnigmaRotor> position in settings.Rotors.Reverse().ToArray())
{
key.Append($"{position.Value.RingPosition:00}");
key.Append(KeyDelimiter);
}
if (settings.Rotors.Count > 0)
{
key.Remove(key.Length - 1, 1);
}
return key.ToString();
}
private static string PlugboardString(IEnigmaPlugboard plugboard)
{
StringBuilder key = new();
IReadOnlyDictionary<char, char> substitutions = plugboard.Substitutions();
foreach (KeyValuePair<char, char> pair in substitutions)
{
key.Append(pair.Key);
key.Append(pair.Value);
key.Append(KeyDelimiter);
}
if (substitutions.Count > 0
&& key.Length > 0)
{
key.Remove(key.Length - 1, 1);
}
return key.ToString();
}
private static char GetRandomRotorCurrentSetting() => "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[new Random().Next(0, 25)];
private void Reset()
{
ModeValue = CipherMode.ECB;
PaddingValue = PaddingMode.None;
KeySizeValue = 16;
BlockSizeValue = 16 * 5;
FeedbackSizeValue = 16;
LegalBlockSizesValue = new KeySizes[1];
LegalBlockSizesValue[0] = new KeySizes(0, int.MaxValue, 16);
LegalKeySizesValue = new KeySizes[1];
LegalKeySizesValue[0] = new KeySizes(0, int.MaxValue, 16);
KeyValue = Array.Empty<byte>();
IVValue = Array.Empty<byte>();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
using System.Diagnostics.SymbolStore;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.Reflection.Emit
{
public sealed class MethodBuilder : MethodInfo
{
#region Private Data Members
// Identity
internal string m_strName; // The name of the method
private MethodToken m_tkMethod; // The token of this method
private ModuleBuilder m_module;
internal TypeBuilder m_containingType;
// IL
private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
internal LocalSymInfo? m_localSymInfo; // keep track debugging local information
internal ILGenerator? m_ilGenerator; // Null if not used.
private byte[]? m_ubBody; // The IL for the method
private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
private bool m_bIsGlobalMethod;
private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not.
// Attributes
private MethodAttributes m_iAttributes;
private CallingConventions m_callingConvention;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
private SignatureHelper? m_signature;
internal Type[]? m_parameterTypes;
private Type m_returnType;
private Type[]? m_returnTypeRequiredCustomModifiers;
private Type[]? m_returnTypeOptionalCustomModifiers;
private Type[][]? m_parameterTypeRequiredCustomModifiers;
private Type[][]? m_parameterTypeOptionalCustomModifiers;
// Generics
private GenericTypeParameterBuilder[]? m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
if (mod == null)
throw new ArgumentNullException(nameof(mod));
if (parameterTypes != null)
{
foreach (Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException(nameof(parameterTypes));
}
}
m_strName = name;
m_module = mod;
m_containingType = type;
m_returnType = returnType ?? typeof(void);
if ((attributes & MethodAttributes.Static) == 0)
{
// turn on the has this calling convention
callingConvention |= CallingConventions.HasThis;
}
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
throw new ArgumentException(SR.Arg_NoStaticVirtual);
}
#if !FEATURE_DEFAULT_INTERFACES
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
{
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
(MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
}
}
#endif
m_callingConvention = callingConvention;
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length);
}
else
{
m_parameterTypes = null;
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
m_bIsBaked = false;
m_fInitLocals = true;
m_localSymInfo = new LocalSymInfo();
m_ubBody = null;
m_ilGenerator = null;
// Default is managed IL. Manged IL has bit flag 0x0020 set off
m_dwMethodImplFlags = MethodImplAttributes.IL;
}
#endregion
#region Internal Members
internal void CheckContext(params Type[]?[]? typess)
{
m_module.CheckContext(typess);
}
internal void CheckContext(params Type?[]? types)
{
m_module.CheckContext(types);
}
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
if (il == null)
{
throw new ArgumentNullException(nameof(il));
}
__ExceptionInfo[] excp;
int counter = 0;
int[] filterAddrs;
int[] catchAddrs;
int[] catchEndAddrs;
Type[] catchClass;
int[] type;
int numCatch;
int start, end;
ModuleBuilder dynMod = (ModuleBuilder)m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
{
// you don't need to call DefineBody when you get your ILGenerator
// through MethodBuilder::GetILGenerator.
//
throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
}
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
}
m_ubBody = il.BakeByteArray();
m_mdMethodFixups = il.GetTokenFixups();
// Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions()!;
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
m_exceptions = new ExceptionHandler[numExceptions];
for (int i = 0; i < excp.Length; i++)
{
filterAddrs = excp[i].GetFilterAddresses();
catchAddrs = excp[i].GetCatchAddresses();
catchEndAddrs = excp[i].GetCatchEndAddresses();
catchClass = excp[i].GetCatchClass();
numCatch = excp[i].GetNumberOfCatches();
start = excp[i].GetStartAddress();
end = excp[i].GetEndAddress();
type = excp[i].GetExceptionTypes();
for (int j = 0; j < numCatch; j++)
{
int tkExceptionClass = 0;
if (catchClass[j] != null)
{
tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
}
switch (type[j])
{
case __ExceptionInfo.None:
case __ExceptionInfo.Fault:
case __ExceptionInfo.Filter:
m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
case __ExceptionInfo.Finally:
m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
}
}
}
}
m_bIsBaked = true;
if (dynMod.GetSymWriter() != null)
{
// set the debugging information such as scope and line number
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter()!;
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
// call OpenScope because OpenMethod no longer implicitly creating
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
if (m_symCustomAttrs != null)
{
foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter()!.SetSymAttribute(
new SymbolToken(MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
}
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
symWriter.CloseScope(il.ILOffset);
symWriter.CloseMethod();
}
}
// This is only called from TypeBuilder.CreateType after the method has been created
internal void ReleaseBakedStructures()
{
if (!m_bIsBaked)
{
// We don't need to do anything here if we didn't baked the method body
return;
}
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes() => m_parameterTypes ??= Array.Empty<Type>();
internal static Type? GetMethodBaseReturnType(MethodBase? method)
{
if (method is MethodInfo mi)
{
return mi.ReturnType;
}
else if (method is ConstructorInfo ci)
{
return ci.GetReturnType();
}
else
{
Debug.Fail("We should never get here!");
return null;
}
}
internal void SetToken(MethodToken token)
{
m_tkMethod = token;
}
internal byte[]? GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
internal int[]? GetTokenFixups()
{
return m_mdMethodFixups;
}
internal SignatureHelper GetMethodSignature()
{
m_parameterTypes ??= Array.Empty<Type>();
m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
return m_signature;
}
// Returns a buffer whose initial signatureLength bytes contain encoded local signature.
internal byte[] GetLocalSignature(out int signatureLength)
{
if (m_localSignature != null)
{
signatureLength = m_localSignature.Length;
return m_localSignature;
}
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
{
// If user is using ILGenerator::DeclareLocal, then get local signaturefrom there.
return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
}
}
return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
}
internal int GetMaxStack()
{
if (m_ilGenerator != null)
{
return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
}
else
{
// this is the case when client provide an array of IL byte stream rather than going through ILGenerator.
return m_maxStack;
}
}
internal ExceptionHandler[]? GetExceptionHandlers()
{
return m_exceptions;
}
internal int ExceptionHandlerCount => m_exceptions != null ? m_exceptions.Length : 0;
internal static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp)
{
int num = 0;
if (excp == null)
{
return 0;
}
for (int i = 0; i < excp.Length; i++)
{
num += excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
{
return m_containingType != null && m_containingType.IsCreated();
}
internal TypeBuilder GetTypeBuilder()
{
return m_containingType;
}
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
#endregion
#region Object Overrides
public override bool Equals(object? obj)
{
if (!(obj is MethodBuilder))
{
return false;
}
if (!this.m_strName.Equals(((MethodBuilder)obj).m_strName))
{
return false;
}
if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes))
{
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
if (thatSig.Equals(GetMethodSignature()))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.m_strName.GetHashCode();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(1000);
sb.Append("Name: ").Append(m_strName).AppendLine(" ");
sb.Append("Attributes: ").Append((int)m_iAttributes).AppendLine();
sb.Append("Method Signature: ").Append(GetMethodSignature()).AppendLine();
sb.AppendLine();
return sb.ToString();
}
#endregion
#region MemberInfo Overrides
public override string Name => m_strName;
internal int MetadataTokenInternal => GetToken().Token;
public override Module Module => m_containingType.Module;
public override Type? DeclaringType
{
get
{
if (m_containingType.m_isHiddenGlobalType)
return null;
return m_containingType;
}
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder();
public override Type? ReflectedType => DeclaringType;
#endregion
#region MethodBase Overrides
public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_dwMethodImplFlags;
}
public override MethodAttributes Attributes => m_iAttributes;
public override CallingConventions CallingConvention => m_callingConvention;
public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule);
public override bool IsSecurityCritical => true;
public override bool IsSecuritySafeCritical => false;
public override bool IsSecurityTransparent => false;
#endregion
#region MethodInfo Overrides
public override MethodInfo GetBaseDefinition()
{
return this;
}
public override Type ReturnType => m_returnType;
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.GetParameters();
}
public override ParameterInfo ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.ReturnParameter;
}
}
#endregion
#region ICustomAttributeProvider Implementation
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
#endregion
#region Generic Members
public override bool IsGenericMethodDefinition => m_bIsGenMethDef;
public override bool ContainsGenericParameters => throw new NotSupportedException();
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod => m_inst != null;
public override Type[] GetGenericArguments() => m_inst ?? Array.Empty<Type>();
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
if (m_inst != null)
throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet);
for (int i = 0; i < names.Length; i++)
if (names[i] == null)
throw new ArgumentNullException(nameof(names));
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked);
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
for (int i = 0; i < names.Length; i++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); }
#endregion
#region Public Members
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
// we only "tokenize" a method when requested. But the order in which the methods are tokenized
// didn't change: the same order the MethodBuilders are constructed. The recursion introduced
// will overflow the stack when there are many methods on the same type (10000 in my experiment).
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
// I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
MethodBuilder? currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
// We need to lock here to prevent a method from being "tokenized" twice.
// We don't need to synchronize this with Type.DefineMethod because it only appends newly
// constructed MethodBuilders to the end of m_listMethods
lock (m_containingType.m_listMethods)
{
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
// If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller
// than the index of the current method.
for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i)
{
currentMethod = m_containingType.m_listMethods[i];
currentToken = currentMethod.GetTokenNoLock();
if (currentMethod == this)
break;
}
m_containingType.m_lastTokenizedMethod = i;
}
Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
Debug.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
private MethodToken GetTokenNoLock()
{
Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
ModuleBuilder module = m_module;
int token = TypeBuilder.DefineMethod(new QCallModule(ref module), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);
m_tkMethod = new MethodToken(token);
if (m_inst != null)
foreach (GenericTypeParameterBuilder tb in m_inst)
if (!tb.m_type.IsCreated()) tb.m_type.CreateType();
TypeBuilder.SetMethodImpl(new QCallModule(ref module), token, m_dwMethodImplFlags);
return m_tkMethod;
}
public void SetParameters(params Type[] parameterTypes)
{
CheckContext(parameterTypes);
SetSignature(null, null, null, parameterTypes, null, null);
}
public void SetReturnType(Type? returnType)
{
CheckContext(returnType);
SetSignature(returnType, null, null, null, null, null);
}
public void SetSignature(
Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
if (m_tkMethod.Token != 0)
return;
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
ThrowIfGeneric();
if (returnType != null)
{
m_returnType = returnType;
}
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
attributes &= ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
}
private List<SymCustomAttr>? m_symCustomAttrs;
private struct SymCustomAttr
{
public string m_name;
public byte[] m_data;
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
m_dwMethodImplFlags = attributes;
m_canBeRuntimeImpl = true;
ModuleBuilder module = m_module;
TypeBuilder.SetMethodImpl(new QCallModule(ref module), MetadataTokenInternal, attributes);
}
public ILGenerator GetILGenerator()
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
return m_ilGenerator ??= new ILGenerator(this);
}
public ILGenerator GetILGenerator(int size)
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
return m_ilGenerator ??= new ILGenerator(this, size);
}
private void ThrowIfShouldNotHaveBody()
{
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
m_isDllImport)
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody);
}
}
public bool InitLocals
{
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
get { ThrowIfGeneric(); return m_fInitLocals; }
set { ThrowIfGeneric(); m_fInitLocals = value; }
}
public Module GetModule()
{
return GetModuleBuilder();
}
public string Signature => GetMethodSignature().ToString();
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con is null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute is null)
throw new ArgumentNullException(nameof(binaryAttribute));
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal,
((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
if (IsKnownCA(con))
ParseCA(con);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con);
}
// this method should return true for any and every ca that requires more work
// than just setting the ca
private static bool IsKnownCA(ConstructorInfo con)
{
Type? caType = con.DeclaringType;
return caType == typeof(MethodImplAttribute) || caType == typeof(DllImportAttribute);
}
private void ParseCA(ConstructorInfo con)
{
Type? caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
// for now we simply set a flag that relaxes the check when saving and
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
else if (caType == typeof(DllImportAttribute))
{
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
}
internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
#endregion
}
internal class LocalSymInfo
{
// This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
internal string[] m_strName = null!; // All these arrys initialized in helper method
internal byte[][] m_ubSignature = null!;
internal int[] m_iLocalSlot = null!;
internal int[] m_iStartOffset = null!;
internal int[] m_iEndOffset = null!;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
internal string[] m_namespace = null!;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
#region Constructor
internal LocalSymInfo()
{
// initialize data variables
m_iLocalSymCount = 0;
m_iNameSpaceCount = 0;
}
#endregion
#region Private Members
private void EnsureCapacityNamespace()
{
if (m_iNameSpaceCount == 0)
{
m_namespace = new string[InitialSize];
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
string[] strTemp = new string[checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, strTemp, m_iNameSpaceCount);
m_namespace = strTemp;
}
}
private void EnsureCapacity()
{
if (m_iLocalSymCount == 0)
{
// First time. Allocate the arrays.
m_strName = new string[InitialSize];
m_ubSignature = new byte[InitialSize][];
m_iLocalSlot = new int[InitialSize];
m_iStartOffset = new int[InitialSize];
m_iEndOffset = new int[InitialSize];
}
else if (m_iLocalSymCount == m_strName.Length)
{
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
int[] temp = new int[newSize];
Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount);
m_iLocalSlot = temp;
temp = new int[newSize];
Array.Copy(m_iStartOffset, temp, m_iLocalSymCount);
m_iStartOffset = temp;
temp = new int[newSize];
Array.Copy(m_iEndOffset, temp, m_iLocalSymCount);
m_iEndOffset = temp;
string[] strTemp = new string[newSize];
Array.Copy(m_strName, strTemp, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount);
m_ubSignature = ubTemp;
}
}
#endregion
#region Internal Members
internal void AddLocalSymInfo(string strName, byte[] signature, int slot, int startOffset, int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
m_iStartOffset[m_iLocalSymCount] = startOffset;
m_iEndOffset[m_iLocalSymCount] = endOffset;
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
checked { m_iLocalSymCount++; }
}
internal void AddUsingNamespace(string strNamespace)
{
EnsureCapacityNamespace();
m_namespace[m_iNameSpaceCount] = strNamespace;
checked { m_iNameSpaceCount++; }
}
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
for (i = 0; i < m_iLocalSymCount; i++)
{
symWriter.DefineLocalVariable(
m_strName[i],
FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
0, // addr2 is not used yet
0, // addr3 is not used
m_iStartOffset[i],
m_iEndOffset[i]);
}
for (i = 0; i < m_iNameSpaceCount; i++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
}
#endregion
}
/// <summary>
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
internal readonly int m_filterOffset;
internal readonly int m_handlerStartOffset;
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
#region Constructors
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
Debug.Assert(tryStartOffset >= 0);
Debug.Assert(tryEndOffset >= 0);
Debug.Assert(filterOffset >= 0);
Debug.Assert(handlerStartOffset >= 0);
Debug.Assert(handlerEndOffset >= 0);
Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerStartOffset;
m_handlerEndOffset = handlerEndOffset;
m_kind = (ExceptionHandlingClauseOptions)kind;
m_exceptionClass = exceptionTypeToken;
}
private static bool IsValidKind(ExceptionHandlingClauseOptions kind)
{
switch (kind)
{
case ExceptionHandlingClauseOptions.Clause:
case ExceptionHandlingClauseOptions.Filter:
case ExceptionHandlingClauseOptions.Finally:
case ExceptionHandlingClauseOptions.Fault:
return true;
default:
return false;
}
}
#endregion
#region Equality
public override int GetHashCode()
{
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
public override bool Equals(object? obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
public bool Equals(ExceptionHandler other)
{
return
other.m_exceptionClass == m_exceptionClass &&
other.m_tryStartOffset == m_tryStartOffset &&
other.m_tryEndOffset == m_tryEndOffset &&
other.m_filterOffset == m_filterOffset &&
other.m_handlerStartOffset == m_handlerStartOffset &&
other.m_handlerEndOffset == m_handlerEndOffset &&
other.m_kind == m_kind;
}
public static bool operator ==(ExceptionHandler left, ExceptionHandler right) => left.Equals(right);
public static bool operator !=(ExceptionHandler left, ExceptionHandler right) => !left.Equals(right);
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main" namespace.
/// </summary>
public static class X15
{
/// <summary>
/// Defines the XML namespace associated with the x15 prefix.
/// </summary>
public static readonly XNamespace x15 = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main";
/// <summary>
/// Represents the x15:activeTabTopLevelEntity XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pivotTableUISettings" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />, <see cref="NoNamespace.type" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FieldListActiveTabTopLevelEntity.</description></item>
/// </list>
/// </remarks>
public static readonly XName activeTabTopLevelEntity = x15 + "activeTabTopLevelEntity";
/// <summary>
/// Represents the x15:bounds XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="state" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.endDate" />, <see cref="NoNamespace.startDate" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: BoundsTimelineRange.</description></item>
/// </list>
/// </remarks>
public static readonly XName bounds = x15 + "bounds";
/// <summary>
/// Represents the x15:c XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pivotRow" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="v" />, <see cref="x" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.i" />, <see cref="NoNamespace.t" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotValueCell.</description></item>
/// </list>
/// </remarks>
public static readonly XName c = x15 + "c";
/// <summary>
/// Represents the x15:cachedUniqueName XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="cachedUniqueNames" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.index" />, <see cref="NoNamespace.name" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CachedUniqueName.</description></item>
/// </list>
/// </remarks>
public static readonly XName cachedUniqueName = x15 + "cachedUniqueName";
/// <summary>
/// Represents the x15:cachedUniqueNames XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cachedUniqueName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CachedUniqueNames.</description></item>
/// </list>
/// </remarks>
public static readonly XName cachedUniqueNames = x15 + "cachedUniqueNames";
/// <summary>
/// Represents the x15:cacheHierarchy XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.aggregatedColumn" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CacheHierarchy.</description></item>
/// </list>
/// </remarks>
public static readonly XName cacheHierarchy = x15 + "cacheHierarchy";
/// <summary>
/// Represents the x15:calculatedMember XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.measure" />, <see cref="NoNamespace.measureGroup" />, <see cref="NoNamespace.numberFormat" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CalculatedMember.</description></item>
/// </list>
/// </remarks>
public static readonly XName calculatedMember = x15 + "calculatedMember";
/// <summary>
/// Represents the x15:connection XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dataFeedPr" />, <see cref="modelTextPr" />, <see cref="oledbPr" />, <see cref="rangePr" />, <see cref="textPr" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.autoDelete" />, <see cref="NoNamespace.excludeFromRefreshAll" />, <see cref="NoNamespace.id" />, <see cref="NoNamespace.model" />, <see cref="NoNamespace.usedByAddin" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Connection.</description></item>
/// </list>
/// </remarks>
public static readonly XName connection = x15 + "connection";
/// <summary>
/// Represents the x15:dataFeedPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="connection" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dbTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.connection" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataFeedProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName dataFeedPr = x15 + "dataFeedPr";
/// <summary>
/// Represents the x15:dataField XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.isCountDistinct" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataField.</description></item>
/// </list>
/// </remarks>
public static readonly XName dataField = x15 + "dataField";
/// <summary>
/// Represents the x15:dataModel XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="extLst" />, <see cref="modelRelationships" />, <see cref="modelTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.minVersionLoad" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataModel.</description></item>
/// </list>
/// </remarks>
public static readonly XName dataModel = x15 + "dataModel";
/// <summary>
/// Represents the x15:dbCommand XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="oledbPr" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.text" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DbCommand.</description></item>
/// </list>
/// </remarks>
public static readonly XName dbCommand = x15 + "dbCommand";
/// <summary>
/// Represents the x15:dbTable XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dbTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DbTable.</description></item>
/// </list>
/// </remarks>
public static readonly XName dbTable = x15 + "dbTable";
/// <summary>
/// Represents the x15:dbTables XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dataFeedPr" />, <see cref="oledbPr" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dbTable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DbTables.</description></item>
/// </list>
/// </remarks>
public static readonly XName dbTables = x15 + "dbTables";
/// <summary>
/// Represents the x15:dxfs XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X.dxf" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.count" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DifferentialFormats.</description></item>
/// </list>
/// </remarks>
public static readonly XName dxfs = x15 + "dxfs";
/// <summary>
/// Represents the x15:extLst XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dataModel" />, <see cref="pivotTableUISettings" />, <see cref="state" />, <see cref="tableSlicerCache" />, <see cref="timeline" />, <see cref="timelineCacheDefinition" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ExtensionList.</description></item>
/// </list>
/// </remarks>
public static readonly XName extLst = x15 + "extLst";
/// <summary>
/// Represents the x15:modelRelationship XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="modelRelationships" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.fromColumn" />, <see cref="NoNamespace.fromTable" />, <see cref="NoNamespace.toColumn" />, <see cref="NoNamespace.toTable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ModelRelationship.</description></item>
/// </list>
/// </remarks>
public static readonly XName modelRelationship = x15 + "modelRelationship";
/// <summary>
/// Represents the x15:modelRelationships XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dataModel" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="modelRelationship" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ModelRelationships.</description></item>
/// </list>
/// </remarks>
public static readonly XName modelRelationships = x15 + "modelRelationships";
/// <summary>
/// Represents the x15:modelTable XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="modelTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.connection" />, <see cref="NoNamespace.id" />, <see cref="NoNamespace.name" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ModelTable.</description></item>
/// </list>
/// </remarks>
public static readonly XName modelTable = x15 + "modelTable";
/// <summary>
/// Represents the x15:modelTables XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dataModel" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="modelTable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ModelTables.</description></item>
/// </list>
/// </remarks>
public static readonly XName modelTables = x15 + "modelTables";
/// <summary>
/// Represents the x15:modelTextPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="connection" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.headers" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ModelTextProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName modelTextPr = x15 + "modelTextPr";
/// <summary>
/// Represents the x15:movingPeriodState XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />, <see cref="state" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.movingMultiple" />, <see cref="NoNamespace.movingPeriod" />, <see cref="NoNamespace.referenceDateBegin" />, <see cref="NoNamespace.referenceMultiple" />, <see cref="NoNamespace.referencePeriod" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: MovingPeriodState.</description></item>
/// </list>
/// </remarks>
public static readonly XName movingPeriodState = x15 + "movingPeriodState";
/// <summary>
/// Represents the x15:oledbPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="connection" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dbCommand" />, <see cref="dbTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.connection" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: OleDbPrpoperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName oledbPr = x15 + "oledbPr";
/// <summary>
/// Represents the x15:pivotCacheDecoupled XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.decoupled" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotCacheDecoupled.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotCacheDecoupled = x15 + "pivotCacheDecoupled";
/// <summary>
/// Represents the x15:pivotCacheIdVersion XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.cacheIdCreatedVersion" />, <see cref="NoNamespace.cacheIdSupportedVersion" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotCacheIdVersion.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotCacheIdVersion = x15 + "pivotCacheIdVersion";
/// <summary>
/// Represents the x15:pivotCaches XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X.pivotCache" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotCaches.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotCaches = x15 + "pivotCaches";
/// <summary>
/// Represents the x15:pivotFilter XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.useWholeDay" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotFilter.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotFilter = x15 + "pivotFilter";
/// <summary>
/// Represents the x15:pivotRow XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pivotTableData" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="c" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.count" />, <see cref="NoNamespace.r" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotRow.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotRow = x15 + "pivotRow";
/// <summary>
/// Represents the x15:pivotTable XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pivotTables" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />, <see cref="NoNamespace.tabId" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCachePivotTable.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTable = x15 + "pivotTable";
/// <summary>
/// Represents the x15:pivotTableData XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="pivotRow" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.cacheId" />, <see cref="NoNamespace.columnCount" />, <see cref="NoNamespace.rowCount" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotTableData.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTableData = x15 + "pivotTableData";
/// <summary>
/// Represents the x15:pivotTableReference XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="pivotTableReferences" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="R.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotTableReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTableReference = x15 + "pivotTableReference";
/// <summary>
/// Represents the x15:pivotTableReferences XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="pivotTableReference" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotTableReferences.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTableReferences = x15 + "pivotTableReferences";
/// <summary>
/// Represents the x15:pivotTables XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineCacheDefinition" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="pivotTable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCachePivotTables.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTables = x15 + "pivotTables";
/// <summary>
/// Represents the x15:pivotTableUISettings XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="activeTabTopLevelEntity" />, <see cref="extLst" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.relNeededHidden" />, <see cref="NoNamespace.sourceDataName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotTableUISettings.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotTableUISettings = x15 + "pivotTableUISettings";
/// <summary>
/// Represents the x15:queryTable XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.clipped" />, <see cref="NoNamespace.drillThrough" />, <see cref="NoNamespace.sourceDataName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: QueryTable.</description></item>
/// </list>
/// </remarks>
public static readonly XName queryTable = x15 + "queryTable";
/// <summary>
/// Represents the x15:rangePr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="connection" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.sourceName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: RangeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName rangePr = x15 + "rangePr";
/// <summary>
/// Represents the x15:selection XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="state" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.endDate" />, <see cref="NoNamespace.startDate" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SelectionTimelineRange.</description></item>
/// </list>
/// </remarks>
public static readonly XName selection = x15 + "selection";
/// <summary>
/// Represents the x15:slicerCacheHideItemsWithNoData XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="slicerCacheOlapLevelName" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.count" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SlicerCacheHideItemsWithNoData.</description></item>
/// </list>
/// </remarks>
public static readonly XName slicerCacheHideItemsWithNoData = x15 + "slicerCacheHideItemsWithNoData";
/// <summary>
/// Represents the x15:slicerCacheOlapLevelName XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="slicerCacheHideItemsWithNoData" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.count" />, <see cref="NoNamespace.uniqueName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SlicerCacheOlapLevelName.</description></item>
/// </list>
/// </remarks>
public static readonly XName slicerCacheOlapLevelName = x15 + "slicerCacheOlapLevelName";
/// <summary>
/// Represents the x15:slicerCachePivotTables XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X14.pivotTable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SlicerCachePivotTables.</description></item>
/// </list>
/// </remarks>
public static readonly XName slicerCachePivotTables = x15 + "slicerCachePivotTables";
/// <summary>
/// Represents the x15:slicerCaches XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X14.slicerCache" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SlicerCaches.</description></item>
/// </list>
/// </remarks>
public static readonly XName slicerCaches = x15 + "slicerCaches";
/// <summary>
/// Represents the x15:state XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineCacheDefinition" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="bounds" />, <see cref="extLst" />, <see cref="movingPeriodState" />, <see cref="selection" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.filterId" />, <see cref="NoNamespace.filterPivotName" />, <see cref="NoNamespace.filterTabId" />, <see cref="NoNamespace.filterType" />, <see cref="NoNamespace.lastRefreshVersion" />, <see cref="NoNamespace.minimalRefreshVersion" />, <see cref="NoNamespace.pivotCacheId" />, <see cref="NoNamespace.singleRangeFilterState" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineState.</description></item>
/// </list>
/// </remarks>
public static readonly XName state = x15 + "state";
/// <summary>
/// Represents the x15:tableSlicerCache XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="extLst" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.column" />, <see cref="NoNamespace.crossFilter" />, <see cref="NoNamespace.customListSort" />, <see cref="NoNamespace.sortOrder" />, <see cref="NoNamespace.tableId" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TableSlicerCache.</description></item>
/// </list>
/// </remarks>
public static readonly XName tableSlicerCache = x15 + "tableSlicerCache";
/// <summary>
/// Represents the x15:textPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="connection" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X.textFields" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.characterSet" />, <see cref="NoNamespace.codePage" />, <see cref="NoNamespace.comma" />, <see cref="NoNamespace.consecutive" />, <see cref="NoNamespace.@decimal" />, <see cref="NoNamespace.delimited" />, <see cref="NoNamespace.delimiter" />, <see cref="NoNamespace.fileType" />, <see cref="NoNamespace.firstRow" />, <see cref="NoNamespace.prompt" />, <see cref="NoNamespace.qualifier" />, <see cref="NoNamespace.semicolon" />, <see cref="NoNamespace.sourceFile" />, <see cref="NoNamespace.space" />, <see cref="NoNamespace.tab" />, <see cref="NoNamespace.thousands" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TextProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName textPr = x15 + "textPr";
/// <summary>
/// Represents the x15:timeline XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelines" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="extLst" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.cache" />, <see cref="NoNamespace.caption" />, <see cref="NoNamespace.level" />, <see cref="NoNamespace.name" />, <see cref="NoNamespace.scrollPosition" />, <see cref="NoNamespace.selectionLevel" />, <see cref="NoNamespace.showHeader" />, <see cref="NoNamespace.showHorizontalScrollbar" />, <see cref="NoNamespace.showSelectionLabel" />, <see cref="NoNamespace.showTimeLevel" />, <see cref="NoNamespace.style" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Timeline.</description></item>
/// </list>
/// </remarks>
public static readonly XName timeline = x15 + "timeline";
/// <summary>
/// Represents the x15:timelineCacheDefinition XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following child XML elements: <see cref="extLst" />, <see cref="pivotTables" />, <see cref="state" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />, <see cref="NoNamespace.sourceName" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCacheDefinition.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineCacheDefinition = x15 + "timelineCacheDefinition";
/// <summary>
/// Represents the x15:timelineCachePivotCaches XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="X.pivotCache" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCachePivotCaches.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineCachePivotCaches = x15 + "timelineCachePivotCaches";
/// <summary>
/// Represents the x15:timelineCacheRef XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineCacheRefs" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="R.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCacheReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineCacheRef = x15 + "timelineCacheRef";
/// <summary>
/// Represents the x15:timelineCacheRefs XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="timelineCacheRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineCacheReferences.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineCacheRefs = x15 + "timelineCacheRefs";
/// <summary>
/// Represents the x15:timelinePivotCacheDefinition XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.timelineData" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelinePivotCacheDefinition.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelinePivotCacheDefinition = x15 + "timelinePivotCacheDefinition";
/// <summary>
/// Represents the x15:timelineRef XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineRefs" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="R.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineRef = x15 + "timelineRef";
/// <summary>
/// Represents the x15:timelineRefs XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="timelineRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineReferences.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineRefs = x15 + "timelineRefs";
/// <summary>
/// Represents the x15:timelines XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following child XML elements: <see cref="timeline" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Timelines.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelines = x15 + "timelines";
/// <summary>
/// Represents the x15:timelineStyle XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineStyles" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="timelineStyleElements" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineStyle.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineStyle = x15 + "timelineStyle";
/// <summary>
/// Represents the x15:timelineStyleElement XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineStyleElements" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.dxfId_" />, <see cref="NoNamespace.type" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineStyleElement.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineStyleElement = x15 + "timelineStyleElement";
/// <summary>
/// Represents the x15:timelineStyleElements XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="timelineStyle" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="timelineStyleElement" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineStyleElements.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineStyleElements = x15 + "timelineStyleElements";
/// <summary>
/// Represents the x15:timelineStyles XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="timelineStyle" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.defaultTimelineStyle" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TimelineStyles.</description></item>
/// </list>
/// </remarks>
public static readonly XName timelineStyles = x15 + "timelineStyles";
/// <summary>
/// Represents the x15:v XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="c" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Xstring.</description></item>
/// </list>
/// </remarks>
public static readonly XName v = x15 + "v";
/// <summary>
/// Represents the x15:webExtension XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="webExtensions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="XNE.f" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.appRef_" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: WebExtension.</description></item>
/// </list>
/// </remarks>
public static readonly XName webExtension = x15 + "webExtension";
/// <summary>
/// Represents the x15:webExtensions XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="webExtension" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: WebExtensions.</description></item>
/// </list>
/// </remarks>
public static readonly XName webExtensions = x15 + "webExtensions";
/// <summary>
/// Represents the x15:workbookPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="X.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.chartTrackingRefBase" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: WorkbookProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName workbookPr = x15 + "workbookPr";
/// <summary>
/// Represents the x15:x XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="c" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.b" />, <see cref="NoNamespace.bc" />, <see cref="NoNamespace.fc" />, <see cref="NoNamespace.i" />, <see cref="NoNamespace.@in" />, <see cref="NoNamespace.st" />, <see cref="NoNamespace.un" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotValueCellExtra.</description></item>
/// </list>
/// </remarks>
public static readonly XName x = x15 + "x";
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public interface IAssemblyResolver : IDisposable {
AssemblyDefinition Resolve (AssemblyNameReference name);
AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters);
}
public interface IMetadataResolver {
TypeDefinition Resolve (TypeReference type);
FieldDefinition Resolve (FieldReference field);
MethodDefinition Resolve (MethodReference method);
}
#if !NET_CORE
[Serializable]
#endif
public sealed class ResolutionException : Exception {
readonly MemberReference member;
public MemberReference Member {
get { return member; }
}
public IMetadataScope Scope {
get {
var type = member as TypeReference;
if (type != null)
return type.Scope;
var declaring_type = member.DeclaringType;
if (declaring_type != null)
return declaring_type.Scope;
throw new NotSupportedException ();
}
}
public ResolutionException (MemberReference member)
: base ("Failed to resolve " + member.FullName)
{
if (member == null)
throw new ArgumentNullException ("member");
this.member = member;
}
#if !NET_CORE
ResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
public class MetadataResolver : IMetadataResolver {
readonly IAssemblyResolver assembly_resolver;
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
}
public MetadataResolver (IAssemblyResolver assemblyResolver)
{
if (assemblyResolver == null)
throw new ArgumentNullException ("assemblyResolver");
assembly_resolver = assemblyResolver;
}
public virtual TypeDefinition Resolve (TypeReference type)
{
Mixin.CheckType (type);
type = type.GetElementType ();
var scope = type.Scope;
if (scope == null)
return null;
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
var assembly = assembly_resolver.Resolve ((AssemblyNameReference) scope);
if (assembly == null)
return null;
return GetType (assembly.MainModule, type);
case MetadataScopeType.ModuleDefinition:
return GetType ((ModuleDefinition) scope, type);
case MetadataScopeType.ModuleReference:
var modules = type.Module.Assembly.Modules;
var module_ref = (ModuleReference) scope;
for (int i = 0; i < modules.Count; i++) {
var netmodule = modules [i];
if (netmodule.Name == module_ref.Name)
return GetType (netmodule, type);
}
break;
}
throw new NotSupportedException ();
}
static TypeDefinition GetType (ModuleDefinition module, TypeReference reference)
{
var type = GetTypeDefinition (module, reference);
if (type != null)
return type;
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++) {
var exported_type = exported_types [i];
if (exported_type.Name != reference.Name)
continue;
if (exported_type.Namespace != reference.Namespace)
continue;
return exported_type.Resolve ();
}
return null;
}
static TypeDefinition GetTypeDefinition (ModuleDefinition module, TypeReference type)
{
if (!type.IsNested)
return module.GetType (type.Namespace, type.Name);
var declaring_type = type.DeclaringType.Resolve ();
if (declaring_type == null)
return null;
return declaring_type.GetNestedType (type.TypeFullName ());
}
public virtual FieldDefinition Resolve (FieldReference field)
{
Mixin.CheckField (field);
var type = Resolve (field.DeclaringType);
if (type == null)
return null;
if (!type.HasFields)
return null;
return GetField (type, field);
}
FieldDefinition GetField (TypeDefinition type, FieldReference reference)
{
while (type != null) {
var field = GetField (type.Fields, reference);
if (field != null)
return field;
if (type.BaseType == null)
return null;
type = Resolve (type.BaseType);
}
return null;
}
static FieldDefinition GetField (Collection<FieldDefinition> fields, FieldReference reference)
{
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (field.Name != reference.Name)
continue;
if (!AreSame (field.FieldType, reference.FieldType))
continue;
return field;
}
return null;
}
public virtual MethodDefinition Resolve (MethodReference method)
{
Mixin.CheckMethod (method);
var type = Resolve (method.DeclaringType);
if (type == null)
return null;
method = method.GetElementMethod ();
if (!type.HasMethods)
return null;
return GetMethod (type, method);
}
MethodDefinition GetMethod (TypeDefinition type, MethodReference reference)
{
while (type != null) {
var method = GetMethod (type.Methods, reference);
if (method != null)
return method;
if (type.BaseType == null)
return null;
type = Resolve (type.BaseType);
}
return null;
}
public static MethodDefinition GetMethod (Collection<MethodDefinition> methods, MethodReference reference)
{
for (int i = 0; i < methods.Count; i++) {
var method = methods [i];
if (method.Name != reference.Name)
continue;
if (method.HasGenericParameters != reference.HasGenericParameters)
continue;
if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)
continue;
if (!AreSame (method.ReturnType, reference.ReturnType))
continue;
if (method.IsVarArg () != reference.IsVarArg ())
continue;
if (method.IsVarArg () && IsVarArgCallTo (method, reference))
return method;
if (method.HasParameters != reference.HasParameters)
continue;
if (!method.HasParameters && !reference.HasParameters)
return method;
if (!AreSame (method.Parameters, reference.Parameters))
continue;
return method;
}
return null;
}
static bool AreSame (Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)
{
var count = a.Count;
if (count != b.Count)
return false;
if (count == 0)
return true;
for (int i = 0; i < count; i++)
if (!AreSame (a [i].ParameterType, b [i].ParameterType))
return false;
return true;
}
static bool IsVarArgCallTo (MethodDefinition method, MethodReference reference)
{
if (method.Parameters.Count >= reference.Parameters.Count)
return false;
if (reference.GetSentinelPosition () != method.Parameters.Count)
return false;
for (int i = 0; i < method.Parameters.Count; i++)
if (!AreSame (method.Parameters [i].ParameterType, reference.Parameters [i].ParameterType))
return false;
return true;
}
static bool AreSame (TypeSpecification a, TypeSpecification b)
{
if (!AreSame (a.ElementType, b.ElementType))
return false;
if (a.IsGenericInstance)
return AreSame ((GenericInstanceType) a, (GenericInstanceType) b);
if (a.IsRequiredModifier || a.IsOptionalModifier)
return AreSame ((IModifierType) a, (IModifierType) b);
if (a.IsArray)
return AreSame ((ArrayType) a, (ArrayType) b);
return true;
}
static bool AreSame (ArrayType a, ArrayType b)
{
if (a.Rank != b.Rank)
return false;
// TODO: dimensions
return true;
}
static bool AreSame (IModifierType a, IModifierType b)
{
return AreSame (a.ModifierType, b.ModifierType);
}
static bool AreSame (GenericInstanceType a, GenericInstanceType b)
{
if (a.GenericArguments.Count != b.GenericArguments.Count)
return false;
for (int i = 0; i < a.GenericArguments.Count; i++)
if (!AreSame (a.GenericArguments [i], b.GenericArguments [i]))
return false;
return true;
}
static bool AreSame (GenericParameter a, GenericParameter b)
{
return a.Position == b.Position;
}
static bool AreSame (TypeReference a, TypeReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null || b == null)
return false;
if (a.etype != b.etype)
return false;
if (a.IsGenericParameter)
return AreSame ((GenericParameter) a, (GenericParameter) b);
if (a.IsTypeSpecification ())
return AreSame ((TypeSpecification) a, (TypeSpecification) b);
if (a.Name != b.Name || a.Namespace != b.Namespace)
return false;
//TODO: check scope
return AreSame (a.DeclaringType, b.DeclaringType);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ApigeeConnect.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedConnectionServiceClientSnippets
{
/// <summary>Snippet for ListConnections</summary>
public void ListConnectionsRequestObject()
{
// Snippet: ListConnections(ListConnectionsRequest, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create();
// Initialize request argument(s)
ListConnectionsRequest request = new ListConnectionsRequest
{
ParentAsEndpointName = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"),
};
// Make the request
PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connection item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectionsAsync</summary>
public async Task ListConnectionsRequestObjectAsync()
{
// Snippet: ListConnectionsAsync(ListConnectionsRequest, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync();
// Initialize request argument(s)
ListConnectionsRequest request = new ListConnectionsRequest
{
ParentAsEndpointName = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"),
};
// Make the request
PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connection item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnections</summary>
public void ListConnections()
{
// Snippet: ListConnections(string, string, int?, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/endpoints/[ENDPOINT]";
// Make the request
PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connection item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectionsAsync</summary>
public async Task ListConnectionsAsync()
{
// Snippet: ListConnectionsAsync(string, string, int?, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/endpoints/[ENDPOINT]";
// Make the request
PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connection item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnections</summary>
public void ListConnectionsResourceNames()
{
// Snippet: ListConnections(EndpointName, string, int?, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create();
// Initialize request argument(s)
EndpointName parent = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]");
// Make the request
PagedEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnections(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Connection item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectionsAsync</summary>
public async Task ListConnectionsResourceNamesAsync()
{
// Snippet: ListConnectionsAsync(EndpointName, string, int?, CallSettings)
// Create client
ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync();
// Initialize request argument(s)
EndpointName parent = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]");
// Make the request
PagedAsyncEnumerable<ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Connection item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Connection item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Connection> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Connection item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
namespace newtelligence.DasBlog.Web
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public partial class AggBugsBox : StatisticsListBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region Web Form Designer generated code
protected override void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
this.PreRender += new EventHandler(this.AggBugsBox_PreRender);
}
#endregion
private void BuildAggBugsRow(TableRow row, StatisticsItem item, object objDataService)
{
IBlogDataService dataService = objDataService as IBlogDataService;
HyperLink link = new HyperLink();
string text = SiteUtilities.ClipString(item.identifier, 80);
if (item.identifier != null && item.identifier.Length > 0)
{
int idx;
string id;
// urls in the log have been written using URL Rewriting
if (item.identifier.IndexOf("guid,") > -1)
{
string guid = item.identifier.Substring(0, item.identifier.Length - 5);
idx = guid.IndexOf("guid,");
id = guid.Substring(idx + 5);
}
else
{
idx = item.identifier.IndexOf("guid=");
id = item.identifier.Substring(idx + 5);
}
Entry entry = dataService.GetEntry(id);
if (entry != null && entry.Title != null && entry.Title.Length > 0)
{
text = SiteUtilities.ClipString(entry.Title, 80);
}
}
link.Text = text;
link.NavigateUrl = item.identifier.ToString();
row.Cells[0].Controls.Add(link);
row.Cells[1].Text = item.count.ToString();
}
private void AggBugsBox_PreRender(object sender, EventArgs e)
{
Control root = contentPlaceHolder;
SiteConfig siteConfig = SiteConfig.GetSiteConfig();
ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
string siteRoot = siteConfig.Root.ToUpper();
Dictionary<string, int> aggBugUrls = new Dictionary<string, int>();
Dictionary<string, int> userAgents = new Dictionary<string, int>();
Dictionary<string, int> referrerUrls = new Dictionary<string, int>();
Dictionary<string, int> userDomains = new Dictionary<string, int>();
// get the user's local time
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);
if (Request.QueryString["date"] != null)
{
try
{
DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
utcTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
}
catch (FormatException ex)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
}
}
LogDataItemCollection logItems = new LogDataItemCollection();
logItems.AddRange(logService.GetAggregatorBugHitsForDay(localTime));
if (siteConfig.AdjustDisplayTimeZone)
{
newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
TimeSpan ts = tz.GetUtcOffset(DateTime.UtcNow);
int offset = ts.Hours;
if (offset < 0)
{
logItems.AddRange(logService.GetAggregatorBugHitsForDay(localTime.AddDays(1)));
}
else
{
logItems.AddRange(logService.GetAggregatorBugHitsForDay(localTime.AddDays(-1)));
}
}
foreach (LogDataItem log in logItems)
{
bool exclude = false;
if (log.UrlReferrer != null)
{
exclude = log.UrlReferrer.ToUpper().StartsWith(siteRoot);
}
if (siteConfig.AdjustDisplayTimeZone)
{
if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
{
exclude = true;
}
}
if (!exclude)
{
if (!referrerUrls.ContainsKey(log.UrlReferrer))
{
referrerUrls[log.UrlReferrer] = 0;
}
referrerUrls[log.UrlReferrer] = referrerUrls[log.UrlReferrer] + 1;
if (!aggBugUrls.ContainsKey(log.UrlRequested))
{
aggBugUrls[log.UrlRequested] = 0;
}
aggBugUrls[log.UrlRequested] = aggBugUrls[log.UrlRequested] + 1;
if (!userAgents.ContainsKey(log.UserAgent))
{
userAgents[log.UserAgent] = 0;
}
userAgents[log.UserAgent] = userAgents[log.UserAgent] + 1;
if (!userDomains.ContainsKey(log.UserDomain))
{
userDomains[log.UserDomain] = 0;
}
userDomains[log.UserDomain] = userDomains[log.UserDomain] + 1;
}
}
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(aggBugUrls), resmgr.GetString("text_activity_read_posts"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAggBugsRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(referrerUrls), resmgr.GetString("text_activity_referrer_urls"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildReferrerRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userDomains), resmgr.GetString("text_activity_user_domains"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildUserDomainRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userAgents), resmgr.GetString("text_activity_user_agent"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAgentsRow), dataService));
DataBind();
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Collections;
using Thrift.Processor;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using Thrift.Transport.Server;
namespace ThriftTest
{
internal enum ProtocolChoice
{
Binary,
Compact,
Json
}
internal enum TransportChoice
{
Socket,
TlsSocket,
NamedPipe
}
internal enum BufferChoice
{
None,
Buffered,
Framed
}
internal class ServerParam
{
internal BufferChoice buffering = BufferChoice.None;
internal ProtocolChoice protocol = ProtocolChoice.Binary;
internal TransportChoice transport = TransportChoice.Socket;
internal int port = 9090;
internal string pipe = null;
internal void Parse(List<string> args)
{
for (var i = 0; i < args.Count; i++)
{
if (args[i].StartsWith("--pipe="))
{
pipe = args[i].Substring(args[i].IndexOf("=") + 1);
transport = TransportChoice.NamedPipe;
}
else if (args[i].StartsWith("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
if(transport != TransportChoice.TlsSocket)
transport = TransportChoice.Socket;
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffering = BufferChoice.Buffered;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
buffering = BufferChoice.Framed;
}
else if (args[i] == "--binary" || args[i] == "--protocol=binary")
{
protocol = ProtocolChoice.Binary;
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = ProtocolChoice.Compact;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = ProtocolChoice.Json;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--ssl")
{
transport = TransportChoice.TlsSocket;
}
else if (args[i] == "--help")
{
PrintOptionsHelp();
return;
}
else
{
Console.WriteLine("Invalid argument: {0}", args[i]);
PrintOptionsHelp();
return;
}
}
}
internal static void PrintOptionsHelp()
{
Console.WriteLine("Server options:");
Console.WriteLine(" --pipe=<pipe name>");
Console.WriteLine(" --port=<port number>");
Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
Console.WriteLine(" --processor=<prototype>");
Console.WriteLine(" --ssl");
Console.WriteLine();
}
}
public class TestServer
{
public static int _clientID = -1;
private static readonly TConfiguration Configuration = null; // or new TConfiguration() if needed
public delegate void TestLogDelegate(string msg, params object[] values);
public class MyServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public Task PreServeAsync(CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.FromResult<object>(null);
}
public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task ProcessContextAsync(object serverContext, TTransport transport, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
}
public class TestHandlerAsync : ThriftTest.IAsync
{
public TServer Server { get; set; }
private readonly int handlerID;
private readonly StringBuilder sb = new StringBuilder();
private readonly TestLogDelegate logger;
public TestHandlerAsync()
{
handlerID = Interlocked.Increment(ref _clientID);
logger += TestConsoleLogger;
logger.Invoke("New TestHandler instance created");
}
public void TestConsoleLogger(string msg, params object[] values)
{
sb.Clear();
sb.AppendFormat("handler{0:D3}:", handlerID);
sb.AppendFormat(msg, values);
sb.AppendLine();
Console.Write(sb.ToString());
}
public Task testVoidAsync(CancellationToken cancellationToken)
{
logger.Invoke("testVoid()");
return Task.CompletedTask;
}
public Task<string> testStringAsync(string thing, CancellationToken cancellationToken)
{
logger.Invoke("testString({0})", thing);
return Task.FromResult(thing);
}
public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken)
{
logger.Invoke("testBool({0})", thing);
return Task.FromResult(thing);
}
public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken)
{
logger.Invoke("testByte({0})", thing);
return Task.FromResult(thing);
}
public Task<int> testI32Async(int thing, CancellationToken cancellationToken)
{
logger.Invoke("testI32({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testI64Async(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testI64({0})", thing);
return Task.FromResult(thing);
}
public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken)
{
logger.Invoke("testDouble({0})", thing);
return Task.FromResult(thing);
}
public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken)
{
logger.Invoke("testBinary({0} bytes)", thing.Length);
return Task.FromResult(thing);
}
public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken)
{
logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing);
return Task.FromResult(thing);
}
public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken)
{
var thing = nest.StructThing;
logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.ByteThing,
thing.StringThing,
thing.ByteThing,
thing.I32Thing,
thing.I64Thing,
nest.I32Thing);
return Task.FromResult(nest);
}
public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testStringMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testSet({{");
var first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testList({{");
var first = true;
foreach (var elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken)
{
logger.Invoke("testEnum({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testTypedef({0})", thing);
return Task.FromResult(thing);
}
public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken)
{
logger.Invoke("testMapMap({0})", hello);
var mapmap = new Dictionary<int, Dictionary<int, int>>();
var pos = new Dictionary<int, int>();
var neg = new Dictionary<int, int>();
for (var i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return Task.FromResult(mapmap);
}
public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken)
{
logger.Invoke("testInsanity()");
/** from ThriftTest.thrift:
* So you think you've got this all worked, out eh?
*
* Creates a the returned map with these values and prints it out:
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
* @return map<UserId, map<Numberz,Insanity>> - a map with the above values
*/
var first_map = new Dictionary<Numberz, Insanity>();
var second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = argument;
first_map[Numberz.THREE] = argument;
second_map[Numberz.SIX] = new Insanity();
var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
{
[1] = first_map,
[2] = second_map
};
return Task.FromResult(insane);
}
public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
CancellationToken cancellationToken)
{
logger.Invoke("testMulti()");
var hello = new Xtruct(); ;
hello.StringThing = "Hello2";
hello.ByteThing = arg0;
hello.I32Thing = arg1;
hello.I64Thing = arg2;
return Task.FromResult(hello);
}
public Task testExceptionAsync(string arg, CancellationToken cancellationToken)
{
logger.Invoke("testException({0})", arg);
if (arg == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = arg
};
throw x;
}
if (arg == "TException")
{
throw new TException();
}
return Task.CompletedTask;
}
public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken)
{
logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
if (arg0 == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = "This is an Xception"
};
throw x;
}
if (arg0 == "Xception2")
{
var x = new Xception2
{
ErrorCode = 2002,
StructThing = new Xtruct { StringThing = "This is an Xception2" }
};
throw x;
}
var result = new Xtruct { StringThing = arg1 };
return Task.FromResult(result);
}
public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken)
{
logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult();
logger.Invoke("testOneway finished");
return Task.CompletedTask;
}
}
private static X509Certificate2 GetServerCert()
{
var serverCertName = "server.p12";
var possiblePaths = new List<string>
{
"../../../keys/",
"../../keys/",
"../keys/",
"keys/",
};
string existingPath = null;
foreach (var possiblePath in possiblePaths)
{
var path = Path.GetFullPath(possiblePath + serverCertName);
if (File.Exists(path))
{
existingPath = path;
break;
}
}
if (string.IsNullOrEmpty(existingPath))
{
throw new FileNotFoundException($"Cannot find file: {serverCertName}");
}
var cert = new X509Certificate2(existingPath, "thrift");
return cert;
}
public static int Execute(List<string> args)
{
using (var loggerFactory = new LoggerFactory()) //.AddConsole().AddDebug();
{
var logger = loggerFactory.CreateLogger("Test");
try
{
var param = new ServerParam();
try
{
param.Parse(args);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return 1;
}
// Endpoint transport (mandatory)
TServerTransport trans;
switch (param.transport)
{
case TransportChoice.NamedPipe:
Debug.Assert(param.pipe != null);
trans = new TNamedPipeServerTransport(param.pipe, Configuration);
break;
case TransportChoice.TlsSocket:
var cert = GetServerCert();
if (cert == null || !cert.HasPrivateKey)
{
cert?.Dispose();
throw new InvalidOperationException("Certificate doesn't contain private key");
}
trans = new TTlsServerSocketTransport(param.port, Configuration,
cert,
(sender, certificate, chain, errors) => true,
null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
break;
case TransportChoice.Socket:
default:
trans = new TServerSocketTransport(param.port, Configuration);
break;
}
// Layered transport (mandatory)
TTransportFactory transFactory = null;
switch (param.buffering)
{
case BufferChoice.Framed:
transFactory = new TFramedTransport.Factory();
break;
case BufferChoice.Buffered:
transFactory = new TBufferedTransport.Factory();
break;
default:
Debug.Assert(param.buffering == BufferChoice.None, "unhandled case");
transFactory = null; // no layered transprt
break;
}
// Protocol (mandatory)
TProtocolFactory proto;
switch (param.protocol)
{
case ProtocolChoice.Compact:
proto = new TCompactProtocol.Factory();
break;
case ProtocolChoice.Json:
proto = new TJsonProtocol.Factory();
break;
case ProtocolChoice.Binary:
default:
proto = new TBinaryProtocol.Factory();
break;
}
// Processor
var testHandler = new TestHandlerAsync();
var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
var processorFactory = new TSingletonProcessorFactory(testProcessor);
TServer serverEngine = new TSimpleAsyncServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);
//Server event handler
var serverEvents = new MyServerEventHandler();
serverEngine.SetEventHandler(serverEvents);
// Run it
var where = (!string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
Console.WriteLine("Starting the AsyncBaseServer " + where +
" with processor TPrototypeProcessorFactory prototype factory " +
(param.buffering == BufferChoice.Buffered ? " with buffered transport" : "") +
(param.buffering == BufferChoice.Framed ? " with framed transport" : "") +
(param.transport == TransportChoice.TlsSocket ? " with encryption" : "") +
(param.protocol == ProtocolChoice.Compact ? " with compact protocol" : "") +
(param.protocol == ProtocolChoice.Json ? " with json protocol" : "") +
"...");
serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
Console.ReadLine();
}
catch (Exception x)
{
Console.Error.Write(x);
return 1;
}
Console.WriteLine("done.");
return 0;
}
}
}
}
| |
namespace AgileObjects.AgileMapper.DataSources
{
using System;
using System.Collections.Generic;
#if NET35
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
using Extensions.Internal;
using Members;
internal static class DataSourceSet
{
#region Factory Methods
public static IDataSourceSet For(IDataSource dataSource, IDataSourceSetInfo info)
=> For(dataSource, info, ValueExpressionBuilders.SingleDataSource);
private static IDataSourceSet For(
IDataSource dataSource,
IDataSourceSetInfo info,
Func<IDataSource, IMemberMapperData, Expression> valueBuilder)
{
if (!dataSource.IsValid)
{
return info.MappingContext.IgnoreUnsuccessfulMemberPopulations
? EmptyDataSourceSet.Instance
: new NullDataSourceSet(dataSource);
}
var mapperData = info.MapperData;
if (mapperData.MapperContext.UserConfigurations.HasSourceValueFilters)
{
dataSource = dataSource.WithFilter(mapperData);
}
return new SingleValueDataSourceSet(dataSource, mapperData, valueBuilder);
}
public static IDataSourceSet For(
IList<IDataSource> dataSources,
IDataSourceSetInfo info,
Func<IList<IDataSource>, IMemberMapperData, Expression> valueBuilder)
{
switch (dataSources.Count)
{
case 0:
return EmptyDataSourceSet.Instance;
case 1:
return For(dataSources.First(), info, (ds, md) => valueBuilder.Invoke(new[] { ds }, md));
default:
var mapperData = info.MapperData;
if (TryAdjustToSingleUseableDataSource(ref dataSources, mapperData))
{
goto case 1;
}
if (mapperData.MapperContext.UserConfigurations.HasSourceValueFilters)
{
dataSources = dataSources.WithFilters(mapperData);
}
return new MultipleValueDataSourceSet(dataSources, mapperData, valueBuilder);
}
}
private static bool TryAdjustToSingleUseableDataSource(
ref IList<IDataSource> dataSources,
IMemberMapperData mapperData)
{
var finalDataSource = dataSources.Last();
if (!finalDataSource.IsFallback)
{
return false;
}
var finalValue = finalDataSource.Value;
if (finalValue.NodeType == ExpressionType.Coalesce)
{
// Coalesce between the existing target member value and the fallback:
dataSources[dataSources.Count - 1] = new AdHocDataSource(
finalDataSource.SourceMember,
((BinaryExpression)finalValue).Right,
finalDataSource.Condition,
finalDataSource.Variables);
return false;
}
var targetMemberAccess = mapperData.GetTargetMemberAccess();
if (!ExpressionEvaluation.AreEqual(finalValue, targetMemberAccess))
{
return false;
}
if (dataSources.Count == 2)
{
return true;
}
var dataSourcesWithoutFallback = new IDataSource[dataSources.Count - 1];
dataSourcesWithoutFallback.CopyFrom(dataSources);
dataSources = dataSourcesWithoutFallback;
return false;
}
#endregion
private class NullDataSourceSet : IDataSourceSet
{
private readonly IDataSource _nullDataSource;
public NullDataSourceSet(IDataSource nullDataSource)
{
_nullDataSource = nullDataSource;
}
public bool None => false;
public bool HasValue => false;
public bool IsConditional => false;
public Expression SourceMemberTypeTest => null;
public IList<ParameterExpression> Variables => Constants.EmptyParameters;
public IDataSource this[int index] => _nullDataSource;
public int Count => 1;
public Expression BuildValue() => _nullDataSource.Value;
}
private class SingleValueDataSourceSet : IDataSourceSet
{
private readonly IDataSource _dataSource;
private readonly IMemberMapperData _mapperData;
private readonly Func<IDataSource, IMemberMapperData, Expression> _valueBuilder;
private Expression _value;
public SingleValueDataSourceSet(
IDataSource dataSource,
IMemberMapperData mapperData,
Func<IDataSource, IMemberMapperData, Expression> valueBuilder)
{
_dataSource = dataSource;
_mapperData = mapperData;
_valueBuilder = valueBuilder;
}
public bool None => false;
public bool HasValue => _dataSource.IsValid;
public bool IsConditional => _dataSource.IsConditional;
public Expression SourceMemberTypeTest => _dataSource.SourceMemberTypeTest;
public IList<ParameterExpression> Variables => _dataSource.Variables;
public IDataSource this[int index] => _dataSource;
public int Count => 1;
public Expression BuildValue()
=> _value ??= _valueBuilder.Invoke(_dataSource, _mapperData);
}
private class MultipleValueDataSourceSet : IDataSourceSet
{
private readonly IList<IDataSource> _dataSources;
private readonly IMemberMapperData _mapperData;
private readonly Func<IList<IDataSource>, IMemberMapperData, Expression> _valueBuilder;
private Expression _value;
public MultipleValueDataSourceSet(
IList<IDataSource> dataSources,
IMemberMapperData mapperData,
Func<IList<IDataSource>, IMemberMapperData, Expression> valueBuilder)
{
_dataSources = dataSources;
_mapperData = mapperData;
_valueBuilder = valueBuilder;
var dataSourcesCount = dataSources.Count;
var variables = default(List<ParameterExpression>);
for (var i = 0; i < dataSourcesCount; ++i)
{
var dataSource = dataSources[i];
if (dataSource.IsValid)
{
HasValue = true;
}
if (dataSource.IsConditional)
{
IsConditional = true;
}
if (dataSource.Variables.Any())
{
variables ??= new List<ParameterExpression>();
variables.AddRange(dataSource.Variables);
}
if (dataSource.SourceMemberTypeTest != null)
{
SourceMemberTypeTest = dataSource.SourceMemberTypeTest;
}
}
Variables = variables ?? (IList<ParameterExpression>)Constants.EmptyParameters;
}
public bool None => false;
public bool HasValue { get; }
public bool IsConditional { get; }
public Expression SourceMemberTypeTest { get; }
public IList<ParameterExpression> Variables { get; }
public IDataSource this[int index] => _dataSources[index];
public int Count => _dataSources.Count;
public Expression BuildValue()
=> _value ??= _valueBuilder.Invoke(_dataSources, _mapperData);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reactive.Disposables;
using System.Runtime.InteropServices;
using System.Threading;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.OpenGL;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Threading;
using Avalonia.Utilities;
using Avalonia.Win32.Input;
using Avalonia.Win32.Interop;
using static Avalonia.Win32.Interop.UnmanagedMethods;
namespace Avalonia
{
public static class Win32ApplicationExtensions
{
public static T UseWin32<T>(
this T builder)
where T : AppBuilderBase<T>, new()
{
return builder.UseWindowingSubsystem(
() => Win32.Win32Platform.Initialize(
AvaloniaLocator.Current.GetService<Win32PlatformOptions>() ?? new Win32PlatformOptions()),
"Win32");
}
}
/// <summary>
/// Platform-specific options which apply to Windows.
/// </summary>
public class Win32PlatformOptions
{
/// <summary>
/// Deferred renderer would be used when set to true. Immediate renderer when set to false. The default value is true.
/// </summary>
/// <remarks>
/// Avalonia has two rendering modes: Immediate and Deferred rendering.
/// Immediate re-renders the whole scene when some element is changed on the scene. Deferred re-renders only changed elements.
/// </remarks>
public bool UseDeferredRendering { get; set; } = true;
/// <summary>
/// Enables ANGLE for Windows. For every Windows version that is above Windows 7, the default is true otherwise it's false.
/// </summary>
/// <remarks>
/// GPU rendering will not be enabled if this is set to false.
/// </remarks>
public bool? AllowEglInitialization { get; set; }
/// <summary>
/// Enables multitouch support. The default value is true.
/// </summary>
/// <remarks>
/// Multitouch allows a surface (a touchpad or touchscreen) to recognize the presence of more than one point of contact with the surface at the same time.
/// </remarks>
public bool? EnableMultitouch { get; set; } = true;
/// <summary>
/// Embeds popups to the window when set to true. The default value is false.
/// </summary>
public bool OverlayPopups { get; set; }
/// <summary>
/// Avalonia would try to use native Widows OpenGL when set to true. The default value is false.
/// </summary>
public bool UseWgl { get; set; }
public IList<GlVersion> WglProfiles { get; set; } = new List<GlVersion>
{
new GlVersion(GlProfileType.OpenGL, 4, 0),
new GlVersion(GlProfileType.OpenGL, 3, 2),
};
/// <summary>
/// Render Avalonia to a Texture inside the Windows.UI.Composition tree.
/// </summary>
/// <remarks>
/// Supported on Windows 10 build 16299 and above. Ignored on other versions.
/// This is recommended if you need to use AcrylicBlur or acrylic in your applications.
/// </remarks>
public bool UseWindowsUIComposition { get; set; } = true;
}
}
namespace Avalonia.Win32
{
public class Win32Platform : IPlatformThreadingInterface, IPlatformSettings, IWindowingPlatform, IPlatformIconLoader, IPlatformLifetimeEventsImpl
{
private static readonly Win32Platform s_instance = new Win32Platform();
private static Thread _uiThread;
private UnmanagedMethods.WndProc _wndProcDelegate;
private IntPtr _hwnd;
private readonly List<Delegate> _delegates = new List<Delegate>();
public Win32Platform()
{
SetDpiAwareness();
CreateMessageWindow();
}
/// <summary>
/// Gets the actual WindowsVersion. Same as the info returned from RtlGetVersion.
/// </summary>
public static Version WindowsVersion { get; } = RtlGetVersion();
public static bool UseDeferredRendering => Options.UseDeferredRendering;
internal static bool UseOverlayPopups => Options.OverlayPopups;
public static Win32PlatformOptions Options { get; private set; }
public Size DoubleClickSize => new Size(
UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CXDOUBLECLK),
UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CYDOUBLECLK));
public TimeSpan DoubleClickTime => TimeSpan.FromMilliseconds(UnmanagedMethods.GetDoubleClickTime());
public static void Initialize()
{
Initialize(new Win32PlatformOptions());
}
public static void Initialize(Win32PlatformOptions options)
{
Options = options;
AvaloniaLocator.CurrentMutable
.Bind<IClipboard>().ToSingleton<ClipboardImpl>()
.Bind<ICursorFactory>().ToConstant(CursorFactory.Instance)
.Bind<IKeyboardDevice>().ToConstant(WindowsKeyboardDevice.Instance)
.Bind<IPlatformSettings>().ToConstant(s_instance)
.Bind<IPlatformThreadingInterface>().ToConstant(s_instance)
.Bind<IRenderLoop>().ToConstant(new RenderLoop())
.Bind<IRenderTimer>().ToConstant(new DefaultRenderTimer(60))
.Bind<ISystemDialogImpl>().ToSingleton<SystemDialogImpl>()
.Bind<IWindowingPlatform>().ToConstant(s_instance)
.Bind<PlatformHotkeyConfiguration>().ToConstant(new PlatformHotkeyConfiguration(KeyModifiers.Control)
{
OpenContextMenu =
{
// Add Shift+F10
new KeyGesture(Key.F10, KeyModifiers.Shift)
}
})
.Bind<IPlatformIconLoader>().ToConstant(s_instance)
.Bind<NonPumpingLockHelper.IHelperImpl>().ToConstant(new NonPumpingSyncContext.HelperImpl())
.Bind<IMountedVolumeInfoProvider>().ToConstant(new WindowsMountedVolumeInfoProvider())
.Bind<IPlatformLifetimeEventsImpl>().ToConstant(s_instance);
Win32GlManager.Initialize();
_uiThread = Thread.CurrentThread;
if (OleContext.Current != null)
AvaloniaLocator.CurrentMutable.Bind<IPlatformDragSource>().ToSingleton<DragSource>();
}
public bool HasMessages()
{
UnmanagedMethods.MSG msg;
return UnmanagedMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
}
public void ProcessMessage()
{
if (UnmanagedMethods.GetMessage(out var msg, IntPtr.Zero, 0, 0) > -1)
{
UnmanagedMethods.TranslateMessage(ref msg);
UnmanagedMethods.DispatchMessage(ref msg);
}
else
{
Logging.Logger.TryGet(Logging.LogEventLevel.Error, Logging.LogArea.Win32Platform)
?.Log(this, "Unmanaged error in {0}. Error Code: {1}", nameof(ProcessMessage), Marshal.GetLastWin32Error());
}
}
public void RunLoop(CancellationToken cancellationToken)
{
var result = 0;
while (!cancellationToken.IsCancellationRequested
&& (result = UnmanagedMethods.GetMessage(out var msg, IntPtr.Zero, 0, 0)) > 0)
{
UnmanagedMethods.TranslateMessage(ref msg);
UnmanagedMethods.DispatchMessage(ref msg);
}
if (result < 0)
{
Logging.Logger.TryGet(Logging.LogEventLevel.Error, Logging.LogArea.Win32Platform)
?.Log(this, "Unmanaged error in {0}. Error Code: {1}", nameof(RunLoop), Marshal.GetLastWin32Error());
}
}
public IDisposable StartTimer(DispatcherPriority priority, TimeSpan interval, Action callback)
{
UnmanagedMethods.TimerProc timerDelegate =
(hWnd, uMsg, nIDEvent, dwTime) => callback();
IntPtr handle = UnmanagedMethods.SetTimer(
IntPtr.Zero,
IntPtr.Zero,
(uint)interval.TotalMilliseconds,
timerDelegate);
// Prevent timerDelegate being garbage collected.
_delegates.Add(timerDelegate);
return Disposable.Create(() =>
{
_delegates.Remove(timerDelegate);
UnmanagedMethods.KillTimer(IntPtr.Zero, handle);
});
}
private static readonly int SignalW = unchecked((int) 0xdeadbeaf);
private static readonly int SignalL = unchecked((int)0x12345678);
public void Signal(DispatcherPriority prio)
{
UnmanagedMethods.PostMessage(
_hwnd,
(int) UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM,
new IntPtr(SignalW),
new IntPtr(SignalL));
}
public bool CurrentThreadIsLoopThread => _uiThread == Thread.CurrentThread;
public event Action<DispatcherPriority?> Signaled;
public event EventHandler<ShutdownRequestedEventArgs> ShutdownRequested;
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")]
private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
if (msg == (int) UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM && wParam.ToInt64() == SignalW && lParam.ToInt64() == SignalL)
{
Signaled?.Invoke(null);
}
if(msg == (uint)WindowsMessage.WM_QUERYENDSESSION)
{
if (ShutdownRequested != null)
{
var e = new ShutdownRequestedEventArgs();
ShutdownRequested(this, e);
if(e.Cancel)
{
return IntPtr.Zero;
}
}
}
return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam);
}
private void CreateMessageWindow()
{
// Ensure that the delegate doesn't get garbage collected by storing it as a field.
_wndProcDelegate = new UnmanagedMethods.WndProc(WndProc);
UnmanagedMethods.WNDCLASSEX wndClassEx = new UnmanagedMethods.WNDCLASSEX
{
cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(),
lpfnWndProc = _wndProcDelegate,
hInstance = UnmanagedMethods.GetModuleHandle(null),
lpszClassName = "AvaloniaMessageWindow " + Guid.NewGuid(),
};
ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx);
if (atom == 0)
{
throw new Win32Exception();
}
_hwnd = UnmanagedMethods.CreateWindowEx(0, atom, null, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (_hwnd == IntPtr.Zero)
{
throw new Win32Exception();
}
}
public IWindowImpl CreateWindow()
{
return new WindowImpl();
}
public IWindowImpl CreateEmbeddableWindow()
{
var embedded = new EmbeddedWindowImpl();
embedded.Show(true, false);
return embedded;
}
public IWindowIconImpl LoadIcon(string fileName)
{
using (var stream = File.OpenRead(fileName))
{
return CreateIconImpl(stream);
}
}
public IWindowIconImpl LoadIcon(Stream stream)
{
return CreateIconImpl(stream);
}
public IWindowIconImpl LoadIcon(IBitmapImpl bitmap)
{
using (var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream);
return new IconImpl(new System.Drawing.Bitmap(memoryStream));
}
}
private static IconImpl CreateIconImpl(Stream stream)
{
try
{
return new IconImpl(new System.Drawing.Icon(stream));
}
catch (ArgumentException)
{
return new IconImpl(new System.Drawing.Bitmap(stream));
}
}
private static void SetDpiAwareness()
{
// Ideally we'd set DPI awareness in the manifest but this doesn't work for netcoreapp2.0
// apps as they are actually dlls run by a console loader. Instead we have to do it in code,
// but there are various ways to do this depending on the OS version.
var user32 = LoadLibrary("user32.dll");
var method = GetProcAddress(user32, nameof(SetProcessDpiAwarenessContext));
if (method != IntPtr.Zero)
{
if (SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) ||
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE))
{
return;
}
}
var shcore = LoadLibrary("shcore.dll");
method = GetProcAddress(shcore, nameof(SetProcessDpiAwareness));
if (method != IntPtr.Zero)
{
SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE);
return;
}
SetProcessDPIAware();
}
}
}
| |
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Using Directives
using System;
using System.Reflection;
using Ninject.Core.Binding;
using Ninject.Core.Infrastructure;
using Ninject.Core.Parameters;
using Ninject.Core.Planning;
using Ninject.Core.Planning.Targets;
using Ninject.Core.Tracking;
#endregion
namespace Ninject.Core.Activation
{
/// <summary>
/// The baseline definition of a context. To create a custom context, extend this type.
/// </summary>
public class StandardContext : DebugInfoProvider, IContext
{
/*----------------------------------------------------------------------------------------*/
#region Properties
/// <summary>
/// Gets or sets the kernel that is processing the activation request.
/// </summary>
public IKernel Kernel { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the scope in which the activation is occurring.
/// </summary>
/// <value></value>
public IScope Scope { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the parent context of this context. If this is a root context, this value
/// is <see langword="null"/>.
/// </summary>
public IContext ParentContext { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the numeric nesting level for the context.
/// </summary>
public int Level { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the type of service that is being activated.
/// </summary>
public Type Service { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the implementation type that will be returned.
/// </summary>
public Type Implementation { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the binding being used to activate items within the context.
/// </summary>
public IBinding Binding { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the plan.
/// </summary>
public IActivationPlan Plan { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the instance that is being activated.
/// </summary>
public object Instance { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the generic type arguments associated with the service, if applicable.
/// </summary>
public Type[] GenericArguments { get; protected set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the transient parameters for the context, if any are defined.
/// </summary>
public IParameterCollection Parameters { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the member that is being injected.
/// </summary>
public MemberInfo Member { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets the target that is being injected.
/// </summary>
/// <remarks>
/// In the case of method and constructor injection, this will represent the current
/// parameter that is being resolved. In the case of field and property injection, it will
/// be the member.
/// </remarks>
public ITarget Target { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets a value indicating whether the dependency resolution occuring in this
/// context is optional.
/// </summary>
/// <remarks>
/// If an optional request is made for a service, and an automatic binding cannot be
/// created (if the requested service is not self-bindable, or automatic bindings are disabled),
/// the kernel will simply inject a <see langword="null"/> value rather than throwing an
/// <see cref="ActivationException"/>.
/// </remarks>
public bool IsOptional { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets a value indicating whether the dependency resolution occurring in this context
/// is an eager activation, which occurs when the kernel is first initialized.
/// </summary>
public bool IsEagerActivation { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets or sets a value indicating whether the instance activated in this context should
/// be tracked by the kernel.
/// </summary>
public bool ShouldTrackInstance { get; set; }
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether this is a root context (that is, it originated from an
/// active request from client code and not passively via dependency resolution).
/// </summary>
public bool IsRoot
{
get { return (ParentContext == null); }
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Disposal
/// <summary>
/// Releases all resources held by the object.
/// </summary>
/// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
protected override void Dispose(bool disposing)
{
if (disposing && !IsDisposed)
{
Kernel = null;
ParentContext = null;
Service = null;
GenericArguments = null;
Binding = null;
Plan = null;
Instance = null;
Member = null;
Target = null;
}
base.Dispose(disposing);
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Constructors
/// <summary>
/// Creates a new root context.
/// </summary>
/// <param name="kernel">The kernel that is processing the activation request.</param>
/// <param name="service">The service being activated.</param>
/// <param name="scope">The scope the activation is occuring in.</param>
public StandardContext(IKernel kernel, Type service, IScope scope)
{
Ensure.ArgumentNotNull(kernel, "kernel");
Ensure.ArgumentNotNull(service, "service");
Ensure.ArgumentNotNull(scope, "scope");
Kernel = kernel;
Level = 0;
Service = service;
Scope = scope;
Initialize();
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Creates a new child context.
/// </summary>
/// <param name="kernel">The kernel that is processing the activation request.</param>
/// <param name="service">The service that will be activated in the new child context.</param>
/// <param name="parent">The parent context containing the new context.</param>
public StandardContext(IKernel kernel, Type service, IContext parent)
{
Ensure.ArgumentNotNull(parent, "parent");
Ensure.ArgumentNotNull(service, "service");
ParentContext = parent;
Kernel = kernel;
Level = parent.Level + 1;
Service = service;
Scope = parent.Scope;
Initialize();
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Public Methods
/// <summary>
/// Prepares the context to activate an instance for the specified binding.
/// </summary>
/// <param name="binding">The binding that will be used during activation.</param>
public void PrepareForActivation(IBinding binding)
{
Ensure.ArgumentNotNull(binding, "binding");
Binding = binding;
if (!Kernel.Options.IgnoreProviderCompatibility && !binding.Provider.IsCompatibleWith(this))
throw new ActivationException(ExceptionFormatter.ProviderIncompatibleWithService(this));
Implementation = binding.Provider.GetImplementationType(this);
Plan = binding.Components.Planner.GetPlan(binding, Implementation);
ShouldTrackInstance = Plan.Behavior.ShouldTrackInstances;
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Private Methods
private void Initialize()
{
if (Service.IsGenericType)
GenericArguments = Service.GetGenericArguments();
#if !NO_STACKTRACE
if (Kernel.Options.GenerateDebugInfo)
DebugInfo = DebugInfo.FromStackTrace();
#endif
Parameters = new ParameterCollection();
if(ParentContext != null)
Parameters.InheritFrom(ParentContext.Parameters);
}
#endregion
/*----------------------------------------------------------------------------------------*/
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="TimeSuggestion.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the TimeSuggestion class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
/// <summary>
/// Represents an availability time suggestion.
/// </summary>
public sealed class TimeSuggestion : ComplexProperty
{
private DateTime meetingTime;
private bool isWorkTime;
private SuggestionQuality quality;
private Collection<Conflict> conflicts = new Collection<Conflict>();
/// <summary>
/// Initializes a new instance of the <see cref="TimeSuggestion"/> class.
/// </summary>
internal TimeSuggestion()
: base()
{
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if appropriate element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.MeetingTime:
this.meetingTime = reader.ReadElementValueAsUnbiasedDateTimeScopedToServiceTimeZone();
return true;
case XmlElementNames.IsWorkTime:
this.isWorkTime = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.SuggestionQuality:
this.quality = reader.ReadElementValue<SuggestionQuality>();
return true;
case XmlElementNames.AttendeeConflictDataArray:
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if (reader.IsStartElement())
{
Conflict conflict = null;
switch (reader.LocalName)
{
case XmlElementNames.UnknownAttendeeConflictData:
conflict = new Conflict(ConflictType.UnknownAttendeeConflict);
break;
case XmlElementNames.TooBigGroupAttendeeConflictData:
conflict = new Conflict(ConflictType.GroupTooBigConflict);
break;
case XmlElementNames.IndividualAttendeeConflictData:
conflict = new Conflict(ConflictType.IndividualAttendeeConflict);
break;
case XmlElementNames.GroupAttendeeConflictData:
conflict = new Conflict(ConflictType.GroupConflict);
break;
default:
EwsUtilities.Assert(
false,
"TimeSuggestion.TryReadElementFromXml",
string.Format("The {0} element name does not map to any AttendeeConflict descendant.", reader.LocalName));
// The following line to please the compiler
break;
}
conflict.LoadFromXml(reader, reader.LocalName);
this.conflicts.Add(conflict);
}
}
while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.AttendeeConflictDataArray));
}
return true;
default:
return false;
}
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service">The service.</param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.MeetingTime:
this.meetingTime = EwsUtilities.ParseAsUnbiasedDatetimescopedToServicetimeZone(jsonProperty.ReadAsString(key), service);
break;
case XmlElementNames.IsWorkTime:
this.isWorkTime = jsonProperty.ReadAsBool(key);
break;
case XmlElementNames.SuggestionQuality:
this.quality = jsonProperty.ReadEnumValue<SuggestionQuality>(key);
break;
case XmlElementNames.AttendeeConflictDataArray:
object[] jsonConflictArray = jsonProperty.ReadAsArray(key);
foreach (object conflictObject in jsonConflictArray)
{
JsonObject jsonConflict = conflictObject as JsonObject;
if (jsonConflict != null)
{
Conflict conflict = null;
switch (jsonConflict.ReadTypeString())
{
case XmlElementNames.UnknownAttendeeConflictData:
conflict = new Conflict(ConflictType.UnknownAttendeeConflict);
break;
case XmlElementNames.TooBigGroupAttendeeConflictData:
conflict = new Conflict(ConflictType.GroupTooBigConflict);
break;
case XmlElementNames.IndividualAttendeeConflictData:
conflict = new Conflict(ConflictType.IndividualAttendeeConflict);
break;
case XmlElementNames.GroupAttendeeConflictData:
conflict = new Conflict(ConflictType.GroupConflict);
break;
default:
EwsUtilities.Assert(
false,
"TimeSuggestion.TryReadElementFromJson",
string.Format("The {0} element name does not map to any AttendeeConflict descendant.", jsonConflict.ReadTypeString()));
// The following line to please the compiler
break;
}
conflict.LoadFromJson(jsonConflict, service);
this.conflicts.Add(conflict);
}
}
break;
default:
break;
}
}
}
/// <summary>
/// Gets the suggested time.
/// </summary>
public DateTime MeetingTime
{
get { return this.meetingTime; }
}
/// <summary>
/// Gets a value indicating whether the suggested time is within working hours.
/// </summary>
public bool IsWorkTime
{
get { return this.isWorkTime; }
}
/// <summary>
/// Gets the quality of the suggestion.
/// </summary>
public SuggestionQuality Quality
{
get { return this.quality; }
}
/// <summary>
/// Gets a collection of conflicts at the suggested time.
/// </summary>
public Collection<Conflict> Conflicts
{
get { return this.conflicts; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Travelopedia_API.Areas.HelpPage.ModelDescriptions;
using Travelopedia_API.Areas.HelpPage.Models;
namespace Travelopedia_API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.AutoML.V1.Snippets
{
using Google.LongRunning;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedPredictionServiceClientSnippets
{
/// <summary>Snippet for Predict</summary>
public void PredictRequestObject()
{
// Snippet: Predict(PredictRequest, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params = { { "", "" }, },
};
// Make the request
PredictResponse response = predictionServiceClient.Predict(request);
// End snippet
}
/// <summary>Snippet for PredictAsync</summary>
public async Task PredictRequestObjectAsync()
{
// Snippet: PredictAsync(PredictRequest, CallSettings)
// Additional: PredictAsync(PredictRequest, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
PredictRequest request = new PredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
Payload = new ExamplePayload(),
Params = { { "", "" }, },
};
// Make the request
PredictResponse response = await predictionServiceClient.PredictAsync(request);
// End snippet
}
/// <summary>Snippet for Predict</summary>
public void Predict()
{
// Snippet: Predict(string, ExamplePayload, IDictionary<string,string>, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
ExamplePayload payload = new ExamplePayload();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
PredictResponse response = predictionServiceClient.Predict(name, payload, @params);
// End snippet
}
/// <summary>Snippet for PredictAsync</summary>
public async Task PredictAsync()
{
// Snippet: PredictAsync(string, ExamplePayload, IDictionary<string,string>, CallSettings)
// Additional: PredictAsync(string, ExamplePayload, IDictionary<string,string>, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
ExamplePayload payload = new ExamplePayload();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
PredictResponse response = await predictionServiceClient.PredictAsync(name, payload, @params);
// End snippet
}
/// <summary>Snippet for Predict</summary>
public void PredictResourceNames()
{
// Snippet: Predict(ModelName, ExamplePayload, IDictionary<string,string>, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]");
ExamplePayload payload = new ExamplePayload();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
PredictResponse response = predictionServiceClient.Predict(name, payload, @params);
// End snippet
}
/// <summary>Snippet for PredictAsync</summary>
public async Task PredictResourceNamesAsync()
{
// Snippet: PredictAsync(ModelName, ExamplePayload, IDictionary<string,string>, CallSettings)
// Additional: PredictAsync(ModelName, ExamplePayload, IDictionary<string,string>, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]");
ExamplePayload payload = new ExamplePayload();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
PredictResponse response = await predictionServiceClient.PredictAsync(name, payload, @params);
// End snippet
}
/// <summary>Snippet for BatchPredict</summary>
public void BatchPredictRequestObject()
{
// Snippet: BatchPredict(BatchPredictRequest, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
BatchPredictRequest request = new BatchPredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
InputConfig = new BatchPredictInputConfig(),
OutputConfig = new BatchPredictOutputConfig(),
Params = { { "", "" }, },
};
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(request);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchPredictAsync</summary>
public async Task BatchPredictRequestObjectAsync()
{
// Snippet: BatchPredictAsync(BatchPredictRequest, CallSettings)
// Additional: BatchPredictAsync(BatchPredictRequest, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
BatchPredictRequest request = new BatchPredictRequest
{
ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
InputConfig = new BatchPredictInputConfig(),
OutputConfig = new BatchPredictOutputConfig(),
Params = { { "", "" }, },
};
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(request);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchPredict</summary>
public void BatchPredict()
{
// Snippet: BatchPredict(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
BatchPredictInputConfig inputConfig = new BatchPredictInputConfig();
BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchPredictAsync</summary>
public async Task BatchPredictAsync()
{
// Snippet: BatchPredictAsync(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings)
// Additional: BatchPredictAsync(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
BatchPredictInputConfig inputConfig = new BatchPredictInputConfig();
BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(name, inputConfig, outputConfig, @params);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchPredict</summary>
public void BatchPredictResourceNames()
{
// Snippet: BatchPredict(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings)
// Create client
PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
// Initialize request argument(s)
ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]");
BatchPredictInputConfig inputConfig = new BatchPredictInputConfig();
BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchPredictAsync</summary>
public async Task BatchPredictResourceNamesAsync()
{
// Snippet: BatchPredictAsync(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings)
// Additional: BatchPredictAsync(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CancellationToken)
// Create client
PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();
// Initialize request argument(s)
ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]");
BatchPredictInputConfig inputConfig = new BatchPredictInputConfig();
BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig();
IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, };
// Make the request
Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(name, inputConfig, outputConfig, @params);
// Poll until the returned long-running operation is complete
Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchPredictResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchPredictResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EntityFramework.Reflection;
namespace EntityFramework.Future
{
/// <summary>
/// Base class for future queries.
/// </summary>
/// <typeparam name="T">The type for the future query.</typeparam>
[DebuggerDisplay("IsLoaded={IsLoaded}")]
public abstract class FutureQueryBase<T> : IFutureQuery
{
private readonly IQueryable<T> _query;
private readonly IFutureContext _futureContext;
private IList<T> _result;
private bool _isLoaded;
/// <summary>
/// Initializes a new instance of the <see cref="FutureQuery<T>" /> class.
/// </summary>
/// <param name="query">The query source to use when materializing.</param>
/// <param name="futureContext">The future context.</param>
protected FutureQueryBase(IQueryable<T> query, IFutureContext futureContext)
{
_query = query;
_futureContext = futureContext;
//_result = null;
}
/// <summary>
/// Gets the action to execute when the query is accessed.
/// </summary>
/// <value>The load action.</value>
//protected Action LoadAction
//{
// get { return _loadAction; }
//}
/// <summary>
/// Gets a value indicating whether this instance is loaded.
/// </summary>
/// <value><c>true</c> if this instance is loaded; otherwise, <c>false</c>.</value>
public bool IsLoaded
{
get { return _isLoaded; }
}
/// <summary>
/// Gets or sets the query execute exception.
/// </summary>
/// <value>The query execute exception.</value>
public Exception Exception { get; set; }
/// <summary>
/// Gets the query source to use when materializing.
/// </summary>
/// <value>The query source to use when materializing.</value>
IQueryable IFutureQuery.Query
{
get { return _query; }
}
/// <summary>
/// Gets the result.
/// </summary>
/// <returns></returns>
protected virtual IList<T> GetResult()
{
if (IsLoaded)
return _result;
// no load action, run query directly
if (_futureContext == null)
{
_isLoaded = true;
var enumerable = _query as IEnumerable<T>;
_result = enumerable == null ? null : enumerable.ToList();
return _result;
}
// invoke the load action on the datacontext
// result will be set with a callback to SetResult
_futureContext.ExecuteFutureQueries();
return _result ?? new List<T>();
}
#if NET45
/// <summary>
/// Gets the result asynchronous.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns></returns>
protected virtual async Task<IList<T>> GetResultAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (IsLoaded)
return _result;
// no load action, run query directly
if (_futureContext == null)
{
_isLoaded = true;
_result = await (_query as IQueryable<T>).ToListAsync(cancellationToken).ConfigureAwait(false);
return _result;
}
// invoke the load action on the datacontext
// result will be set with a callback to SetResult
await _futureContext.ExecuteFutureQueriesAsync(cancellationToken).ConfigureAwait(false);
return _result ?? new List<T>();
}
#endif
/// <summary>
/// Gets the data command for this query.
/// </summary>
/// <param name="dataContext">The data context to get the command from.</param>
/// <returns>The requested command object.</returns>
FuturePlan IFutureQuery.GetPlan(ObjectContext dataContext)
{
return GetPlan(dataContext);
}
/// <summary>
/// Gets the data command for this query.
/// </summary>
/// <param name="dataContext">The data context to get the command from.</param>
/// <returns>The requested command object.</returns>
protected virtual FuturePlan GetPlan(ObjectContext dataContext)
{
IFutureQuery futureQuery = this;
var source = futureQuery.Query;
var q = source as ObjectQuery;
if (q == null)
throw new InvalidOperationException("The future query is not of type ObjectQuery.");
var plan = new FuturePlan
{
CommandText = q.ToTraceString(),
Parameters = q.Parameters
};
return plan;
}
/// <summary>
/// Sets the underling value after the query has been executed.
/// </summary>
/// <param name="dataContext">The data context to translate the results with.</param>
/// <param name="reader">The <see cref="DbDataReader"/> to get the result from.</param>
void IFutureQuery.SetResult(ObjectContext dataContext, DbDataReader reader)
{
SetResult(dataContext, reader);
}
/// <summary>
/// Sets the underling value after the query has been executed.
/// </summary>
/// <param name="dataContext">The data context to translate the results with.</param>
/// <param name="reader">The <see cref="DbDataReader"/> to get the result from.</param>
protected virtual void SetResult(ObjectContext dataContext, DbDataReader reader)
{
_isLoaded = true;
try
{
IFutureQuery futureQuery = this;
var source = futureQuery.Query;
var q = source as ObjectQuery;
if (q == null)
throw new InvalidOperationException("The future query is not of type ObjectQuery.");
// create execution plan
dynamic queryProxy = new DynamicProxy(q);
// ObjectQueryState
dynamic queryState = queryProxy.QueryState;
// ObjectQueryExecutionPlan
dynamic executionPlan = queryState.GetExecutionPlan(null);
// ShaperFactory
dynamic shaperFactory = executionPlan.ResultShaperFactory;
// Shaper<T>
dynamic shaper = shaperFactory.Create(reader, dataContext, dataContext.MetadataWorkspace,
MergeOption.AppendOnly, false, true, false);
var list = new List<T>();
IEnumerator<T> enumerator = shaper.GetEnumerator();
while (enumerator.MoveNext())
list.Add(enumerator.Current);
_result = list;
// translate has issue with column names not matching
//var resultSet = dataContext.Translate<T>(reader);
//_result = resultSet.ToList();
}
catch (Exception ex)
{
Exception = ex;
}
}
#if NET45
/// <summary>
/// Sets the underling value after the query has been executed.
/// </summary>
/// <param name="dataContext">The data context to translate the results with.</param>
/// <param name="reader">The <see cref="DbDataReader" /> to get the result from.</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task IFutureQuery.SetResultAsync(ObjectContext dataContext, DbDataReader reader, CancellationToken cancellationToken = default(CancellationToken))
{
return SetResultAsync(dataContext, reader, cancellationToken);
}
/// <summary>
/// Sets the underling value after the query has been executed.
/// </summary>
/// <param name="dataContext">The data context to translate the results with.</param>
/// <param name="reader">The <see cref="DbDataReader" /> to get the result from.</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">The future query is not of type ObjectQuery.</exception>
protected virtual async Task SetResultAsync(ObjectContext dataContext, DbDataReader reader, CancellationToken cancellationToken = default(CancellationToken))
{
_isLoaded = true;
try
{
IFutureQuery futureQuery = this;
var source = futureQuery.Query;
var q = source as ObjectQuery;
if (q == null)
throw new InvalidOperationException("The future query is not of type ObjectQuery.");
// create execution plan
dynamic queryProxy = new DynamicProxy(q);
// ObjectQueryState
dynamic queryState = queryProxy.QueryState;
// ObjectQueryExecutionPlan
dynamic executionPlan = queryState.GetExecutionPlan(null);
// ShaperFactory
dynamic shaperFactory = executionPlan.ResultShaperFactory;
// Shaper<T>
dynamic shaper = shaperFactory.Create(reader, dataContext, dataContext.MetadataWorkspace,
MergeOption.AppendOnly, false, true, false);
var list = new List<T>();
// Shaper<T> GetEnumerator method return IDbEnumerator<T>, which implements publicly accessible IDbAsyncEnumerator<T>
IDbAsyncEnumerator<T> enumerator = shaper.GetEnumerator();
while (await enumerator.MoveNextAsync(cancellationToken).ConfigureAwait(false))
list.Add(enumerator.Current);
_result = list;
// translate has issue with column names not matching
//var resultSet = dataContext.Translate<T>(reader);
//_result = resultSet.ToList();
}
catch (Exception ex)
{
Exception = ex;
}
}
#endif
}
}
| |
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Runtime;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using DotVVM.Framework.Compilation.Javascript;
using System.Runtime.CompilerServices;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Controls
{
[Flags]
public enum ControlLifecycleRequirements : short
{
None = 0,
RealtimePreInit = 1 << 0,
RealtimeInit = 1 << 1,
RealtimeLoad = 1 << 2,
RealtimePreRender = 1 << 3,
RealtimePreRenderComplete = 1 << 4,
InvokeMissingPreInit = 1 << 5,
InvokeMissingInit = 1 << 6,
InvokeMissingLoad = 1 << 7,
InvokeMissingPreRender = 1 << 8,
InvokeMissingPreRenderComplete = 1 << 9,
OnlyRealtime = RealtimePreInit | RealtimeInit | RealtimeLoad | RealtimePreRender | RealtimePreRenderComplete,
OnlyMissing = InvokeMissingPreInit | InvokeMissingInit | InvokeMissingLoad | InvokeMissingPreRender | InvokeMissingPreRenderComplete,
All = OnlyRealtime | OnlyMissing,
PreInit = RealtimePreInit | InvokeMissingPreInit,
Init = RealtimeInit | InvokeMissingInit,
Load = RealtimeLoad | InvokeMissingLoad,
PreRender = RealtimePreRender | InvokeMissingPreRender,
PreRenderComplete = RealtimePreRenderComplete | InvokeMissingPreRenderComplete,
}
/// <summary>
/// Represents a base class for all DotVVM controls.
/// </summary>
public abstract class DotvvmControl : DotvvmBindableObject, IDotvvmControl
{
/// <summary>
/// Gets the child controls.
/// </summary>
[MarkupOptions(MappingMode = MappingMode.Exclude)]
public DotvvmControlCollection Children { get; private set; }
// automatically assign requirements
public ControlLifecycleRequirements LifecycleRequirements = ControlLifecycleRequirements.Init | ControlLifecycleRequirements.Load | ControlLifecycleRequirements.PreRender;
/// <summary>
/// Gets or sets the unique control ID.
/// </summary>
[MarkupOptions]
public string? ID
{
get { return (string?)GetValue(IDProperty); }
set { SetValue(IDProperty, value); }
}
public static readonly DotvvmProperty IDProperty =
DotvvmProperty.Register<string?, DotvvmControl>(c => c.ID, isValueInherited: false);
/// <summary>
/// Gets id of the control that will be written in 'id' attribute. Returns null if the IDProperty is not set.
/// </summary>
[MarkupOptions(MappingMode = MappingMode.Exclude)]
public string? ClientID => (string?)GetValue(ClientIDProperty) ?? CreateAndSaveClientId();
public static readonly DotvvmProperty ClientIDProperty
= DotvvmProperty.Register<string?, DotvvmControl>(c => c.ClientID, null);
string? CreateAndSaveClientId()
{
var id = CreateClientId();
if (id != null) SetValue(ClientIDProperty, id);
return (string?)id;
}
/// <summary>
/// Gets or sets the client ID generation algorithm.
/// </summary>
[MarkupOptions(AllowBinding = false)]
public ClientIDMode ClientIDMode
{
get { return (ClientIDMode)GetValue(ClientIDModeProperty)!; }
set { SetValue(ClientIDModeProperty, value); }
}
public static readonly DotvvmProperty ClientIDModeProperty =
DotvvmProperty.Register<ClientIDMode, DotvvmControl>(c => c.ClientIDMode, ClientIDMode.Static, isValueInherited: true);
/// <summary>
/// Gets or sets whether the control is included in the DOM of the page.
/// </summary>
/// <remarks>
/// Essentially wraps Knockout's 'if' binding.
/// </remarks>
[MarkupOptions(AllowHardCodedValue = false)]
public bool IncludeInPage
{
get { return (bool)GetValue(IncludeInPageProperty)!; }
set { SetValue(IncludeInPageProperty, value); }
}
DotvvmControlCollection IDotvvmControl.Children => throw new NotImplementedException();
ClientIDMode IDotvvmControl.ClientIDMode { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
string IDotvvmControl.ID { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
DotvvmBindableObject? IDotvvmControl.Parent { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public static readonly DotvvmProperty IncludeInPageProperty =
DotvvmProperty.Register<bool, DotvvmControl>(t => t.IncludeInPage, true);
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmControl"/> class.
/// </summary>
public DotvvmControl()
{
Children = new DotvvmControlCollection(this);
}
/// <summary>
/// Gets this control and all of its descendants.
/// </summary>
public IEnumerable<DotvvmControl> GetThisAndAllDescendants(Func<DotvvmControl, bool>? enumerateChildrenCondition = null)
{
// PERF: non-linear complexity
yield return this;
if (enumerateChildrenCondition == null || enumerateChildrenCondition(this))
{
foreach (var descendant in GetAllDescendants(enumerateChildrenCondition))
{
yield return descendant;
}
}
}
/// <summary>
/// Gets all descendant controls of this control.
/// </summary>
public IEnumerable<DotvvmControl> GetAllDescendants(Func<DotvvmControl, bool>? enumerateChildrenCondition = null)
{
// PERF: non-linear complexity
foreach (var child in Children)
{
yield return child;
if (enumerateChildrenCondition == null || enumerateChildrenCondition(child))
{
foreach (var grandChild in child.GetAllDescendants(enumerateChildrenCondition))
{
yield return grandChild;
}
}
}
}
/// <summary>
/// Determines whether the control has only white space content.
/// </summary>
public bool HasOnlyWhiteSpaceContent() =>
Children.HasOnlyWhiteSpaceContent();
/// <summary>
/// Renders the control into the specified writer.
/// </summary>
public virtual void Render(IHtmlWriter writer, IDotvvmRequestContext context)
{
this.Children.ValidateParentsLifecycleEvents(); // debug check
writer.SetErrorContext(this);
if (properties.Contains(PostBack.UpdateProperty))
{
AddDotvvmUniqueIdAttribute();
}
try
{
RenderControl(writer, context);
}
catch (Exception e)
{
if (e is IDotvvmException { RelatedControl: not null })
throw;
if (e is DotvvmExceptionBase dotvvmException)
{
dotvvmException.RelatedControl = this;
throw;
}
throw new DotvvmControlException(this, "Error occurred in Render method", e);
}
}
/// <summary>
/// Adds 'data-dotvvm-id' attribute with generated unique id to the control. You can find control by this id using FindControlByUniqueId method.
/// </summary>
protected void AddDotvvmUniqueIdAttribute()
{
var htmlAttributes = this as IControlWithHtmlAttributes;
if (htmlAttributes == null)
{
throw new DotvvmControlException(this, "Postback.Update cannot be set on property which don't render html attributes.");
}
htmlAttributes.Attributes.Set("data-dotvvm-id", GetDotvvmUniqueId());
}
protected struct RenderState
{
internal object? IncludeInPage;
internal IValueBinding? DataContext;
internal bool HasActives;
internal bool HasActiveGroups;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static bool TouchProperty(DotvvmProperty property, object? val, ref RenderState r)
{
if (property == DotvvmControl.IncludeInPageProperty)
r.IncludeInPage = val;
else if (property == DotvvmControl.DataContextProperty)
r.DataContext = val as IValueBinding;
else if (property is ActiveDotvvmProperty)
r.HasActives = true;
else if (property is GroupedDotvvmProperty groupedProperty && groupedProperty.PropertyGroup is ActiveDotvvmPropertyGroup)
r.HasActiveGroups = true;
else return false;
return true;
}
/// <returns>true means that rendering of the rest of this control should be skipped</returns>
protected bool RenderBeforeControl(in RenderState r, IHtmlWriter writer, IDotvvmRequestContext context)
{
if (r.IncludeInPage != null && !(r.IncludeInPage is IValueBinding) && !this.IncludeInPage)
return true;
if (r.DataContext != null)
{
var parent = Parent ?? throw new DotvvmControlException(this, "Cannot set DataContext binding on the root control");
writer.WriteKnockoutWithComment(r.DataContext.GetKnockoutBindingExpression(parent));
}
if (r.IncludeInPage != null && r.IncludeInPage is IValueBinding binding)
{
writer.WriteKnockoutDataBindComment("if", binding.GetKnockoutBindingExpression(this));
}
if (r.HasActives) foreach (var item in properties)
{
if (item.Key is ActiveDotvvmProperty activeProp)
{
activeProp.AddAttributesToRender(writer, context, this);
}
}
if (r.HasActiveGroups)
{
var groups = properties
.Where(p => p.Key is GroupedDotvvmProperty gp && gp.PropertyGroup is ActiveDotvvmPropertyGroup)
.GroupBy(p => ((GroupedDotvvmProperty)p.Key).PropertyGroup);
foreach (var item in groups)
{
((ActiveDotvvmPropertyGroup)item.Key).AddAttributesToRender(writer, context, this, item.Select(i => i.Key));
}
}
return false;
}
protected void RenderAfterControl(in RenderState r, IHtmlWriter writer)
{
if (r.DataContext != null)
{
writer.WriteKnockoutDataBindEndComment();
}
if (r.IncludeInPage != null && r.IncludeInPage is IValueBinding binding)
{
writer.WriteKnockoutDataBindEndComment();
}
}
/// <summary>
/// Renders the control into the specified writer.
/// </summary>
protected virtual void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context)
{
RenderState r = default;
foreach (var (prop, value) in properties)
TouchProperty(prop, value, ref r);
if (RenderBeforeControl(in r, writer, context))
return;
AddAttributesToRender(writer, context);
RenderBeginTag(writer, context);
RenderContents(writer, context);
RenderEndTag(writer, context);
RenderAfterControl(in r, writer);
}
/// <summary>
/// Adds all attributes that should be added to the control begin tag.
/// </summary>
protected virtual void AddAttributesToRender(IHtmlWriter writer, IDotvvmRequestContext context)
{
}
/// <summary>
/// Renders the control begin tag.
/// </summary>
protected virtual void RenderBeginTag(IHtmlWriter writer, IDotvvmRequestContext context)
{
}
/// <summary>
/// Renders the contents inside the control begin and end tags.
/// </summary>
protected virtual void RenderContents(IHtmlWriter writer, IDotvvmRequestContext context)
{
RenderChildren(writer, context);
}
/// <summary>
/// Renders the control end tag.
/// </summary>
protected virtual void RenderEndTag(IHtmlWriter writer, IDotvvmRequestContext context)
{
}
/// <summary>
/// Renders the children.
/// </summary>
protected void RenderChildren(IHtmlWriter writer, IDotvvmRequestContext context)
{
foreach (var child in Children)
{
child.Render(writer, context);
}
}
[Obsolete("Use FindControlInContainer instead. Or FindControlByClientId if you want to be limited only to this container.")]
public DotvvmControl? FindControl(string id, bool throwIfNotFound = false) => FindControlInContainer(id, throwIfNotFound);
[Obsolete("Use FindControlInContainer instead. Or FindControlByClientId if you want to be limited only to this container.")]
public T FindControl<T>(string id, bool throwIfNotFound = false) where T : DotvvmControl => FindControlInContainer<T>(id, throwIfNotFound);
/// <summary>
/// Finds a control by its ID coded in markup. Does not recurse into naming containers. Returns null if the <paramref name="throwIfNotFound" /> is false and the control is not found.
/// </summary>
public DotvvmControl? FindControlInContainer(string id, bool throwIfNotFound = false)
{
if (string.IsNullOrEmpty(id)) throw new ArgumentNullException(nameof(id));
var control = GetAllDescendants(c => !IsNamingContainer(c)).SingleOrDefault(c => c.ID == id);
if (control == null && throwIfNotFound)
{
throw new Exception(string.Format("The control with ID '{0}' was not found.", id));
}
return control;
}
/// <summary>
/// Finds a control by its ID coded in markup. Does not recurse into naming containers.
/// </summary>
public T FindControlInContainer<T>(string id, bool throwIfNotFound = false) where T : DotvvmControl
{
var control = FindControlInContainer(id, throwIfNotFound);
if (!(control is T)) // TODO: this does not work
{
throw new DotvvmControlException(this, $"The control with ID '{id}' was found, however it is not an instance of the desired type '{typeof(T)}'.");
}
return (T)control;
}
/// <summary>
/// Finds a control by its ClientId - the id rendered to output html.
/// </summary>
public DotvvmControl? FindControlByClientId(string id, bool throwIfNotFound = false)
{
if (string.IsNullOrEmpty(id)) throw new ArgumentNullException(nameof(id));
var control = GetAllDescendants().SingleOrDefault(c => c.ClientID == id);
if (control == null && throwIfNotFound)
{
throw new Exception(string.Format("The control with ID '{0}' was not found.", id));
}
return control;
}
/// <summary>
/// Finds a control by its ClientId - the id rendered to output html.
/// </summary>
public T FindControlByClientId<T>(string id, bool throwIfNotFound = false) where T : DotvvmControl
{
var control = FindControlByClientId(id, throwIfNotFound);
if (!(control is T))
{
throw new DotvvmControlException(this, $"The control with ID '{id}' was found, however it is not an instance of the desired type '{typeof(T)}'.");
}
return (T)control;
}
/// <summary>
/// Finds a control by its unique ID. Returns null if the control is not found.
/// </summary>
public DotvvmControl? FindControlByUniqueId(string controlUniqueId)
{
var parts = controlUniqueId.Split('_');
DotvvmControl? result = this;
for (var i = 0; i < parts.Length; i++)
{
result = result.GetAllDescendants(c => !IsNamingContainer(c))
.SingleOrDefault(c => c.GetValue(Internal.UniqueIDProperty) as string == parts[i]);
if (result == null)
{
return null;
}
}
return result;
}
/// <summary>
/// Gets the naming container of the current control.
/// </summary>
public DotvvmControl GetNamingContainer()
{
var control = this;
while (!IsNamingContainer(control) && control.Parent is DotvvmControl parent)
{
control = parent;
}
return control;
}
/// <summary>
/// Determines whether the specified control is a naming container.
/// </summary>
public static bool IsNamingContainer(DotvvmBindableObject control)
{
return (bool)control.GetValue(Internal.IsNamingContainerProperty)!;
}
/// <summary>
/// Occurs after the viewmodel tree is complete.
/// </summary>
internal virtual void OnPreInit(IDotvvmRequestContext context)
{
}
/// <summary>
/// Called right before the rendering shall occur.
/// </summary>
internal virtual void OnPreRenderComplete(IDotvvmRequestContext context)
{
}
/// <summary>
/// Occurs before the viewmodel is applied to the page.
/// </summary>
protected internal virtual void OnInit(IDotvvmRequestContext context)
{
}
/// <summary>
/// Occurs after the viewmodel is applied to the page IHtmlWriter writer and before the commands are executed.
/// </summary>
protected internal virtual void OnLoad(IDotvvmRequestContext context)
{
}
/// <summary>
/// Occurs after the page commands are executed.
/// </summary>
protected internal virtual void OnPreRender(IDotvvmRequestContext context)
{
}
/// <summary>
/// Gets the internal unique ID of the control. Returns either string or IValueBinding.
/// </summary>
public object GetDotvvmUniqueId() =>
// build the client ID
JoinValuesOrBindings(GetUniqueIdFragments());
private object JoinValuesOrBindings(IList<object?> fragments)
{
if (fragments.All(f => f is string))
{
return string.Join("_", fragments);
}
else
{
BindingCompilationService? service = null;
var result = new ParametrizedCode.Builder();
var first = true;
foreach (var f in fragments)
{
if (!first | (first = false))
result.Add("+'_'+");
if (f is IValueBinding binding)
{
service = service ?? binding.GetProperty<BindingCompilationService>(ErrorHandlingMode.ReturnNull);
result.Add(binding.GetParametrizedKnockoutExpression(this, unwrapped: true), 14);
}
else result.Add(JavascriptCompilationHelper.CompileConstant(f));
}
if (service == null) throw new NotSupportedException();
return ValueBindingExpression.CreateBinding<string?>(service.WithoutInitialization(), h => null, result.Build(new OperatorPrecedence()), this.GetDataContextType());
}
}
/// <summary>
/// Adds the corresponding attribute for the Id property.
/// </summary>
protected virtual object? CreateClientId() =>
!this.IsPropertySet(IDProperty) ? null :
// build the client ID
GetClientIdFragments()?.Apply(JoinValuesOrBindings);
private IList<object?> GetUniqueIdFragments()
{
var fragments = new List<object?> { GetValue(Internal.UniqueIDProperty) };
foreach (var ancestor in GetAllAncestors())
{
if (IsNamingContainer(ancestor))
{
fragments.Add(ancestor.GetValueRaw(Internal.ClientIDFragmentProperty) ?? ancestor.GetValueRaw(Internal.UniqueIDProperty));
}
}
fragments.Reverse();
return fragments;
}
private IList<object?>? GetClientIdFragments()
{
var rawId = GetValue(IDProperty);
// can't generate ID from nothing
if (rawId == null) return null;
if (ClientIDMode == ClientIDMode.Static)
{
// just rewrite Static mode ID
return new[] { GetValueRaw(IDProperty) };
}
var fragments = new List<object?> { rawId };
DotvvmControl? childContainer = null;
bool searchingForIdElement = false;
foreach (DotvvmControl ancestor in GetAllAncestors())
{
if (IsNamingContainer(ancestor))
{
if (searchingForIdElement)
{
fragments.Add(childContainer!.GetDotvvmUniqueId());
}
searchingForIdElement = false;
var clientIdExpression = ancestor.GetValueRaw(Internal.ClientIDFragmentProperty);
if (clientIdExpression is IValueBinding)
{
fragments.Add(clientIdExpression);
}
else if (ancestor.GetValueRaw(IDProperty) is object ancestorId && "" != ancestorId as string)
{
// add the ID fragment
fragments.Add(ancestorId);
}
else
{
searchingForIdElement = true;
childContainer = ancestor;
}
}
if (searchingForIdElement && ancestor.IsPropertySet(ClientIDProperty))
{
fragments.Add(ancestor.GetValueRaw(ClientIDProperty));
searchingForIdElement = false;
}
if (ancestor.ClientIDMode == ClientIDMode.Static)
{
break;
}
}
if (searchingForIdElement)
{
fragments.Add(childContainer!.GetDotvvmUniqueId());
}
fragments.Reverse();
return fragments;
}
/// <summary>
/// Verifies that the control contains only a plain text content and tries to extract it.
/// </summary>
protected bool TryGetTextContent(out string textContent)
{
textContent = string.Join(string.Empty, Children.OfType<RawLiteral>().Where(l => !l.IsWhitespace).Select(l => l.UnencodedText));
return Children.All(c => c is RawLiteral);
}
public override IEnumerable<DotvvmBindableObject> GetLogicalChildren()
{
return Children;
}
protected internal override DotvvmBindableObject CloneControl()
{
var newControl = (DotvvmControl)base.CloneControl();
newControl.Children = new DotvvmControlCollection(newControl);
foreach (var child in Children)
newControl.Children.Add((DotvvmControl)child.CloneControl());
return newControl;
}
IEnumerable<DotvvmBindableObject> IDotvvmControl.GetAllAncestors(bool includingThis) => this.GetAllAncestors(includingThis);
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Net.Sockets;
namespace Hydra.Framework.AsyncSockets
{
//
//**********************************************************************
/// <summary>
/// A collection of <c>SocketStream</c> objects.
/// </summary>
//**********************************************************************
//
public class SocketsList
: CollectionBase,
IDisposable
{
#region Private Delegates
///<summary>
/// Called when ever the <c>SocketsList</c> gets empty.
///</summary>
private SocketsListEventHandler OnEmpty;
///<summary>
/// Called when the first item added(after was <c>SocketsList</c> empty).
///</summary>
private SocketsListEventHandler OnFirstItemAdded;
#endregion
#region Public Events
//
//**********************************************************************
/// <summary>
/// Called when ever the <c>SocketsList</c> gets empty.
/// </summary>
//**********************************************************************
//
[Category("Action") , Description("Is event is called when ever the SocketsList gets empty.")]
public event SocketsListEventHandler EmptyList
{
add
{
OnEmpty+= value;
}
remove
{
OnEmpty-= value;
}
}
//
//**********************************************************************
/// <summary>
/// Called when the first item added(after was <c>SocketsList</c> empty).
/// </summary>
//**********************************************************************
//
[Category("Action") , Description("Called when the first item added(after was SocketsList empty).")]
public event SocketsListEventHandler FirstItemAdded
{
add
{
OnFirstItemAdded+= value;
}
remove
{
OnFirstItemAdded-= value;
}
}
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the <c>SocketStream</c> object at the given location.
/// </summary>
/// <value></value>
//**********************************************************************
//
public SocketStream this[int indexer]
{
get
{
return (SocketStream)List[indexer];
}
set
{
List[indexer] = value;
}
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Adds an Client object to the <c>SocketsList</c> collection.
/// </summary>
/// <param name="SocketStreamObject"><c>SocketStream</c> object to add to the collection.</param>
/// <returns>
/// The position into which the new element was inserted.
/// </returns>
//**********************************************************************
//
public int Add(SocketStream SocketStreamObject)
{
int temp = List.Add(SocketStreamObject);
//
// If first item added and the event has handlers call them.
//
if (List.Count == 1 && OnFirstItemAdded != null)
OnFirstItemAdded();
return temp;
}
//
//**********************************************************************
/// <summary>
/// Inserts an item to the <c>SocketsList</c> at the specified position.
/// </summary>
/// <param name="Index">The zero-based index at which value should be inserted.</param>
/// <param name="SocketStreamObject">The item to insert into the <c>SocketsList</c>.</param>
//**********************************************************************
//
public void Insert(int Index, Socket SocketStreamObject)
{
List.Insert(Index, SocketStreamObject);
//
// If first item added and the event has handlers call them.
//
if (List.Count == 1 && OnFirstItemAdded != null)
OnFirstItemAdded();
}
//
//**********************************************************************
/// <summary>
/// Removes the first occurrence of a specific object from the <c>SocketsList</c>.
/// </summary>
/// <param name="SocketStreamObject">The <c>SocketStream</c> to remove from the <c>SocketsList</c>.</param>
//**********************************************************************
//
public void Remove(SocketStream SocketStreamObject)
{
List.Remove(SocketStreamObject);
//
// If list is empty and has event handlers call them.
//
if (List.Count == 0 && OnEmpty != null)
OnEmpty();
}
//
//**********************************************************************
/// <summary>
/// Removes from the <c>SocketsList</c> an item at the specified index.
/// </summary>
/// <param name="Index">The zero-based index of the item to remove.</param>
//**********************************************************************
//
public new void RemoveAt(int Index)
{
base.RemoveAt(Index);
//If list is empty and has event handlers call them.
if (List.Count == 0 && OnEmpty != null)
OnEmpty();
}
//
//**********************************************************************
/// <summary>
/// Removes all items from the <c>SocketsList</c>;
/// </summary>
//**********************************************************************
//
public new void Clear()
{
base.Clear();
//
// If has event handlers call them.
//
if (OnEmpty!=null)
OnEmpty();
}
//
//**********************************************************************
/// <summary>
/// Determines whether two <c>SocketsList</c> instances are equal.
/// </summary>
/// <param name="socketsList"><c>SocketsList</c> object to compare with the current one.</param>
/// <returns>
/// Boolean flag indicates whether the elements are equal.
/// </returns>
//**********************************************************************
//
public bool Equals(SocketsList socketsList)
{
return (List.Equals(socketsList.List));
}
//
//**********************************************************************
/// <summary>
/// Determines whether the <c>SocketsList</c> contains a specific value.
/// </summary>
/// <param name="SocketStreamObject">The <c>SocketStream</c> object to locate in the <c>SocketsList</c>.</param>
/// <returns>
/// True if the <c>SocketStream</c> is found in the <c>SocketsList</c>; otherwise, false.
/// </returns>
//**********************************************************************
//
public bool Contains(SocketStream SocketStreamObject)
{
return List.Contains(SocketStreamObject);
}
//
//**********************************************************************
/// <summary>
/// Determines the index of a specific item in the <c>SocketsList</c>.
/// </summary>
/// <param name="SocketStreamObject">The <c>SocketStream</c> object to locate in the <c>SocketsList</c>.</param>
/// <returns>
/// The index of value if found in the <c>SocketsList</c>; otherwise, -1.
/// </returns>
//**********************************************************************
//
public int IndexOf(SocketStream SocketStreamObject)
{
return List.IndexOf(SocketStreamObject);
}
//
//**********************************************************************
/// <summary>
/// Removes all the <c>SocketStream</c> that are not connected.
/// </summary>
//**********************************************************************
//
public void RemoveUnpluggedSockets()
{
for (int i=0; i < List.Count ;++i)
{
if (!this[i].GetSocket.Connected)
{
Remove(this[i]);
--i;
}
//
// If list is empty and has event handlers call them.
//
if (List.Count == 0 && OnEmpty != null)
OnEmpty();
}
}
#endregion
#region IDisposable Implementation
//
//**********************************************************************
/// <summary>
/// Releases resources.
/// </summary>
//**********************************************************************
//
public void Dispose()
{
foreach (SocketStream Sock in List)
{
Sock.Dispose();
}
List.Clear();
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedAdapter
{
using System.Collections.Generic;
/// <summary>
/// This class is used to specify the cell identifier.
/// </summary>
public class CellID : BasicObject
{
/// <summary>
/// Initializes a new instance of the CellID class with specified ExGuids.
/// </summary>
/// <param name="extendGuid1">Specify the first ExGuid.</param>
/// <param name="extendGuid2">Specify the second ExGuid.</param>
public CellID(ExGuid extendGuid1, ExGuid extendGuid2)
{
this.ExtendGUID1 = extendGuid1;
this.ExtendGUID2 = extendGuid2;
}
/// <summary>
/// Initializes a new instance of the CellID class, this is the copy constructor.
/// </summary>
/// <param name="cellId">Specify the CellID.</param>
public CellID(CellID cellId)
{
if (cellId.ExtendGUID1 != null)
{
this.ExtendGUID1 = new ExGuid(cellId.ExtendGUID1);
}
if (cellId.ExtendGUID2 != null)
{
this.ExtendGUID2 = new ExGuid(cellId.ExtendGUID2);
}
}
/// <summary>
/// Initializes a new instance of the CellID class, this is default constructor.
/// </summary>
public CellID()
{
}
/// <summary>
/// Gets or sets an extended GUID that specifies the first cell identifier.
/// </summary>
public ExGuid ExtendGUID1 { get; set; }
/// <summary>
/// Gets or sets an extended GUID that specifies the second cell identifier.
/// </summary>
public ExGuid ExtendGUID2 { get; set; }
/// <summary>
/// This method is used to convert the element of CellID basic object into a byte List.
/// </summary>
/// <returns>Return the byte list which store the byte information of CellID.</returns>
public override List<byte> SerializeToByteList()
{
List<byte> byteList = new List<byte>();
byteList.AddRange(this.ExtendGUID1.SerializeToByteList());
byteList.AddRange(this.ExtendGUID2.SerializeToByteList());
return byteList;
}
/// <summary>
/// Override the Equals method.
/// </summary>
/// <param name="obj">Specify the object.</param>
/// <returns>Return true if equals, otherwise return false.</returns>
public override bool Equals(object obj)
{
CellID another = obj as CellID;
if (another == null)
{
return false;
}
if (another.ExtendGUID1 != null && another.ExtendGUID2 != null && this.ExtendGUID1 != null && this.ExtendGUID2 != null)
{
return another.ExtendGUID1.Equals(this.ExtendGUID1) && another.ExtendGUID2.Equals(this.ExtendGUID2);
}
return false;
}
/// <summary>
/// Override the GetHashCode.
/// </summary>
/// <returns>Return the hash value.</returns>
public override int GetHashCode()
{
return this.ExtendGUID1.GetHashCode() + this.ExtendGUID2.GetHashCode();
}
/// <summary>
/// This method is used to deserialize the CellID basic object from the specified byte array and start index.
/// </summary>
/// <param name="byteArray">Specify the byte array.</param>
/// <param name="startIndex">Specify the start index from the byte array.</param>
/// <returns>Return the length in byte of the CellID basic object.</returns>
protected override int DoDeserializeFromByteArray(byte[] byteArray, int startIndex)
{
int index = startIndex;
this.ExtendGUID1 = BasicObject.Parse<ExGuid>(byteArray, ref index);
this.ExtendGUID2 = BasicObject.Parse<ExGuid>(byteArray, ref index);
return index - startIndex;
}
}
/// <summary>
/// This class is used to specify the array of cell IDs.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")]
public class CellIDArray : BasicObject
{
/// <summary>
/// Initializes a new instance of the CellIDArray class.
/// </summary>
/// <param name="count">Specify the number of CellID in the CellID array.</param>
/// <param name="content">Specify the list of CellID.</param>
public CellIDArray(ulong count, List<CellID> content)
{
this.Count = count;
this.Content = content;
}
/// <summary>
/// Initializes a new instance of the CellIDArray class, this is copy constructor.
/// </summary>
/// <param name="cellIdArray">Specify the CellIDArray.</param>
public CellIDArray(CellIDArray cellIdArray)
{
this.Count = cellIdArray.Count;
if (cellIdArray.Content != null)
{
foreach (CellID cellId in cellIdArray.Content)
{
this.Content.Add(new CellID(cellId));
}
}
}
/// <summary>
/// Initializes a new instance of the CellIDArray class, this is default constructor.
/// </summary>
public CellIDArray()
{
this.Content = new List<CellID>();
}
/// <summary>
/// Gets or sets a compact unsigned 64-bit integer that specifies the count of cell IDs in the array.
/// </summary>
public ulong Count { get; set; }
/// <summary>
/// Gets or sets a cell ID list that specifies a list of cells.
/// </summary>
public List<CellID> Content { get; set; }
/// <summary>
/// This method is used to convert the element of CellIDArray basic object into a byte List.
/// </summary>
/// <returns>Return the byte list which store the byte information of CellIDArray.</returns>
public override List<byte> SerializeToByteList()
{
List<byte> byteList = new List<byte>();
byteList.AddRange((new Compact64bitInt(this.Count)).SerializeToByteList());
if (this.Content != null)
{
foreach (CellID extendGuid in this.Content)
{
byteList.AddRange(extendGuid.SerializeToByteList());
}
}
return byteList;
}
/// <summary>
/// This method is used to deserialize the CellIDArray basic object from the specified byte array and start index.
/// </summary>
/// <param name="byteArray">Specify the byte array.</param>
/// <param name="startIndex">Specify the start index from the byte array.</param>
/// <returns>Return the length in byte of the CellIDArray basic object.</returns>
protected override int DoDeserializeFromByteArray(byte[] byteArray, int startIndex)
{
int index = startIndex;
this.Count = BasicObject.Parse<Compact64bitInt>(byteArray, ref index).DecodedValue;
for (ulong i = 0; i < this.Count; i++)
{
this.Content.Add(BasicObject.Parse<CellID>(byteArray, ref index));
}
return index - startIndex;
}
}
}
| |
namespace System.Workflow.Activities
{
#region Imports
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Drawing;
using System.Diagnostics;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Xml.Serialization;
using System.Workflow.ComponentModel.Compiler;
#endregion
[SRDescription(SR.StateActivityDescription)]
[ToolboxItem(typeof(ActivityToolboxItem))]
[Designer(typeof(StateDesigner), typeof(IDesigner))]
[ToolboxBitmap(typeof(StateActivity), "Resources.StateActivity.png")]
[ActivityValidator(typeof(StateActivityValidator))]
[SRCategory(SR.Standard)]
[System.Runtime.InteropServices.ComVisible(false)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class StateActivity : CompositeActivity
{
#region Fields
public const string StateChangeTrackingDataKey = "StateActivity.StateChange";
internal static DependencyProperty StateMachineExecutionStateProperty = DependencyProperty.Register(StateMachineExecutionState.StateMachineExecutionStateKey, typeof(StateMachineExecutionState), typeof(StateActivity), new PropertyMetadata());
#endregion Fields
#region Constructor
public StateActivity()
{
}
public StateActivity(string name)
: base(name)
{
}
#endregion Constructor
#region Methods
protected override void OnClosed(IServiceProvider provider)
{
base.RemoveProperty(StateActivity.StateMachineExecutionStateProperty);
}
#region Public Methods
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal Activity GetDynamicActivity(Activity childActivity)
{
if (childActivity == null)
throw new ArgumentNullException("childActivity");
if (!this.EnabledActivities.Contains(childActivity))
throw new ArgumentException(SR.GetString(SR.Error_StateChildNotFound), "childActivity");
else
{
Activity[] dynamicChildActivity = this.GetDynamicActivities(childActivity);
if (dynamicChildActivity.Length != 0)
return dynamicChildActivity[0];
else
return null;
}
}
public Activity GetDynamicActivity(String childActivityName)
{
if (childActivityName == null)
throw new ArgumentNullException("childActivityName");
Activity childActivity = null;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
if (this.EnabledActivities[i].QualifiedName.Equals(childActivityName))
{
childActivity = this.EnabledActivities[i];
break;
}
}
if (childActivity != null)
return GetDynamicActivity(childActivity);
throw new ArgumentException(SR.GetString(SR.Error_StateChildNotFound), "childActivityName");
}
#endregion Public Methods
protected override void Initialize(IServiceProvider provider)
{
base.Initialize(provider);
ActivityExecutionContext context = (ActivityExecutionContext)provider;
StateActivity rootState = StateMachineHelpers.GetRootState(this);
if (!StateMachineHelpers.IsStateMachine(rootState))
throw new InvalidOperationException(SR.GetError_StateActivityMustBeContainedInAStateMachine());
string initialStateName = StateMachineHelpers.GetInitialStateName(this);
if (String.IsNullOrEmpty(initialStateName))
throw new InvalidOperationException(SR.GetError_CannotExecuteStateMachineWithoutInitialState());
//
if (this.QualifiedName != initialStateName)
StateMachineSubscriptionManager.DisableStateWorkflowQueues(context, this);
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (StateMachineHelpers.IsRootState(this))
{
ExecuteRootState(executionContext);
}
else
{
if (StateMachineHelpers.IsLeafState(this))
{
ExecuteLeafState(executionContext);
}
else
{
ExecuteState(executionContext);
}
}
return this.ExecutionStatus;
}
private void ExecuteRootState(ActivityExecutionContext context)
{
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = new StateMachineExecutionState(this.WorkflowInstanceId);
executionState.SchedulerBusy = false;
state.SetValue(StateActivity.StateMachineExecutionStateProperty, executionState);
executionState.SubscriptionManager.CreateSetStateEventQueue(context);
string initialStateName = StateMachineHelpers.GetInitialStateName(state);
executionState.CalculateStateTransition(this, initialStateName);
executionState.ProcessActions(context);
}
private static void ExecuteState(ActivityExecutionContext context)
{
StateMachineExecutionState executionState = GetExecutionState(context);
executionState.SchedulerBusy = false;
executionState.ProcessActions(context);
}
private static void ExecuteLeafState(ActivityExecutionContext context)
{
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
executionState.SchedulerBusy = false;
executionState.CurrentStateName = state.QualifiedName;
StateInitializationActivity stateInitialization = GetStateInitialization(context);
if (stateInitialization != null)
{
ExecuteStateInitialization(context, stateInitialization);
}
else
{
EnteringLeafState(context);
}
}
private static void EnteringLeafState(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
Debug.Assert(StateMachineHelpers.IsLeafState(state));
StateMachineExecutionState executionState = GetExecutionState(state);
executionState.SubscriptionManager.SubscribeToSetStateEvent(context);
string completedStateName = StateMachineHelpers.GetCompletedStateName(state);
if (StateMachineHelpers.IsCompletedState(state))
{
// make sure that we track that we entered the completed state
EnteringStateAction enteringState = new EnteringStateAction(state.QualifiedName);
executionState.EnqueueAction(enteringState);
executionState.ProcessActions(context);
// this is the final state, so we start completing this tree
executionState.Completed = true;
LeavingState(context);
}
else
{
if (String.IsNullOrEmpty(executionState.NextStateName))
{
executionState.SubscriptionManager.ReevaluateSubscriptions(context);
EnteringStateAction enteringState = new EnteringStateAction(state.QualifiedName);
executionState.EnqueueAction(enteringState);
executionState.LockQueue();
}
else
{
// The StateInitialization requested a state transtion
EnteringStateAction enteringState = new EnteringStateAction(state.QualifiedName);
executionState.EnqueueAction(enteringState);
executionState.ProcessTransitionRequest(context);
}
executionState.ProcessActions(context);
}
}
internal static void LeavingState(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
if (StateMachineHelpers.IsLeafState(state))
{
StateFinalizationActivity stateFinalization = GetStateFinalization(context);
if (stateFinalization == null)
Complete(context);
else
ExecuteStateFinalization(context, stateFinalization);
}
else
Complete(context);
}
private static void CleanUp(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
if (state.ExecutionStatus == ActivityExecutionStatus.Faulting)
return; // if we're faulting, then we're already in a bad state, so we don't try to unsubscribe
StateMachineExecutionState executionState = GetExecutionState(state);
StateMachineSubscriptionManager subscriptionManager = executionState.SubscriptionManager;
subscriptionManager.UnsubscribeState(context);
if (StateMachineHelpers.IsRootState(state))
subscriptionManager.DeleteSetStateEventQueue(context);
else if (StateMachineHelpers.IsLeafState(state))
subscriptionManager.UnsubscribeToSetStateEvent(context);
}
protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
CleanUp(executionContext);
Debug.Assert(executionContext.Activity == this);
bool canCloseNow = true;
ActivityExecutionContextManager contextManager = executionContext.ExecutionContextManager;
foreach (ActivityExecutionContext existingContext in contextManager.ExecutionContexts)
{
if (existingContext.Activity.Parent == this)
{
canCloseNow = false;
if (existingContext.Activity.ExecutionStatus == ActivityExecutionStatus.Executing)
existingContext.CancelActivity(existingContext.Activity);
}
}
return canCloseNow ? ActivityExecutionStatus.Closed : this.ExecutionStatus;
}
private static void Complete(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
if (StateMachineHelpers.IsLeafState(state))
{
executionState.PreviousStateName = state.Name;
}
CleanUp(context);
executionState.SchedulerBusy = true;
context.CloseActivity();
}
private static void ExecuteChild(ActivityExecutionContext context, Activity childActivity)
{
if (context == null)
throw new ArgumentNullException("context");
if (childActivity == null)
throw new ArgumentNullException("childActivity");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
Debug.Assert(!executionState.SchedulerBusy);
executionState.SchedulerBusy = true;
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
ActivityExecutionContext childContext = contextManager.CreateExecutionContext(childActivity);
childContext.Activity.Closed += state.HandleChildActivityClosed;
childContext.ExecuteActivity(childContext.Activity);
}
private static void CleanupChildAtClosure(ActivityExecutionContext context, Activity childActivity)
{
if (context == null)
throw new ArgumentNullException("context");
if (childActivity == null)
throw new ArgumentNullException("childActivity");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
childActivity.Closed -= state.HandleChildActivityClosed;
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
ActivityExecutionContext childContext = contextManager.GetExecutionContext(childActivity);
contextManager.CompleteExecutionContext(childContext);
}
internal void RaiseProcessActionEvent(ActivityExecutionContext context)
{
StateMachineExecutionState executionState = GetExecutionState(context);
Debug.Assert(!executionState.SchedulerBusy);
executionState.SchedulerBusy = true;
base.Invoke<EventArgs>(this.HandleProcessActionEvent, new EventArgs());
}
private void HandleProcessActionEvent(object sender,
EventArgs eventArgs)
{
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
StateMachineExecutionState executionState = GetExecutionState(context);
executionState.SchedulerBusy = false;
executionState.ProcessActions(context);
}
#region HandleStatusChange
private void HandleChildActivityClosed(object sender, ActivityExecutionStatusChangedEventArgs eventArgs)
{
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
if (eventArgs == null)
throw new ArgumentNullException("eventArgs");
Activity completedChildActivity = eventArgs.Activity;
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(context);
executionState.SchedulerBusy = false;
CleanupChildAtClosure(context, completedChildActivity);
switch (state.ExecutionStatus)
{
case ActivityExecutionStatus.Canceling:
case ActivityExecutionStatus.Faulting:
context.CloseActivity();
return;
case ActivityExecutionStatus.Executing:
if (completedChildActivity is EventDrivenActivity)
{
HandleEventDrivenCompleted(context);
return;
}
StateInitializationActivity stateInitialization = completedChildActivity as StateInitializationActivity;
if (stateInitialization != null)
{
HandleStateInitializationCompleted(context, stateInitialization);
return;
}
if (completedChildActivity is StateFinalizationActivity)
{
HandleStateFinalizationCompleted(context);
return;
}
if (completedChildActivity is StateActivity)
{
HandleSubStateCompleted(context);
return;
}
InvalidChildActivity(state);
break;
default:
throw new InvalidOperationException(SR.GetInvalidActivityStatus(context.Activity));
}
}
private static void InvalidChildActivity(StateActivity state)
{
if (StateMachineHelpers.IsLeafState(state))
throw new InvalidOperationException(SR.GetError_InvalidLeafStateChild());
else
throw new InvalidOperationException(SR.GetError_InvalidCompositeStateChild());
}
internal static void ExecuteEventDriven(ActivityExecutionContext context, EventDrivenActivity eventDriven)
{
StateMachineExecutionState executionState = GetExecutionState(context);
Debug.Assert(!executionState.HasEnqueuedActions);
ExecuteChild(context, eventDriven);
}
private static void HandleEventDrivenCompleted(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(context);
if (String.IsNullOrEmpty(executionState.NextStateName))
{
executionState.SubscriptionManager.ReevaluateSubscriptions(context);
executionState.LockQueue();
}
else
executionState.ProcessTransitionRequest(context);
executionState.ProcessActions(context);
}
private static void ExecuteStateInitialization(ActivityExecutionContext context, StateInitializationActivity stateInitialization)
{
StateMachineExecutionState executionState = GetExecutionState(context);
Debug.Assert(!executionState.HasEnqueuedActions);
ExecuteChild(context, stateInitialization);
}
private static void HandleStateInitializationCompleted(ActivityExecutionContext context, StateInitializationActivity stateInitialization)
{
if (context == null)
throw new ArgumentNullException("context");
if (stateInitialization == null)
throw new ArgumentNullException("stateInitialization");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
if (!String.IsNullOrEmpty(executionState.NextStateName) && executionState.NextStateName.Equals(state.QualifiedName))
throw new InvalidOperationException(SR.GetInvalidSetStateInStateInitialization());
EnteringLeafState(context);
}
private static void ExecuteStateFinalization(ActivityExecutionContext context, StateFinalizationActivity stateFinalization)
{
StateMachineExecutionState executionState = GetExecutionState(context);
ExecuteChild(context, stateFinalization);
}
private static void HandleStateFinalizationCompleted(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateMachineExecutionState executionState = GetExecutionState(context);
Complete(context);
}
internal static void ExecuteState(ActivityExecutionContext context, StateActivity state)
{
StateMachineExecutionState executionState = GetExecutionState(context);
ExecuteChild(context, state);
}
private static void HandleSubStateCompleted(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateMachineExecutionState executionState = GetExecutionState(context);
if (executionState.Completed)
{
// We're closing the state machine
LeavingState(context);
}
else
{
executionState.ProcessActions(context);
}
}
#endregion
#region Helper methods
private static StateInitializationActivity GetStateInitialization(ActivityExecutionContext context)
{
StateActivity state = (StateActivity)context.Activity;
Debug.Assert(StateMachineHelpers.IsLeafState(state),
"GetStateInitialization: StateInitialization is only allowed in a leaf node state");
return GetHandlerActivity<StateInitializationActivity>(context);
}
private static StateFinalizationActivity GetStateFinalization(ActivityExecutionContext context)
{
StateActivity state = (StateActivity)context.Activity;
Debug.Assert(StateMachineHelpers.IsLeafState(state),
"GetStateFinalization: StateFinalization is only allowed in a leaf node state");
return GetHandlerActivity<StateFinalizationActivity>(context);
}
private static T GetHandlerActivity<T>(ActivityExecutionContext context) where T : class
{
StateActivity state = (StateActivity)context.Activity;
foreach (Activity activity in state.EnabledActivities)
{
T handler = activity as T;
if (handler != null)
{
return handler;
}
}
return null;
}
private static StateMachineExecutionState GetExecutionState(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
StateActivity state = (StateActivity)context.Activity;
StateMachineExecutionState executionState = GetExecutionState(state);
return executionState;
}
private static StateMachineExecutionState GetExecutionState(StateActivity state)
{
if (state == null)
throw new ArgumentNullException("state");
StateActivity rootState = StateMachineHelpers.GetRootState(state);
StateMachineExecutionState executionState = StateMachineExecutionState.Get(rootState);
return executionState;
}
#endregion
#endregion Methods
#region Dynamic Update Functions
protected override void OnActivityChangeAdd(ActivityExecutionContext executionContext, Activity addedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (addedActivity == null)
throw new ArgumentNullException("addedActivity");
if (!addedActivity.Enabled)
return;
if (executionContext.Activity.ExecutionStatus != ActivityExecutionStatus.Executing)
return; // activity is not executing
EventDrivenActivity eventDriven = addedActivity as EventDrivenActivity;
if (eventDriven == null)
return;
// Activity we added is an EventDrivenActivity
// First we disable the queue
StateMachineSubscriptionManager.ChangeEventDrivenQueueState(executionContext, eventDriven, false);
StateActivity rootState = StateMachineHelpers.GetRootState(executionContext.Activity as StateActivity);
StateMachineExecutionState executionState = StateMachineExecutionState.Get(rootState);
StateActivity currentState = StateMachineHelpers.GetCurrentState(executionContext);
if (currentState == null)
return; // Dynamic update happened before we entered the initial state
StateMachineSubscriptionManager subscriptionManager = executionState.SubscriptionManager;
subscriptionManager.ReevaluateSubscriptions(executionContext);
executionState.LockQueue();
executionState.ProcessActions(executionContext);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Cci;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.MutableCodeModel;
namespace GenFacades
{
public class Generator
{
private const uint ReferenceAssemblyFlag = 0x70;
public static bool Execute(
string seeds,
string contracts,
string facadePath,
Version assemblyFileVersion = null,
bool clearBuildAndRevision = false,
bool ignoreMissingTypes = false,
bool ignoreBuildAndRevisionMismatch = false,
bool buildDesignTimeFacades = false,
string inclusionContracts = null,
ErrorTreatment seedLoadErrorTreatment = ErrorTreatment.Default,
ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
string[] seedTypePreferencesUnsplit = null,
bool forceZeroVersionSeeds = false,
bool producePdb = true,
string partialFacadeAssemblyPath = null,
bool buildPartialReferenceFacade = false)
{
if (!Directory.Exists(facadePath))
Directory.CreateDirectory(facadePath);
var nameTable = new NameTable();
var internFactory = new InternFactory();
try
{
Dictionary<string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);
using (var contractHost = new HostEnvironment(nameTable, internFactory))
using (var seedHost = new HostEnvironment(nameTable, internFactory))
{
contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
seedHost.LoadErrorTreatment = seedLoadErrorTreatment;
var contractAssemblies = LoadAssemblies(contractHost, contracts);
IReadOnlyDictionary<string, IEnumerable<string>> docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);
IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();
IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;
if (forceZeroVersionSeeds)
{
// Create a deep copier, copy the seed assemblies, and zero out their versions.
var copier = new MetadataDeepCopier(seedHost);
for (int i = 0; i < seedAssemblies.Length; i++)
{
var mutableSeed = copier.Copy(seedAssemblies[i]);
mutableSeed.Version = new Version(0, 0, 0, 0);
// Copy the modified seed assembly back.
seedAssemblies[i] = mutableSeed;
if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
{
seedCoreAssemblyRef = mutableSeed;
}
}
}
var typeTable = GenerateTypeTable(seedAssemblies);
var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);
if (buildPartialReferenceFacade && ignoreMissingTypes)
{
throw new FacadeGenerationException(
"When buildPartialReferenceFacade is specified ignoreMissingTypes must not be specified.");
}
if (partialFacadeAssemblyPath != null)
{
if (contractAssemblies.Count() != 1)
{
throw new FacadeGenerationException(
"When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
}
if (buildPartialReferenceFacade)
{
throw new FacadeGenerationException(
"When partialFacadeAssemblyPath is specified, buildPartialReferenceFacade must not be specified.");
}
IAssembly contractAssembly = contractAssemblies.First();
IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
if (contractAssembly.Name != partialFacadeAssembly.Name
|| contractAssembly.Version.Major != partialFacadeAssembly.Version.Major
|| contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor
|| (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build)
|| (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision)
|| contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
{
throw new FacadeGenerationException(
string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
contractAssembly.AssemblyIdentity,
partialFacadeAssembly.AssemblyIdentity));
}
Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);
if (filledPartialFacade == null)
{
Trace.TraceError("Errors were encountered while generating the facade.");
return false;
}
string pdbLocation = null;
if (producePdb)
{
string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
if (producePdb && !File.Exists(pdbLocation))
{
pdbLocation = null;
Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
}
}
OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
}
else
{
foreach (var contract in contractAssemblies)
{
Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes, buildPartialReferenceFacade: buildPartialReferenceFacade);
if (facade == null)
{
#if !COREFX
Debug.Assert(Environment.ExitCode != 0);
#endif
return false;
}
OutputFacadeToFile(facadePath, seedHost, facade, contract);
}
}
}
return true;
}
catch (FacadeGenerationException ex)
{
Trace.TraceError(ex.Message);
#if !COREFX
Debug.Assert(Environment.ExitCode != 0);
#endif
return false;
}
}
private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null)
{
// Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name.
string facadeFileName = Path.GetFileName(contract.Location);
string facadeOutputPath = Path.Combine(facadePath, facadeFileName);
using (Stream peOutStream = File.Create(facadeOutputPath))
{
if (pdbLocation != null)
{
if (File.Exists(pdbLocation))
{
string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb");
using (Stream pdbReadStream = File.OpenRead(pdbLocation))
using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost))
using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader))
{
PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter);
}
}
else
{
throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation);
}
}
else
{
PeWriter.WritePeToStream(facade, seedHost, peOutStream);
}
}
}
private static Dictionary<string, string> ParseSeedTypePreferences(string[] preferences)
{
var dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
if (preferences != null)
{
foreach (string preference in preferences)
{
int i = preference.IndexOf('=');
if (i < 0)
{
throw new FacadeGenerationException("Invalid seed type preference. Correct usage is /preferSeedType:FullTypeName=AssemblyName");
}
string key = preference.Substring(0, i);
string value = preference.Substring(i + 1);
if (!key.StartsWith("T:", StringComparison.Ordinal))
{
key = "T:" + key;
}
string existingValue;
if (dictionary.TryGetValue(key, out existingValue))
{
Trace.TraceWarning("Overriding /preferSeedType:{0}={1} with /preferSeedType:{2}={3}.", key, existingValue, key, value);
}
dictionary[key] = value;
}
}
return dictionary;
}
private static IEnumerable<IAssembly> LoadAssemblies(HostEnvironment host, string assemblyPaths)
{
host.UnifyToLibPath = true;
string[] splitPaths = HostEnvironment.SplitPaths(assemblyPaths);
foreach (string path in splitPaths)
{
if (Directory.Exists(path))
{
host.AddLibPath(Path.GetFullPath(path));
}
else if (File.Exists(path))
{
host.AddLibPath(Path.GetDirectoryName(Path.GetFullPath(path)));
}
}
return host.LoadAssemblies(splitPaths);
}
private static IReadOnlyDictionary<string, IEnumerable<string>> GenerateDocIdTable(IEnumerable<IAssembly> contractAssemblies, string inclusionContracts)
{
Dictionary<string, HashSet<string>> mutableDocIdTable = new Dictionary<string, HashSet<string>>();
foreach (IAssembly contractAssembly in contractAssemblies)
{
string simpleName = contractAssembly.AssemblyIdentity.Name.Value;
if (mutableDocIdTable.ContainsKey(simpleName))
throw new FacadeGenerationException(string.Format("Multiple contracts named \"{0}\" specified on -contracts.", simpleName));
mutableDocIdTable[simpleName] = new HashSet<string>(EnumerateDocIdsToForward(contractAssembly));
}
if (inclusionContracts != null)
{
foreach (string inclusionContractPath in HostEnvironment.SplitPaths(inclusionContracts))
{
// Assembly identity conflicts are permitted and normal in the inclusion contract list so load each one in a throwaway host to avoid problems.
using (HostEnvironment inclusionHost = new HostEnvironment(new NameTable(), new InternFactory()))
{
IAssembly inclusionAssembly = inclusionHost.LoadAssemblyFrom(inclusionContractPath);
if (inclusionAssembly == null || inclusionAssembly is Dummy)
throw new FacadeGenerationException(string.Format("Could not load assembly \"{0}\".", inclusionContractPath));
string simpleName = inclusionAssembly.Name.Value;
HashSet<string> hashset;
if (!mutableDocIdTable.TryGetValue(simpleName, out hashset))
{
Trace.TraceWarning("An assembly named \"{0}\" was specified in the -include list but no contract was specified named \"{0}\". Ignoring.", simpleName);
}
else
{
foreach (string docId in EnumerateDocIdsToForward(inclusionAssembly))
{
hashset.Add(docId);
}
}
}
}
}
Dictionary<string, IEnumerable<string>> docIdTable = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, HashSet<string>> kv in mutableDocIdTable)
{
string key = kv.Key;
IEnumerable<string> sortedDocIds = kv.Value.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
docIdTable.Add(key, sortedDocIds);
}
return docIdTable;
}
private static IEnumerable<string> EnumerateDocIdsToForward(IAssembly contractAssembly)
{
// Use INamedTypeReference instead of INamespaceTypeReference in order to also include nested
// class type-forwards.
var typeForwardsToForward = contractAssembly.ExportedTypes.Select(alias => alias.AliasedType)
.OfType<INamedTypeReference>();
var typesToForward = contractAssembly.GetAllTypes().Where(t => TypeHelper.IsVisibleOutsideAssembly(t))
.OfType<INamespaceTypeDefinition>();
List<string> result = typeForwardsToForward.Concat(typesToForward)
.Select(type => TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId)).ToList();
foreach(var type in typesToForward)
{
AddNestedTypeDocIds(result, type);
}
return result;
}
private static void AddNestedTypeDocIds(List<string> docIds, INamedTypeDefinition type)
{
foreach (var nestedType in type.NestedTypes)
{
if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId));
AddNestedTypeDocIds(docIds, nestedType);
}
}
private static IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> GenerateTypeTable(IEnumerable<IAssembly> seedAssemblies)
{
var typeTable = new Dictionary<string, IReadOnlyList<INamedTypeDefinition>>();
foreach (var assembly in seedAssemblies)
{
foreach (var type in assembly.GetAllTypes().OfType<INamedTypeDefinition>())
{
if (!TypeHelper.IsVisibleOutsideAssembly(type))
continue;
AddTypeAndNestedTypesToTable(typeTable, type);
}
}
return typeTable;
}
private static void AddTypeAndNestedTypesToTable(Dictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, INamedTypeDefinition type)
{
if (type != null)
{
IReadOnlyList<INamedTypeDefinition> seedTypes;
string docId = TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId);
if (!typeTable.TryGetValue(docId, out seedTypes))
{
seedTypes = new List<INamedTypeDefinition>(1);
typeTable.Add(docId, seedTypes);
}
if (!seedTypes.Contains(type))
((List<INamedTypeDefinition>)seedTypes).Add(type);
foreach (INestedTypeDefinition nestedType in type.NestedTypes)
{
if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
AddTypeAndNestedTypesToTable(typeTable, nestedType);
}
}
}
private class FacadeGenerator
{
private readonly IMetadataHost _seedHost;
private readonly IMetadataHost _contractHost;
private readonly IReadOnlyDictionary<string, IEnumerable<string>> _docIdTable;
private readonly IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> _typeTable;
private readonly IReadOnlyDictionary<string, string> _seedTypePreferences;
private readonly bool _clearBuildAndRevision;
private readonly bool _buildDesignTimeFacades;
private readonly Version _assemblyFileVersion;
public FacadeGenerator(
IMetadataHost seedHost,
IMetadataHost contractHost,
IReadOnlyDictionary<string, IEnumerable<string>> docIdTable,
IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable,
IReadOnlyDictionary<string, string> seedTypePreferences,
bool clearBuildAndRevision,
bool buildDesignTimeFacades,
Version assemblyFileVersion
)
{
_seedHost = seedHost;
_contractHost = contractHost;
_docIdTable = docIdTable;
_typeTable = typeTable;
_seedTypePreferences = seedTypePreferences;
_clearBuildAndRevision = clearBuildAndRevision;
_buildDesignTimeFacades = buildDesignTimeFacades;
_assemblyFileVersion = assemblyFileVersion;
}
public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null, bool buildPartialReferenceFacade = false)
{
Assembly assembly;
if (overrideContractAssembly != null)
{
MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
}
else
{
MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
assembly = copier.Copy(contractAssembly);
// if building a reference facade don't strip the contract
if (!buildPartialReferenceFacade)
{
ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
rewriter.Rewrite(assembly);
}
}
string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value;
IEnumerable<string> docIds = _docIdTable[contractAssemblyName];
// Add all the type forwards
bool error = false;
Dictionary<string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef);
IEnumerable<string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id));
Dictionary<string, INamedTypeReference> forwardedTypes = new Dictionary<string, INamedTypeReference>();
foreach (string docId in docIdsToForward)
{
IReadOnlyList<INamedTypeDefinition> seedTypes;
if (!_typeTable.TryGetValue(docId, out seedTypes))
{
if (!ignoreMissingTypes && !buildPartialReferenceFacade)
{
Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
error = true;
}
continue;
}
INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
if (seedType == null)
{
TraceDuplicateSeedTypeError(docId, seedTypes);
error = true;
continue;
}
if (buildPartialReferenceFacade)
{
// honor preferSeedType for keeping contract type
string preferredSeedAssembly;
bool keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) &&
contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase);
if (keepType)
{
continue;
}
assembly.AllTypes.Remove(existingDocIds[docId]);
forwardedTypes.Add(docId, seedType);
}
AddTypeForward(assembly, seedType);
}
if (buildPartialReferenceFacade)
{
if (forwardedTypes.Count == 0)
{
Trace.TraceError("Did not find any types in any of the seed assemblies.");
return null;
}
else
{
// for any thing that's now a typeforward, make sure typerefs point to that rather than
// the type previously inside the assembly.
TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType =>
{
INamedTypeReference newType = null;
return forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType;
});
typeRefRewriter.Rewrite(assembly);
}
}
if (error)
{
return null;
}
if (_assemblyFileVersion != null)
{
assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
}
if (_buildDesignTimeFacades)
{
assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
assembly.Flags |= ReferenceAssemblyFlag;
}
if (_clearBuildAndRevision)
{
assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
}
AddWin32VersionResource(contractAssembly.Location, assembly);
return assembly;
}
private INamedTypeDefinition GetSeedType(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes)
{
Debug.Assert(seedTypes.Count != 0); // we should already have checked for non-existent types.
if (seedTypes.Count == 1)
{
return seedTypes[0];
}
string preferredSeedAssembly;
if (_seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly))
{
return seedTypes.SingleOrDefault(t => String.Equals(t.GetAssembly().Name.Value, preferredSeedAssembly, StringComparison.OrdinalIgnoreCase));
}
return null;
}
private static void TraceDuplicateSeedTypeError(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes)
{
Trace.TraceError("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId);
foreach (INamedTypeDefinition type in seedTypes)
{
Trace.TraceError(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value);
}
}
private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType)
{
var alias = new NamespaceAliasForType();
alias.AliasedType = ConvertDefinitionToReferenceIfTypeIsNested(seedType, _seedHost);
alias.IsPublic = true;
if (assembly.ExportedTypes == null)
assembly.ExportedTypes = new List<IAliasForType>();
// Make sure that the typeforward doesn't already exist in the ExportedTypes
if (!assembly.ExportedTypes.Any(t => t.AliasedType.RefDocId() == alias.AliasedType.RefDocId()))
assembly.ExportedTypes.Add(alias);
else
throw new FacadeGenerationException($"{seedType.FullName()} typeforward already exists");
}
private void AddWin32VersionResource(string contractLocation, Assembly facade)
{
var versionInfo = FileVersionInfo.GetVersionInfo(contractLocation);
var versionSerializer = new VersionResourceSerializer(
true,
versionInfo.Comments,
versionInfo.CompanyName,
versionInfo.FileDescription,
_assemblyFileVersion == null ? versionInfo.FileVersion : _assemblyFileVersion.ToString(),
versionInfo.InternalName,
versionInfo.LegalCopyright,
versionInfo.LegalTrademarks,
versionInfo.OriginalFilename,
versionInfo.ProductName,
_assemblyFileVersion == null ? versionInfo.ProductVersion : _assemblyFileVersion.ToString(),
facade.Version);
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream, Encoding.Unicode, true))
{
versionSerializer.WriteVerResource(writer);
var resource = new Win32Resource();
resource.Id = 1;
resource.TypeId = 0x10;
resource.Data = stream.ToArray().ToList();
facade.Win32Resources.Add(resource);
}
}
// This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table
// for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition
// so we make an ITypeReference copy as a workaround.
private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host)
{
var nestedTypeDef = typeDef as INestedTypeDefinition;
if (nestedTypeDef == null)
return typeDef;
var typeRef = new NestedTypeReference();
typeRef.Copy(nestedTypeDef, host.InternFactory);
return typeRef;
}
private ICustomAttribute CreateAttribute(string typeName, IAssembly seedCoreAssembly, string argument = null)
{
var type = seedCoreAssembly.GetAllTypes().FirstOrDefault(t => t.FullName() == typeName);
if (type == null)
{
throw new FacadeGenerationException(String.Format("Cannot find {0} type in seed core assembly.", typeName));
}
IEnumerable<IMethodDefinition> constructors = type.GetMembersNamed(_seedHost.NameTable.Ctor, false).OfType<IMethodDefinition>();
IMethodDefinition constructor = null;
if (argument != null)
{
constructor = constructors.SingleOrDefault(m => m.ParameterCount == 1 && m.Parameters.First().Type.AreEquivalent("System.String"));
}
else
{
constructor = constructors.SingleOrDefault(m => m.ParameterCount == 0);
}
if (constructor == null)
{
throw new FacadeGenerationException(String.Format("Cannot find {0} constructor taking single string argument in seed core assembly.", typeName));
}
var attribute = new CustomAttribute();
attribute.Constructor = constructor;
if (argument != null)
{
var argumentExpression = new MetadataConstant();
argumentExpression.Type = _seedHost.PlatformType.SystemString;
argumentExpression.Value = argument;
attribute.Arguments = new List<IMetadataExpression>(1);
attribute.Arguments.Add(argumentExpression);
}
return attribute;
}
}
private class ReferenceAssemblyToFacadeRewriter : MetadataRewriter
{
private IMetadataHost _seedHost;
private IMetadataHost _contractHost;
private IAssemblyReference _seedCoreAssemblyReference;
private bool _stripFileVersionAttributes;
public ReferenceAssemblyToFacadeRewriter(
IMetadataHost seedHost,
IMetadataHost contractHost,
IAssemblyReference seedCoreAssemblyReference,
bool stripFileVersionAttributes)
: base(seedHost)
{
_seedHost = seedHost;
_contractHost = contractHost;
_stripFileVersionAttributes = stripFileVersionAttributes;
_seedCoreAssemblyReference = seedCoreAssemblyReference;
}
public override IAssemblyReference Rewrite(IAssemblyReference assemblyReference)
{
if (assemblyReference == null)
return assemblyReference;
if (assemblyReference.UnifiedAssemblyIdentity.Equals(_contractHost.CoreAssemblySymbolicIdentity) &&
!assemblyReference.ModuleIdentity.Equals(host.CoreAssemblySymbolicIdentity))
{
assemblyReference = _seedCoreAssemblyReference;
}
return base.Rewrite(assemblyReference);
}
public override void RewriteChildren(RootUnitNamespace rootUnitNamespace)
{
var assemblyReference = rootUnitNamespace.Unit as IAssemblyReference;
if (assemblyReference != null)
rootUnitNamespace.Unit = Rewrite(assemblyReference).ResolvedUnit;
base.RewriteChildren(rootUnitNamespace);
}
public override List<INamespaceMember> Rewrite(List<INamespaceMember> namespaceMembers)
{
// Ignore traversing or rewriting any namspace members.
return base.Rewrite(new List<INamespaceMember>());
}
public override void RewriteChildren(Assembly assembly)
{
// Clear all win32 resources. The version resource will get repopulated.
assembly.Win32Resources = new List<IWin32Resource>();
// Remove all the references they will get repopulated while outputing.
assembly.AssemblyReferences.Clear();
// Remove all the module references (aka native references)
assembly.ModuleReferences = new List<IModuleReference>();
// Remove all file references (ex: *.nlp files in mscorlib)
assembly.Files = new List<IFileReference>();
// Remove all security attributes (ex: permissionset in IL)
assembly.SecurityAttributes = new List<ISecurityAttribute>();
// Reset the core assembly symbolic identity to the seed core assembly (e.g. mscorlib, corefx)
// and not the contract core (e.g. System.Runtime).
assembly.CoreAssemblySymbolicIdentity = _seedCoreAssemblyReference.AssemblyIdentity;
// Add reference to seed core assembly up-front so that we keep the same order as the C# compiler.
assembly.AssemblyReferences.Add(_seedCoreAssemblyReference);
// Remove all type definitions except for the "<Module>" type. Remove all fields and methods from it.
NamespaceTypeDefinition moduleType = assembly.AllTypes.SingleOrDefault(t => t.Name.Value == "<Module>") as NamespaceTypeDefinition;
assembly.AllTypes.Clear();
if (moduleType != null)
{
moduleType.Fields?.Clear();
moduleType.Methods?.Clear();
assembly.AllTypes.Add(moduleType);
}
// Remove any preexisting typeforwards.
assembly.ExportedTypes = new List<IAliasForType>();
// Remove any preexisting resources.
assembly.Resources = new List<IResourceReference>();
// Clear the reference assembly flag from the contract.
// For design-time facades, it will be added back later.
assembly.Flags &= ~ReferenceAssemblyFlag;
// This flag should not be set until the delay-signed assembly we emit is actually signed.
assembly.StrongNameSigned = false;
base.RewriteChildren(assembly);
}
public override List<ICustomAttribute> Rewrite(List<ICustomAttribute> customAttributes)
{
if (customAttributes == null)
return customAttributes;
List<ICustomAttribute> newCustomAttributes = new List<ICustomAttribute>();
// Remove all of them except for the ones that begin with Assembly
// Also remove AssemblyFileVersion and AssemblyInformationVersion if stripFileVersionAttributes is set
foreach (ICustomAttribute attribute in customAttributes)
{
ITypeReference attributeType = attribute.Type;
if (attributeType is Dummy)
continue;
string typeName = TypeHelper.GetTypeName(attributeType, NameFormattingOptions.OmitContainingNamespace | NameFormattingOptions.OmitContainingType);
if (!typeName.StartsWith("Assembly"))
continue;
// We need to remove the signature key attribute otherwise we will not be able to re-sign these binaries.
if (typeName == "AssemblySignatureKeyAttribute")
continue;
if (_stripFileVersionAttributes && ((typeName == "AssemblyFileVersionAttribute" || typeName == "AssemblyInformationalVersionAttribute")))
continue;
newCustomAttributes.Add(attribute);
}
return base.Rewrite(newCustomAttributes);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Data.Common;
using System.Globalization;
namespace System.Data.SqlClient.ManualTesting.Tests
{
/// <summary>
/// represents a base class for SQL type random generation
/// </summary>
public abstract class SqlRandomTypeInfo
{
// max size on the row for large blob types to prevent row overflow, when creating the table:
// "Warning: The table "TestTable" has been created, but its maximum row size exceeds the allowed maximum of 8060 bytes. INSERT or UPDATE to this table will fail if the resulting row exceeds the size limit."
// tests show that the actual size is 36, I added 4 more bytes for extra
protected const int LargeVarDataRowUsage = 40; // var types
protected const int LargeDataRowUsage = 40; // text/ntext/image
protected internal const int XmlRowUsage = 40; //
protected const int VariantRowUsage = 40;
public readonly SqlDbType Type;
protected SqlRandomTypeInfo(SqlDbType t)
{
Type = t;
}
/// <summary>
/// true if column of this type can be created as sparse column
/// </summary>
public virtual bool CanBeSparseColumn
{
get
{
return true;
}
}
/// <summary>
/// creates a default column instance for given type
/// </summary>
public SqlRandomTableColumn CreateDefaultColumn()
{
return CreateDefaultColumn(SqlRandomColumnOptions.None);
}
/// <summary>
/// creates a default column instance for given type
/// </summary>
public virtual SqlRandomTableColumn CreateDefaultColumn(SqlRandomColumnOptions options)
{
return new SqlRandomTableColumn(this, options);
}
/// <summary>
/// creates a column with random size/precision/scale values, where applicable.
/// </summary>
/// <remarks>this method is overridden for some types to create columns with random size/precision</remarks>
public virtual SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
{
return CreateDefaultColumn(options);
}
/// <summary>
/// helper method to check validity of input column
/// </summary>
protected void ValidateColumnInfo(SqlRandomTableColumn columnInfo)
{
if (columnInfo == null)
throw new ArgumentNullException("columnInfo");
if (Type != columnInfo.Type)
throw new ArgumentException("Type mismatch");
}
/// <summary>
/// Returns the size used by a column value within the row. This method is used when generating random table to ensure
/// the row size does not overflow
/// </summary>
public double GetInRowSize(SqlRandomTableColumn columnInfo, object value)
{
ValidateColumnInfo(columnInfo);
if (columnInfo.IsSparse)
{
if (value == DBNull.Value && value == null)
{
// null values of sparse columns do not use in-row size
return 0;
}
else
{
// if sparse column has non-null value, it has an additional penalty of 4 bytes added to its storage size
return 4 + GetInRowSizeInternal(columnInfo);
}
}
else
{
// not a sparse column
return GetInRowSizeInternal(columnInfo);
}
}
protected abstract double GetInRowSizeInternal(SqlRandomTableColumn columnInfo);
/// <summary>
/// gets TSQL definition of the column
/// </summary>
public string GetTSqlTypeDefinition(SqlRandomTableColumn columnInfo)
{
ValidateColumnInfo(columnInfo);
return GetTSqlTypeDefinitionInternal(columnInfo);
}
protected abstract string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo);
/// <summary>
/// creates random, but valued value for the type, based on the given column definition
/// </summary>
public object CreateRandomValue(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
{
ValidateColumnInfo(columnInfo);
return CreateRandomValueInternal(rand, columnInfo);
}
protected abstract object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo);
/// <summary>
/// helper method to read character data from the reader
/// </summary>
protected object ReadCharData(DbDataReader reader, int ordinal, Type asType)
{
if (reader.IsDBNull(ordinal))
return DBNull.Value;
if (asType == typeof(string))
return reader.GetString(ordinal);
else if (asType == typeof(char[]) || asType == typeof(DBNull))
return reader.GetString(ordinal).ToCharArray();
else
throw new NotSupportedException("Wrong type: " + asType.FullName);
}
/// <summary>
/// helper method to read byte-array data from the reader
/// </summary>
protected object ReadByteArray(DbDataReader reader, int ordinal, Type asType)
{
if (reader.IsDBNull(ordinal))
return DBNull.Value;
if (asType == typeof(byte[]) || asType == typeof(DBNull))
return (byte[])reader.GetValue(ordinal);
else
throw new NotSupportedException("Wrong type: " + asType.FullName);
}
protected bool IsNullOrDbNull(object value)
{
return DBNull.Value.Equals(value) || value == null;
}
/// <summary>
/// helper method to check that actual test value has same type as expectedType or it is dbnull.
/// </summary>
/// <param name="bothDbNull">set to true if both values are DbNull</param>
/// <returns>true if expected value is DbNull or has the expected type</returns>
protected bool CompareDbNullAndType(Type expectedType, object expected, object actual, out bool bothDbNull)
{
bool isNullExpected = IsNullOrDbNull(expected);
bool isNullActual = IsNullOrDbNull(actual);
bothDbNull = isNullActual && isNullExpected;
if (bothDbNull)
return true;
if (isNullActual || isNullExpected)
return false; // only one is null, but not both
if (expectedType == null)
return true;
// both not null
if (expectedType != expected.GetType())
throw new ArgumentException("Wrong type!");
return (expectedType == actual.GetType());
}
/// <summary>
/// helper method to compare two byte arrays
/// </summary>
/// <remarks>I considered use of Generics here, but switched to explicit typed version due to performance overhead.
/// When using generic version, there is no way to quickly compare two values (expected[i] == actual[i]), and using
/// Equals method performs boxing, increasing the time spent on this method.</remarks>
private bool CompareByteArray(byte[] expected, byte[] actual, bool allowIncomplete = false, byte paddingValue = 0)
{
if (expected.Length > actual.Length)
{
return false;
}
else if (!allowIncomplete && expected.Length < actual.Length)
{
return false;
}
// check expected array values
int end = expected.Length;
for (int i = 0; i < end; i++)
{
if (expected[i] != actual[i])
return false;
}
// check for padding in actual values
end = actual.Length;
for (int i = expected.Length; i < end; i++)
{
// ensure rest of array are zeros
if (paddingValue != actual[i])
{
return false;
}
}
return true;
}
/// <summary>
/// helper method to compare two char arrays
/// </summary>
/// <remarks>I considered use of Generics here, but switched to explicit typed version due to performance overhead.
/// When using generic version, there is no way to quickly compare two values (expected[i] == actual[i]), and using
/// Equals method performs boxing, increasing the time spent on this method.</remarks>
private bool CompareCharArray(char[] expected, char[] actual, bool allowIncomplete = false, char paddingValue = ' ')
{
if (expected.Length > actual.Length)
{
return false;
}
else if (!allowIncomplete && expected.Length < actual.Length)
{
return false;
}
// check expected array values
int end = expected.Length;
for (int i = 0; i < end; i++)
{
if (expected[i] != actual[i])
return false;
}
// check for padding in actual values
end = actual.Length;
for (int i = expected.Length; i < end; i++)
{
// ensure rest of array are zeros
if (paddingValue != actual[i])
{
return false;
}
}
return true;
}
/// <summary>
/// helper method to compare two non-array values.
/// </summary>
protected bool CompareValues<T>(object expected, object actual) where T : struct
{
bool bothDbNull;
if (!CompareDbNullAndType(typeof(T), expected, actual, out bothDbNull) || bothDbNull)
return bothDbNull;
return expected.Equals(actual);
}
/// <summary>
/// validates that the actual value is DbNull or byte array and compares it to expected
/// </summary>
protected bool CompareByteArray(object expected, object actual, bool allowIncomplete, byte paddingValue = 0)
{
bool bothDbNull;
if (!CompareDbNullAndType(typeof(byte[]), expected, actual, out bothDbNull) || bothDbNull)
return bothDbNull;
return CompareByteArray((byte[])expected, (byte[])actual, allowIncomplete, paddingValue);
}
/// <summary>
/// validates that the actual value is DbNull or char array and compares it to expected
/// </summary>
protected bool CompareCharArray(object expected, object actual, bool allowIncomplete, char paddingValue = ' ')
{
bool bothDbNull;
if (!CompareDbNullAndType(typeof(char[]), expected, actual, out bothDbNull) || bothDbNull)
return bothDbNull;
return CompareCharArray((char[])expected, (char[])actual, allowIncomplete, paddingValue);
}
/// <summary>
/// helper method to reads datetime from the reader
/// </summary>
protected object ReadDateTime(DbDataReader reader, int ordinal, Type asType)
{
ValidateReadType(typeof(DateTime), asType);
if (reader.IsDBNull(ordinal))
return DBNull.Value;
return reader.GetDateTime(ordinal);
}
protected void ValidateReadType(Type expectedType, Type readAsType)
{
if (readAsType != expectedType && readAsType != typeof(DBNull))
throw new ArgumentException("Wrong type: " + readAsType.FullName);
}
/// <summary>
/// this method is called to read the value from the data reader
/// </summary>
public object Read(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
{
if (reader == null || asType == null)
throw new ArgumentNullException("reader == null || asType == null");
ValidateColumnInfo(columnInfo);
return ReadInternal(reader, ordinal, columnInfo, asType);
}
protected abstract object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType);
/// <summary>
/// used to check if this column can be compared; returns true by default (timestamp and column set columns return false)
/// </summary>
public virtual bool CanCompareValues(SqlRandomTableColumn columnInfo)
{
return true;
}
/// <summary>
/// This method is called to compare the actual value read to expected. Expected value must be either dbnull or from the given type.
/// Actual value can be any.
/// </summary>
public bool CompareValues(SqlRandomTableColumn columnInfo, object expected, object actual)
{
ValidateColumnInfo(columnInfo);
return CompareValuesInternal(columnInfo, expected, actual);
}
protected abstract bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual);
public string BuildErrorMessage(SqlRandomTableColumn columnInfo, object expected, object actual)
{
ValidateColumnInfo(columnInfo);
string expectedAsString = IsNullOrDbNull(expected) ? "null" : "\"" + ValueAsString(columnInfo, expected) + "\"";
string actualAsString = IsNullOrDbNull(actual) ? "null" : "\"" + ValueAsString(columnInfo, actual) + "\"";
return string.Format(CultureInfo.InvariantCulture,
" Column type: {0}\n" +
" Expected value: {1}\n" +
" Actual value: {2}",
GetTSqlTypeDefinition(columnInfo),
expectedAsString,
actualAsString);
}
/// <summary>
/// using ToString by default, supports arrays and many primitives;
/// override as needed
/// </summary>
/// <param name="value">value is not null or dbnull(validated before)</param>
protected virtual string ValueAsString(SqlRandomTableColumn columnInfo, object value)
{
Array a = value as Array;
if (a == null)
{
return string.Format(CultureInfo.InvariantCulture, "{0}: {1}", value.GetType().Name, PrimitiveValueAsString(value));
}
else
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}[{1}]", value.GetType().Name, a.Length);
if (a.Length > 0)
{
sb.Append(":");
for (int i = 0; i < a.Length; i++)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", PrimitiveValueAsString(a.GetValue(i)));
}
}
return sb.ToString();
}
}
public string PrimitiveValueAsString(object value)
{
if (value is char)
{
int c = (int)(char)value; // double-cast is needed from object
return c.ToString("X4", CultureInfo.InvariantCulture);
}
else if (value is byte)
{
byte b = (byte)value;
return b.ToString("X2", CultureInfo.InvariantCulture);
}
else
{
return string.Format(CultureInfo.InvariantCulture, "{0}", value.ToString());
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Year 9-12 Exit Destinations Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGDDataSet : EduHubDataSet<KGD>
{
/// <inheritdoc />
public override string Name { get { return "KGD"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return false; } }
internal KGDDataSet(EduHubContext Context)
: base(Context)
{
Index_KGDKEY = new Lazy<Dictionary<string, KGD>>(() => this.ToDictionary(i => i.KGDKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGD" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGD" /> fields for each CSV column header</returns>
internal override Action<KGD, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGD, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KGDKEY":
mapper[i] = (e, v) => e.KGDKEY = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "CATEGORY":
mapper[i] = (e, v) => e.CATEGORY = v;
break;
case "OPEN_CLOSED":
mapper[i] = (e, v) => e.OPEN_CLOSED = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGD" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGD" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGD" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGD}"/> of entities</returns>
internal override IEnumerable<KGD> ApplyDeltaEntities(IEnumerable<KGD> Entities, List<KGD> DeltaEntities)
{
HashSet<string> Index_KGDKEY = new HashSet<string>(DeltaEntities.Select(i => i.KGDKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KGDKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KGDKEY.Remove(entity.KGDKEY);
if (entity.KGDKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KGD>> Index_KGDKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KGD by KGDKEY field
/// </summary>
/// <param name="KGDKEY">KGDKEY value used to find KGD</param>
/// <returns>Related KGD entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGD FindByKGDKEY(string KGDKEY)
{
return Index_KGDKEY.Value[KGDKEY];
}
/// <summary>
/// Attempt to find KGD by KGDKEY field
/// </summary>
/// <param name="KGDKEY">KGDKEY value used to find KGD</param>
/// <param name="Value">Related KGD entity</param>
/// <returns>True if the related KGD entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKGDKEY(string KGDKEY, out KGD Value)
{
return Index_KGDKEY.Value.TryGetValue(KGDKEY, out Value);
}
/// <summary>
/// Attempt to find KGD by KGDKEY field
/// </summary>
/// <param name="KGDKEY">KGDKEY value used to find KGD</param>
/// <returns>Related KGD entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGD TryFindByKGDKEY(string KGDKEY)
{
KGD value;
if (Index_KGDKEY.Value.TryGetValue(KGDKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGD table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGD](
[KGDKEY] varchar(6) NOT NULL,
[DESCRIPTION] varchar(50) NULL,
[CATEGORY] varchar(50) NULL,
[OPEN_CLOSED] varchar(1) NULL,
CONSTRAINT [KGD_Index_KGDKEY] PRIMARY KEY CLUSTERED (
[KGDKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KGDDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KGDDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGD"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGD"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGD> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KGDKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KGDKEY.Add(entity.KGDKEY);
}
builder.AppendLine("DELETE [dbo].[KGD] WHERE");
// Index_KGDKEY
builder.Append("[KGDKEY] IN (");
for (int index = 0; index < Index_KGDKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KGDKEY
var parameterKGDKEY = $"@p{parameterIndex++}";
builder.Append(parameterKGDKEY);
command.Parameters.Add(parameterKGDKEY, SqlDbType.VarChar, 6).Value = Index_KGDKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGD data set</returns>
public override EduHubDataSetDataReader<KGD> GetDataSetDataReader()
{
return new KGDDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGD data set</returns>
public override EduHubDataSetDataReader<KGD> GetDataSetDataReader(List<KGD> Entities)
{
return new KGDDataReader(new EduHubDataSetLoadedReader<KGD>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGDDataReader : EduHubDataSetDataReader<KGD>
{
public KGDDataReader(IEduHubDataSetReader<KGD> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 4; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KGDKEY
return Current.KGDKEY;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // CATEGORY
return Current.CATEGORY;
case 3: // OPEN_CLOSED
return Current.OPEN_CLOSED;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // CATEGORY
return Current.CATEGORY == null;
case 3: // OPEN_CLOSED
return Current.OPEN_CLOSED == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KGDKEY
return "KGDKEY";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // CATEGORY
return "CATEGORY";
case 3: // OPEN_CLOSED
return "OPEN_CLOSED";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KGDKEY":
return 0;
case "DESCRIPTION":
return 1;
case "CATEGORY":
return 2;
case "OPEN_CLOSED":
return 3;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using DotNetRules.Runtime;
namespace DotNetRules
{
public class Settings
{
public bool CatchExceptions { get; set; }
}
public static class Executor
{
public static readonly Settings Settings = new Settings { CatchExceptions = false };
public static List<ExceptionInformation> Exceptions { get; private set; }
static volatile Dictionary<string, List<object>> _types = new Dictionary<string, List<object>>();
static readonly object SyncRoot = new object();
[Experimental]
public static void RegisterObject<T>(T type)
{
var fullName = type.GetType().FullName;
if (string.IsNullOrEmpty(fullName))
throw new Exception("Only types with full names can be registered");
lock (SyncRoot)
{
if (!_types.ContainsKey(fullName))
{
_types.Add(fullName, new List<object>());
}
_types[fullName].Add(type);
}
}
[Experimental]
public static IEnumerable<T> Resolve<T>()
{
var fullName = typeof(T).FullName;
if (string.IsNullOrEmpty(fullName))
throw new Exception("Only types with full names can be resolved");
return _types.ContainsKey(fullName) ? _types[fullName].Select(_ => (T) _) : new List<T>();
}
[Experimental]
public static void ExecuteOn<T>(Action<T> action)
{
Resolve<T>().ToList().ForEach(action);
}
[Experimental]
public static void NotifyPolicies<TSubject>(this TSubject subject, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
new Task(() => Apply(subject, policyLocation, policies)).Start();
}
public static ExecutionTrace ApplyPolicies<TSubject>(this TSubject subject, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return Apply(subject, policyLocation, policies);
}
public static ExecutionTrace ApplyPoliciesFor<TSubject, TSource>(this TSubject subject, TSource source, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return (ExecutionTrace)Apply<object, TSubject, TSource>(subject, source, policyLocation, policies);
}
public static ExecutionTrace Apply<TSubject>(TSubject subject, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return (ExecutionTrace)Apply<object, TSubject>(subject, policyLocation, policies);
}
public static ExecutionTrace<TReturn> ApplyPolicies<TReturn, TSubject>(this TSubject subject, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return Apply<TReturn, TSubject>(subject, policyLocation, policies);
}
public static ExecutionTrace<TReturn> ApplyPoliciesFor<TReturn, TSubject, TSource>(this TSubject subject, TSource source, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return Apply<TReturn, TSubject, TSource>(subject, source, policyLocation, policies);
}
public static ExecutionTrace<TReturn> Apply<TReturn, TSubject>(TSubject subject, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
if (policies == null)
{
policies = Enumerable.Empty<Type>();
}
var type = (typeof(TSubject));
var policyLocations = RetrievePolicyLocations(ref policyLocation, policies, type);
Exceptions = new List<ExceptionInformation>();
var executionTrace = new ExecutionTrace<TReturn>(policyLocation);
foreach (var mon in policyLocations.SelectMany(location => location.GetTypesWithPolicyAttribute(policies.Any(), type)
.Select(item => new DotNetRulesContext(item))
.Where(_ => (!policies.Any()) || policies.Any(type1 => type1 == _.CurrentPolicy))))
{
mon.Establish(subject);
if (mon.Given() || mon.Or())
{
executionTrace.Called++;
executionTrace.By.Enqueue(mon.CurrentPolicy);
MonitorThen(mon);
}
mon.Finally();
executionTrace.ReturnType = mon.Return<TReturn>();
}
return executionTrace;
}
public static ExecutionTrace Apply<TSource, TTarget>(TSource source, TTarget target, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
return (ExecutionTrace)Apply<object, TSource, TTarget>(source, target, policyLocation, policies);
}
public static ExecutionTrace<TReturn> Apply<TReturn, TSource, TTarget>(TSource source, TTarget target, Assembly policyLocation = null, IEnumerable<Type> policies = null)
{
if (policies == null)
{
policies = Enumerable.Empty<Type>();
}
var type = (typeof(TSource));
var policyLocations = RetrievePolicyLocations(ref policyLocation, policies, type);
Exceptions = new List<ExceptionInformation>();
var executionTrace = new ExecutionTrace<TReturn>(policyLocation);
foreach (var mon in policyLocations.SelectMany(location => location.GetTypesWithPolicyAttribute(policies.Any(), type, typeof (TTarget))
.Select(item => new DotNetRulesContext(item))
.Where(_ => !policies.Any() || policies.Any(type1 => type1 == _.CurrentPolicy))))
{
mon.Establish(source, target);
if (mon.Given() || mon.Or())
{
executionTrace.Called++;
executionTrace.By.Enqueue(mon.CurrentPolicy);
MonitorThen(mon);
}
mon.Finally();
executionTrace.ReturnType = mon.Return<TReturn>();
}
return executionTrace;
}
public static ExecutionTrace Apply(params dynamic[] values)
{
return Apply(null, null, values);
}
public static ExecutionTrace Apply(IEnumerable<Type> policies, params dynamic[] values)
{
return Apply(null, policies, values);
}
public static ExecutionTrace Apply(Assembly policyLocation, params dynamic[] values)
{
return Apply(null, null, values);
}
public static ExecutionTrace Apply(Assembly policyLocation, IEnumerable<Type> policies, params dynamic[] values)
{
return (ExecutionTrace)Apply<object>(policyLocation, policies, values);
}
public static ExecutionTrace<TReturn> Apply<TReturn>(params dynamic[] values)
{
return Apply<TReturn>(null, null, values);
}
public static ExecutionTrace<TReturn> Apply<TReturn>(IEnumerable<Type> policies, params dynamic[] values)
{
return Apply<TReturn>(null, policies, values);
}
public static ExecutionTrace<TReturn> Apply<TReturn>(Assembly policyLocation, params dynamic[] values)
{
return Apply<TReturn>(null, null, values);
}
public static ExecutionTrace<TReturn> Apply<TReturn>(Assembly policyLocation, IEnumerable<Type> policies, params dynamic[] values)
{
if (policies == null)
{
policies = Enumerable.Empty<Type>();
}
var types = values.Select(_ => (Type)_.GetType()).ToArray();
if (policyLocation == null)
{
policyLocation = types.First().Assembly;
}
Exceptions = new List<ExceptionInformation>();
var target = new ExecutionTrace<TReturn>(policyLocation);
foreach (var mon in policyLocation.GetTypesWithPolicyAttribute(policies.Any(), types.ToArray())
.Select(item => new DotNetRulesContext(item))
.Where(_ => !policies.Any() || policies.Any(type1 => type1 == _.CurrentPolicy)))
{
mon.EstablishMore(values);
if (mon.Given() || mon.Or())
{
target.Called++;
target.By.Enqueue(mon.CurrentPolicy);
MonitorThen(mon);
}
mon.Finally();
for (var i = 0; i < values.Count(); i++)
{
var value = values[i];
target.ReturnType = mon.Return<TReturn>();
}
}
return target;
}
static void MonitorThen(DotNetRulesContext mon)
{
Exceptions.AddRange(mon.Then(Settings.CatchExceptions));
}
static IEnumerable<Assembly> RetrievePolicyLocations(ref Assembly policyLocation, IEnumerable<Type> policies, Type type)
{
var policyLocations = new List<Assembly>();
if (policyLocation == null)
{
policyLocations = policies.Any() ? policies.Select(_ => _.Assembly).Distinct().ToList() : AppDomain.CurrentDomain.GetAssemblies().ToList();
policyLocation = type.Assembly;
}
else
{
policyLocations.Add(policyLocation);
}
return policyLocations;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Tasks;
using System.Runtime.InteropServices.ComTypes;
using Marshal = System.Runtime.InteropServices.Marshal;
using COMException = System.Runtime.InteropServices.COMException;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class ComReferenceWalker_Tests
{
static private int MockReleaseComObject(object o)
{
return 0;
}
private void AssertDependenciesContainTypeLib(TYPELIBATTR[] dependencies, MockTypeLib typeLib, bool contains)
{
AssertDependenciesContainTypeLib("", dependencies, typeLib, contains);
}
private void AssertDependenciesContainTypeLib(string message, TYPELIBATTR[] dependencies, MockTypeLib typeLib, bool contains)
{
bool dependencyExists = false;
foreach (TYPELIBATTR attr in dependencies)
{
if (attr.guid == typeLib.Attributes.guid)
{
dependencyExists = true;
break;
}
}
Assert.Equal(contains, dependencyExists);
}
[Fact]
public void WalkTypeInfosInEmptyLibrary()
{
MockTypeLib typeLib = new MockTypeLib();
ComDependencyWalker walker = new ComDependencyWalker(new MarshalReleaseComObject(MockReleaseComObject));
walker.AnalyzeTypeLibrary(typeLib);
Assert.Equal(0, walker.GetDependencies().GetLength(0));
typeLib.AssertAllHandlesReleased();
}
private void CreateTwoTypeLibs(out MockTypeLib mainTypeLib, out MockTypeLib dependencyTypeLib)
{
mainTypeLib = new MockTypeLib();
mainTypeLib.AddTypeInfo(new MockTypeInfo());
dependencyTypeLib = new MockTypeLib();
dependencyTypeLib.AddTypeInfo(new MockTypeInfo());
}
private TYPELIBATTR[] RunDependencyWalker(MockTypeLib mainTypeLib, MockTypeLib dependencyTypeLib, bool dependencyShouldBePresent)
{
ComDependencyWalker walker = new ComDependencyWalker(new MarshalReleaseComObject(MockReleaseComObject));
walker.AnalyzeTypeLibrary(mainTypeLib);
TYPELIBATTR[] dependencies = walker.GetDependencies();
// types from the main type library should be in the dependency list
AssertDependenciesContainTypeLib(dependencies, mainTypeLib, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib, dependencyShouldBePresent);
mainTypeLib.AssertAllHandlesReleased();
dependencyTypeLib.AssertAllHandlesReleased();
return dependencies;
}
/// <summary>
/// A type in the main type library implements an interface from a dependent type library
/// </summary>
[Fact]
public void ImplementedInterfaces()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].ImplementsInterface(dependencyTypeLib.ContainedTypeInfos[0]);
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void DefinedVariableUDT()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib.ContainedTypeInfos[0]);
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void DefinedVariableUDTArray()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(new ArrayCompositeTypeInfo(dependencyTypeLib.ContainedTypeInfos[0]));
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void DefinedVariableUDTPtr()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(new PtrCompositeTypeInfo(dependencyTypeLib.ContainedTypeInfos[0]));
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void ThereAndBackAgain()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(new PtrCompositeTypeInfo(dependencyTypeLib.ContainedTypeInfos[0]));
dependencyTypeLib.ContainedTypeInfos[0].ImplementsInterface(mainTypeLib.ContainedTypeInfos[0]);
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void ComplexComposition()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(
new ArrayCompositeTypeInfo(new ArrayCompositeTypeInfo(new PtrCompositeTypeInfo(
new PtrCompositeTypeInfo(new ArrayCompositeTypeInfo(new PtrCompositeTypeInfo(dependencyTypeLib.ContainedTypeInfos[0])))))));
RunDependencyWalker(mainTypeLib, dependencyTypeLib, true);
}
[Fact]
public void DefinedFunction()
{
MockTypeLib mainTypeLib, dependencyTypeLib1, dependencyTypeLib2, dependencyTypeLib3;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib1);
CreateTwoTypeLibs(out dependencyTypeLib2, out dependencyTypeLib3);
mainTypeLib.ContainedTypeInfos[0].DefinesFunction(
new MockTypeInfo[] { dependencyTypeLib1.ContainedTypeInfos[0], dependencyTypeLib2.ContainedTypeInfos[0] },
dependencyTypeLib3.ContainedTypeInfos[0]);
TYPELIBATTR[] dependencies = RunDependencyWalker(mainTypeLib, dependencyTypeLib1, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib2, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib3, true);
dependencyTypeLib2.AssertAllHandlesReleased();
dependencyTypeLib3.AssertAllHandlesReleased();
}
[Fact]
public void IgnoreKnownOleTypes()
{
MockTypeLib mainTypeLib = new MockTypeLib();
mainTypeLib.AddTypeInfo(new MockTypeInfo());
MockTypeLib oleTypeLib = new MockTypeLib();
oleTypeLib.AddTypeInfo(new MockTypeInfo(NativeMethods.IID_IUnknown));
oleTypeLib.AddTypeInfo(new MockTypeInfo(NativeMethods.IID_IDispatch));
oleTypeLib.AddTypeInfo(new MockTypeInfo(NativeMethods.IID_IDispatchEx));
oleTypeLib.AddTypeInfo(new MockTypeInfo(NativeMethods.IID_IEnumVariant));
oleTypeLib.AddTypeInfo(new MockTypeInfo(NativeMethods.IID_ITypeInfo));
// We don't check for this type in the ComDependencyWalker, so it doesn't get counted as a known OLE type.
// It's too late in the Dev10 cycle to add it to shipping code without phenomenally good reason, but we should
// re-examine this in Dev11.
// oleTypeLib.AddTypeInfo(new MockTypeInfo(TYPEKIND.TKIND_ENUM));
foreach (MockTypeInfo typeInfo in oleTypeLib.ContainedTypeInfos)
{
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(typeInfo);
}
RunDependencyWalker(mainTypeLib, oleTypeLib, false);
}
[Fact]
public void IgnoreGuidType()
{
MockTypeLib mainTypeLib = new MockTypeLib();
mainTypeLib.AddTypeInfo(new MockTypeInfo());
MockTypeLib oleTypeLib = new MockTypeLib(NativeMethods.IID_StdOle);
oleTypeLib.AddTypeInfo(new MockTypeInfo());
oleTypeLib.ContainedTypeInfos[0].TypeName = "GUID";
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(oleTypeLib.ContainedTypeInfos[0]);
RunDependencyWalker(mainTypeLib, oleTypeLib, false);
}
[Fact]
public void IgnoreNetExportedTypeLibs()
{
MockTypeLib mainTypeLib, dependencyTypeLib;
CreateTwoTypeLibs(out mainTypeLib, out dependencyTypeLib);
mainTypeLib.ContainedTypeInfos[0].DefinesFunction(
new MockTypeInfo[] { dependencyTypeLib.ContainedTypeInfos[0] }, dependencyTypeLib.ContainedTypeInfos[0]);
dependencyTypeLib.ExportedFromComPlus = "1";
RunDependencyWalker(mainTypeLib, dependencyTypeLib, false);
}
/// <summary>
/// The main type lib is broken... don't expect any results, but make sure we don't throw.
/// </summary>
[Fact]
public void FaultInjectionMainLib()
{
// The primary test here is that we don't throw, which can't be explicitly expressed in NUnit...
// other asserts are secondary
foreach (MockTypeLibrariesFailurePoints failurePoint in Enum.GetValues(typeof(MockTypeLibrariesFailurePoints)))
{
MockTypeLib mainTypeLib = new MockTypeLib();
mainTypeLib.AddTypeInfo(new MockTypeInfo());
// Make it the StdOle lib to exercise the ITypeInfo.GetDocumentation failure point
MockTypeLib dependencyTypeLib = new MockTypeLib(NativeMethods.IID_StdOle);
dependencyTypeLib.AddTypeInfo(new MockTypeInfo());
COMException failureException = new COMException("unhandled exception in " + failurePoint.ToString());
mainTypeLib.InjectFailure(failurePoint, failureException);
dependencyTypeLib.InjectFailure(failurePoint, failureException);
mainTypeLib.ContainedTypeInfos[0].ImplementsInterface(dependencyTypeLib.ContainedTypeInfos[0]);
mainTypeLib.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib.ContainedTypeInfos[0]);
mainTypeLib.ContainedTypeInfos[0].DefinesFunction(
new MockTypeInfo[] { dependencyTypeLib.ContainedTypeInfos[0] }, dependencyTypeLib.ContainedTypeInfos[0]);
ComDependencyWalker walker = new ComDependencyWalker(new MarshalReleaseComObject(MockReleaseComObject));
walker.AnalyzeTypeLibrary(mainTypeLib);
Assert.Single(walker.EncounteredProblems); // "Test failed for failure point " + failurePoint.ToString()
Assert.Equal(failureException, walker.EncounteredProblems[0]); // "Test failed for failure point " + failurePoint.ToString()
mainTypeLib.AssertAllHandlesReleased();
dependencyTypeLib.AssertAllHandlesReleased();
}
}
private static void CreateFaultInjectionTypeLibs(MockTypeLibrariesFailurePoints failurePoint, out MockTypeLib mainTypeLib,
out MockTypeLib dependencyTypeLibGood1, out MockTypeLib dependencyTypeLibBad1,
out MockTypeLib dependencyTypeLibGood2, out MockTypeLib dependencyTypeLibBad2)
{
mainTypeLib = new MockTypeLib();
mainTypeLib.AddTypeInfo(new MockTypeInfo());
mainTypeLib.AddTypeInfo(new MockTypeInfo());
dependencyTypeLibGood1 = new MockTypeLib();
dependencyTypeLibGood1.AddTypeInfo(new MockTypeInfo());
// Make it the StdOle lib to exercise the ITypeInfo.GetDocumentation failure point
dependencyTypeLibBad1 = new MockTypeLib(NativeMethods.IID_StdOle);
dependencyTypeLibBad1.AddTypeInfo(new MockTypeInfo());
dependencyTypeLibGood2 = new MockTypeLib();
dependencyTypeLibGood2.AddTypeInfo(new MockTypeInfo());
// Make it the StdOle lib to exercise the ITypeInfo.GetDocumentation failure point
dependencyTypeLibBad2 = new MockTypeLib(NativeMethods.IID_StdOle);
dependencyTypeLibBad2.AddTypeInfo(new MockTypeInfo());
COMException failureException = new COMException("unhandled exception in " + failurePoint.ToString());
dependencyTypeLibBad1.InjectFailure(failurePoint, failureException);
dependencyTypeLibBad2.InjectFailure(failurePoint, failureException);
}
private void RunDependencyWalkerFaultInjection(MockTypeLibrariesFailurePoints failurePoint, MockTypeLib mainTypeLib, MockTypeLib dependencyTypeLibGood1, MockTypeLib dependencyTypeLibBad1, MockTypeLib dependencyTypeLibGood2, MockTypeLib dependencyTypeLibBad2)
{
ComDependencyWalker walker = new ComDependencyWalker(new MarshalReleaseComObject(MockReleaseComObject));
walker.AnalyzeTypeLibrary(mainTypeLib);
// Did the current failure point get hit for this test? If not then no point in checking anything
// The previous test (FaultInjectionMainLib) ensures that all defined failure points actually
// cause some sort of trouble
if (walker.EncounteredProblems.Count > 0)
{
TYPELIBATTR[] dependencies = walker.GetDependencies();
AssertDependenciesContainTypeLib("Test failed for failure point " + failurePoint.ToString(),
dependencies, mainTypeLib, true);
AssertDependenciesContainTypeLib("Test failed for failure point " + failurePoint.ToString(),
dependencies, dependencyTypeLibGood1, true);
AssertDependenciesContainTypeLib("Test failed for failure point " + failurePoint.ToString(),
dependencies, dependencyTypeLibGood2, true);
AssertDependenciesContainTypeLib("Test failed for failure point " + failurePoint.ToString(),
dependencies, dependencyTypeLibBad1, false);
AssertDependenciesContainTypeLib("Test failed for failure point " + failurePoint.ToString(),
dependencies, dependencyTypeLibBad2, false);
}
mainTypeLib.AssertAllHandlesReleased();
dependencyTypeLibGood1.AssertAllHandlesReleased();
dependencyTypeLibGood2.AssertAllHandlesReleased();
dependencyTypeLibBad1.AssertAllHandlesReleased();
dependencyTypeLibBad2.AssertAllHandlesReleased();
}
[Fact]
public void FullDependenciesWithIncrementalAnalysis()
{
MockTypeLib mainTypeLib1, mainTypeLib2, mainTypeLib3, dependencyTypeLib1, dependencyTypeLib2, dependencyTypeLib3;
CreateTwoTypeLibs(out mainTypeLib1, out dependencyTypeLib1);
CreateTwoTypeLibs(out mainTypeLib2, out dependencyTypeLib2);
CreateTwoTypeLibs(out mainTypeLib3, out dependencyTypeLib3);
mainTypeLib1.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib1.ContainedTypeInfos[0]);
mainTypeLib2.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib1.ContainedTypeInfos[0]);
mainTypeLib2.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib2.ContainedTypeInfos[0]);
mainTypeLib3.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib1.ContainedTypeInfos[0]);
mainTypeLib3.ContainedTypeInfos[0].DefinesVariable(dependencyTypeLib3.ContainedTypeInfos[0]);
ComDependencyWalker walker = new ComDependencyWalker(MockReleaseComObject);
walker.AnalyzeTypeLibrary(mainTypeLib1);
TYPELIBATTR[] dependencies = walker.GetDependencies();
ICollection<string> analyzedTypes = walker.GetAnalyzedTypeNames();
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib1, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib2, false);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib3, false);
Assert.Equal(2, analyzedTypes.Count);
walker.ClearDependencyList();
walker.AnalyzeTypeLibrary(mainTypeLib2);
dependencies = walker.GetDependencies();
analyzedTypes = walker.GetAnalyzedTypeNames();
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib1, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib2, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib3, false);
Assert.Equal(4, analyzedTypes.Count);
walker.ClearDependencyList();
walker.AnalyzeTypeLibrary(mainTypeLib3);
dependencies = walker.GetDependencies();
analyzedTypes = walker.GetAnalyzedTypeNames();
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib1, true);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib2, false);
AssertDependenciesContainTypeLib(dependencies, dependencyTypeLib3, true);
Assert.Equal(6, analyzedTypes.Count);
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// StringBuilder.Capacity Property
/// Gets or sets the maximum number of characters that can be contained
/// in the memory allocated by the current instance.
/// </summary>
public class StringBuilderCapacity
{
private const int c_MIN_STR_LEN = 1;
private const int c_MAX_STR_LEN = 260;
private const int c_MAX_CAPACITY = Int16.MaxValue;
public static int Main()
{
StringBuilderCapacity testObj = new StringBuilderCapacity();
TestLibrary.TestFramework.BeginTestCase("for property: StringBuilder.Capacity");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: Get the capacity property";
string errorDesc;
StringBuilder sb;
int actualCapacity, expectedCapacity;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
expectedCapacity = str.Length
+ TestLibrary.Generator.GetInt32(-55) % (c_MAX_CAPACITY - str.Length + 1);
sb = new StringBuilder(str, expectedCapacity);
actualCapacity = sb.Capacity;
if (actualCapacity != expectedCapacity)
{
errorDesc = "Capacity of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedCapacity, actualCapacity);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: Set the capacity property";
string errorDesc;
StringBuilder sb;
int actualCapacity, expectedCapacity;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
expectedCapacity = str.Length
+ TestLibrary.Generator.GetInt32(-55) % (c_MAX_CAPACITY - str.Length + 1);
sb.Capacity = expectedCapacity;
actualCapacity = sb.Capacity;
if (actualCapacity != expectedCapacity)
{
errorDesc = "Capacity of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedCapacity, actualCapacity);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentOutOfRangeException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: The value specified for a set operation is less than the current length of this instance.";
string errorDesc;
StringBuilder sb;
int capacity, currentInstanceLength;
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
currentInstanceLength = str.Length;
capacity = TestLibrary.Generator.GetInt32(-55) % currentInstanceLength;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Capacity = capacity;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nString value of StringBuilder is {0}", str);
errorDesc += string.Format("\nCurrent length of instance is {0}, capacity specified is {1}",
currentInstanceLength, capacity);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString value of StringBuilder is {0}", str);
errorDesc += string.Format("\nCurrent length of instance is {0}, capacity specified is {1}",
currentInstanceLength, capacity);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: The value specified for a set operation is less than zero.";
string errorDesc;
StringBuilder sb;
int capacity, currentInstanceLength;
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
currentInstanceLength = str.Length;
capacity = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Capacity = capacity;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nString value of StringBuilder is {0}", str);
errorDesc += string.Format("\nCurrent length of instance is {0}, capacity specified is {1}",
currentInstanceLength, capacity);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString value of StringBuilder is {0}", str);
errorDesc += string.Format("\nCurrent length of instance is {0}, capacity spdified is {1}",
currentInstanceLength, capacity);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: The value specified for a set operation is greater than the maximum capacity.";
string errorDesc;
StringBuilder sb;
int capacity;
int maxCapacity = TestLibrary.Generator.GetInt32(-55) % c_MAX_CAPACITY;
sb = new StringBuilder(0, maxCapacity);
capacity = maxCapacity + 1 + TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - maxCapacity);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Capacity = capacity;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nMaximum capacity of instance is {0}, capacity spdified is {1}",
maxCapacity, capacity);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nMaximum capacity of instance is {0}, capacity spdified is {1}",
maxCapacity, capacity);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System.IO;
using System.Net;
using System.Text;
using AsterNET.FastAGI.MappingStrategies;
using AsterNET.IO;
using AsterNET.Util;
namespace AsterNET.FastAGI
{
public class AsteriskFastAGI
{
#region Flags
/// <summary>
/// If set to true, causes the AGIChannel to throw an exception when a status code of 511 (Channel Dead) is returned.
/// This is set to false by default to maintain backwards compatibility
/// </summary>
public bool SC511_CAUSES_EXCEPTION = false;
/// <summary>
/// If set to true, causes the AGIChannel to throw an exception when return status is 0 and reply is HANGUP.
/// This is set to false by default to maintain backwards compatibility
/// </summary>
public bool SCHANGUP_CAUSES_EXCEPTION = false;
#endregion
#region Variables
#if LOGGER
private readonly Logger logger = Logger.Instance();
#endif
private ServerSocket serverSocket;
/// <summary> The port to listen on.</summary>
private int port;
/// <summary> The address to listen on.</summary>
private readonly string address;
/// <summary>The thread pool that contains the worker threads to process incoming requests.</summary>
private ThreadPool pool;
/// <summary>
/// The number of worker threads in the thread pool. This equals the maximum number of concurrent requests this
/// AGIServer can serve.
/// </summary>
private int poolSize;
/// <summary> True while this server is shut down. </summary>
private bool stopped;
/// <summary>
/// The strategy to use for bind AGIRequests to AGIScripts that serve them.
/// </summary>
private IMappingStrategy mappingStrategy;
private Encoding socketEncoding = Encoding.ASCII;
#endregion
#region PoolSize
/// <summary>
/// Sets the number of worker threads in the thread pool.<br />
/// This equals the maximum number of concurrent requests this AGIServer can serve.<br />
/// The default pool size is 10.
/// </summary>
public int PoolSize
{
set { poolSize = value; }
}
#endregion
#region BindPort
/// <summary>
/// Sets the TCP port to listen on for new connections.<br />
/// The default bind port is 4573.
/// </summary>
public int BindPort
{
set { port = value; }
}
#endregion
#region MappingStrategy
/// <summary>
/// Sets the strategy to use for mapping AGIRequests to AGIScripts that serve them.<br />
/// The default mapping is a MappingStrategy.
/// </summary>
/// <seealso cref="MappingStrategy" />
public IMappingStrategy MappingStrategy
{
set { mappingStrategy = value; }
}
#endregion
#region SocketEncoding
public Encoding SocketEncoding
{
get { return socketEncoding; }
set { socketEncoding = value; }
}
#endregion
#region Constructor - AsteriskFastAGI()
/// <summary>
/// Creates a new AsteriskFastAGI.
/// </summary>
public AsteriskFastAGI()
{
address = Common.AGI_BIND_ADDRESS;
port = Common.AGI_BIND_PORT;
poolSize = Common.AGI_POOL_SIZE;
mappingStrategy = new ResourceMappingStrategy();
}
#endregion
#region Constructor - AsteriskFastAGI()
/// <summary>
/// Creates a new AsteriskFastAGI.
/// </summary>
public AsteriskFastAGI(string mappingStrategy)
{
address = Common.AGI_BIND_ADDRESS;
port = Common.AGI_BIND_PORT;
poolSize = Common.AGI_POOL_SIZE;
this.mappingStrategy = new ResourceMappingStrategy(mappingStrategy);
}
#endregion
#region Constructor - AsteriskFastAGI()
/// <summary>
/// Creates a new AsteriskFastAGI.
/// </summary>
public AsteriskFastAGI(IMappingStrategy mappingStrategy)
{
address = Common.AGI_BIND_ADDRESS;
port = Common.AGI_BIND_PORT;
poolSize = Common.AGI_POOL_SIZE;
this.mappingStrategy = mappingStrategy;
}
public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize)
{
address = ipaddress;
this.port = port;
this.poolSize = poolSize;
this.mappingStrategy = mappingStrategy;
}
#endregion
#region Constructor - AsteriskFastAGI(int port, int poolSize)
/// <summary>
/// Creates a new AsteriskFastAGI.
/// </summary>
/// <param name="port">The port to listen on.</param>
/// <param name="poolSize">
/// The number of worker threads in the thread pool.
/// This equals the maximum number of concurrent requests this AGIServer can serve.
/// </param>
public AsteriskFastAGI(int port, int poolSize)
{
address = Common.AGI_BIND_ADDRESS;
this.port = port;
this.poolSize = poolSize;
mappingStrategy = new ResourceMappingStrategy();
}
#endregion
#region Constructor - AsteriskFastAGI(string address, int port, int poolSize)
/// <summary>
/// Creates a new AsteriskFastAGI.
/// </summary>
/// <param name="ipaddress">The address to listen on.</param>
/// <param name="port">The port to listen on.</param>
/// <param name="poolSize">
/// The number of worker threads in the thread pool.
/// This equals the maximum number of concurrent requests this AGIServer can serve.
/// </param>
public AsteriskFastAGI(string ipaddress, int port, int poolSize)
{
address = ipaddress;
this.port = port;
this.poolSize = poolSize;
mappingStrategy = new ResourceMappingStrategy();
}
#endregion
public AsteriskFastAGI(string ipaddress = Common.AGI_BIND_ADDRESS,
int port = Common.AGI_BIND_PORT,
int poolSize = Common.AGI_POOL_SIZE,
bool sc511_CausesException = false,
bool scHangUp_CausesException = false)
{
address = ipaddress;
this.port = port;
this.poolSize = poolSize;
mappingStrategy = new ResourceMappingStrategy();
SC511_CAUSES_EXCEPTION = sc511_CausesException;
SCHANGUP_CAUSES_EXCEPTION = scHangUp_CausesException;
}
#region Start()
public void Start()
{
stopped = false;
mappingStrategy.Load();
pool = new ThreadPool("AGIServer", poolSize);
#if LOGGER
logger.Info("Thread pool started.");
#endif
try
{
var ipAddress = IPAddress.Parse(address);
serverSocket = new ServerSocket(port, ipAddress, SocketEncoding);
}
catch (IOException ex)
{
#if LOGGER
logger.Error("Unable start AGI Server: cannot to bind to " + address + ":" + port + ".", ex);
#endif
throw ex;
}
#if LOGGER
logger.Info("Listening on " + address + ":" + port + ".");
#endif
try
{
SocketConnection socket;
while ((socket = serverSocket.Accept()) != null)
{
#if LOGGER
logger.Info("Received connection.");
#endif
var connectionHandler = new AGIConnectionHandler(socket, mappingStrategy, SC511_CAUSES_EXCEPTION,
SCHANGUP_CAUSES_EXCEPTION);
pool.AddJob(connectionHandler);
}
}
catch (IOException ex)
{
if (!stopped)
{
#if LOGGER
logger.Error("IOException while waiting for connections (1).", ex);
#endif
throw ex;
}
}
finally
{
if (serverSocket != null)
{
try
{
serverSocket.Close();
}
#if LOGGER
catch (IOException ex)
{
logger.Error("IOException while waiting for connections (2).", ex);
}
#else
catch { }
#endif
}
serverSocket = null;
pool.Shutdown();
#if LOGGER
logger.Info("AGIServer shut down.");
#endif
}
}
#endregion
#region Stop()
public void Stop()
{
stopped = true;
if (serverSocket != null)
serverSocket.Close();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.BuildEngine.Shared;
using System.Xml;
using System.Text.RegularExpressions;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class ItemExpanderTest
{
/// <summary>
/// Generate a hashtable of items by type with a bunch of sample items, so that we can exercise
/// ItemExpander.ItemizeItemVector.
/// </summary>
/// <returns></returns>
/// <owner>RGoel</owner>
private Hashtable GenerateTestItems()
{
Hashtable itemGroupsByType = new Hashtable(StringComparer.OrdinalIgnoreCase);
// Set up our item group programmatically.
BuildItemGroup itemGroup = new BuildItemGroup();
itemGroupsByType["Compile"] = itemGroup;
BuildItem a = itemGroup.AddNewItem("Compile", "a.cs");
a.SetMetadata("WarningLevel", "4");
BuildItem b = itemGroup.AddNewItem("Compile", "b.cs");
b.SetMetadata("WarningLevel", "3");
BuildItemGroup itemGroup2 = new BuildItemGroup();
itemGroupsByType["Resource"] = itemGroup2;
BuildItem c = itemGroup2.AddNewItem("Resource", "c.resx");
return itemGroupsByType;
}
/// <summary>
/// Expand item vectors, basic case
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsBasic()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("@(Compile)", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("a.cs;b.cs", evaluatedString);
}
/// <summary>
/// Expand item vectors, macro expansion
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsMacroExpansion()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("@(Compile->'%(filename)')", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("a;b", evaluatedString);
}
/// <summary>
/// Expand item vectors, separator
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsSeparator()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("@(Compile, '#')", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("a.cs#b.cs", evaluatedString);
}
/// <summary>
/// Expand item vectors, multiple vectors
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsMultiple()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("...@(Compile)...@(Resource)...", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("...a.cs;b.cs...c.resx...", evaluatedString);
}
/// <summary>
/// Expand item vectors, macro expansion and separator
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsSeparatorAndMacroExpansion()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("@(Compile->'%(filename)','#')", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("a#b", evaluatedString);
}
/// <summary>
/// Expand item vectors, no vectors
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsNoVectors()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors("blah", foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("blah", evaluatedString);
}
/// <summary>
/// Expand item vectors, empty
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ExpandEmbeddedItemVectorsEmpty()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
XmlNode foo = new XmlDocument().CreateElement("Foo");
string evaluatedString = ItemExpander.ExpandEmbeddedItemVectors(String.Empty, foo, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals(String.Empty, evaluatedString);
}
/// <summary>
/// Itemize a normal item vector -- @(Compile)
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void ItemizeItemVectorNormal()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
BuildItemGroup compileItems = ItemExpander.ItemizeItemVector("@(Compile)", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("Resulting item group should have 2 items", 2, compileItems.Count);
Assertion.AssertEquals("First item should be a.cs", "a.cs", compileItems[0].FinalItemSpecEscaped);
Assertion.AssertEquals("First item WarningLevel should be 4", "4", compileItems[0].GetMetadata("WarningLevel"));
Assertion.AssertEquals("First item should be b.cs", "b.cs", compileItems[1].FinalItemSpecEscaped);
Assertion.AssertEquals("First item WarningLevel should be 3", "3", compileItems[1].GetMetadata("WarningLevel"));
}
/// <summary>
/// Attempt to itemize an expression that is an @(...) item list concatenated with another string.
/// </summary>
/// <owner>RGoel</owner>
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ItemizeItemVectorWithConcatenation()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
BuildItemGroup compileItems = ItemExpander.ItemizeItemVector("@(Compile)foo", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
}
/// <summary>
/// Attempt to itemize an expression that is in fact not an item list at all.
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void ItemizeItemVectorWithNoItemLists()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
BuildItemGroup compileItems = ItemExpander.ItemizeItemVector("foobar", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
// If the specified expression does not contain any item lists, then we expect ItemizeItemVector
// to give us back null, but not throw an exception.
Assertion.AssertNull(compileItems);
}
/// <summary>
/// Verify that an item list reference *with a separator* produces a scalar when itemized
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void ItemizeItemVectorWithSeparator()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
Match disposableMatch;
BuildItemGroup compileItems = ItemExpander.ItemizeItemVector("@(Compile, ' ')", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup, out disposableMatch);
// @(Compile, ' ') is a scalar, so we should only have one item in the resulting item group
Assertion.AssertEquals(1, compileItems.Count);
Assertion.Assert(compileItems[0].Include == "a.cs b.cs");
}
/// <summary>
/// Verify that an item list reference *with a separator* produces a scalar when itemized.
/// This test makes sure that bucketed items take precedence over the full set of items in the project.
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void ItemizeItemVectorWithSeparatorBucketed()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
Lookup lookup = LookupHelpers.CreateLookup(itemGroupsByType);
lookup.EnterScope();
lookup.PopulateWithItem(new BuildItem("Compile", "c.cs"));
lookup.PopulateWithItem(new BuildItem("Compile", "d.cs"));
Match disposableMatch;
BuildItemGroup compileItems = ItemExpander.ItemizeItemVector("@(Compile, ' ')", null, new ReadOnlyLookup(lookup), out disposableMatch);
// @(Compile, ' ') is a scalar, so we should only have one item in the resulting item group
Assertion.AssertEquals(1, compileItems.Count);
Assertion.Assert(compileItems[0].Include == "c.cs d.cs");
}
/// <summary>
/// Regression test for bug 534115. Using an item separator when there are no items in the list.
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void ItemizeItemVectorWithSeparatorWithZeroItems1()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
Match disposableMatch;
BuildItemGroup zeroItems = ItemExpander.ItemizeItemVector("@(ItemThatDoesNotExist, ' ')", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup, out disposableMatch);
Assertion.AssertEquals(0, zeroItems.Count);
}
/// <summary>
/// Regression test for bug 534115. Using an item separator when there are no items in the list.
/// </summary>
/// <owner>RGoel</owner>
[Test]
public void ItemizeItemVectorWithSeparatorWithZeroItems2()
{
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<exists Include=`foo`/>
</ItemGroup>
<Target Name=`t`>
<!-- REPRO 1 -->
<CreateProperty Value=`@(doesntexist, ' ')`>
<Output TaskParameter=`Value` ItemName=`zz`/>
</CreateProperty>
<!-- REPRO 2-->
<CreateProperty Value=`@(exists->'', '!')`>
<Output TaskParameter=`Value` ItemName=`zz`/>
</CreateProperty>
<Message Text=`zz=[@(zz)]`/>
</Target>
</Project>
");
logger.AssertLogContains("zz=[]");
}
// Valid names. The goal here is that an item name is recognized iff it is valid
// in a project. (That is, iff it matches "[A-Za-z_][A-Za-z_0-9\-]*")
private string[] validItemVectors = new string[]
{
"@( a1234567890_-AXZaxz )",
"@(z1234567890_-AZaz)",
"@(A1234567890_-AZaz)",
"@(Z1234567890_-AZaz)",
"@(x1234567890_-AZaz)",
"@(_X)",
"@(a)",
"@(_)"
};
// Invalid item names
private string[] invalidItemVectors = new string[]
{
"@(Com pile)",
"@(Com.pile)",
"@(Com%pile)",
"@(Com:pile)",
"@(.Compile)",
"@(%Compile)",
"@(:Compile)",
"@(-Compile)",
"@(1Compile)",
"@()",
"@( )"
};
private string[] validMetadataExpressions = new string[]
{
"%( a1234567890_-AXZaxz.a1234567890_-AXZaxz )",
"%(z1234567890_-AZaz.z1234567890_-AZaz)",
"%(A1234567890_-AZaz.A1234567890_-AZaz)",
"%(Z1234567890_-AZaz.Z1234567890_-AZaz)",
"%(x1234567890_-AZaz.x1234567890_-AZaz)",
"%(abc._X)",
"%(a12.a)",
"%(x._)",
"%(a1234567890_-AXZaxz)",
"%(z1234567890_-AZaz)",
"%(A1234567890_-AZaz)",
"%(Z1234567890_-AZaz)",
"%(x1234567890_-AZaz)",
"%(_X)",
"%(a)",
"%(_)"
};
private string[] invalidMetadataExpressions = new string[]
{
"%(Com pile.Com pile)",
"%(Com.pile.Com.pile)",
"%(Com%pile.Com%pile)",
"%(Com:pile.Com:pile)",
"%(.Compile)",
"%(Compile.)",
"%(%Compile.%Compile)",
"%(:Compile.:Compile)",
"%(-Compile.-Compile)",
"%(1Compile.1Compile)",
"%()",
"%(.)",
"%( )",
"%(Com pile)",
"%(Com%pile)",
"%(Com:pile)",
"%(.Compile)",
"%(%Compile)",
"%(:Compile)",
"%(-Compile)",
"%(1Compile)"
};
private string[] validItemVectorsWithTransforms = new string[]
{
"@(z1234567890_-AXZaxz -> '%(a1234567890_-AXZaxz).%(adfas)' )",
"@(a1234567890_-AZaz->'z1234567890_-AZaz')",
"@(A1234567890_-AZaz ->'A1234567890_-AZaz')",
"@(Z1234567890_-AZaz -> 'Z1234567890_-AZaz')",
"@(x1234567890_-AZaz->'x1234567890_-AZaz')",
"@(_X->'_X')",
"@(a->'a')",
"@(_->'@#$%$%^&*&*)')"
};
private string[] validItemVectorsWithSeparators = new string[]
{
"@(a1234567890_-AXZaxz , 'z123%%4567890_-AXZaxz' )",
"@(z1234567890_-AZaz,'a1234567890_-AZaz')",
"@(A1234567890_-AZaz,'!@#$%^&*)(_+'))",
"@(_X,'X')",
"@(a , 'a')",
"@(_,'@#$%$%^&*&*)')"
};
private string[] validItemVectorsWithTransformsAndSeparators = new string[]
{
"@(a1234567890_-AXZaxz -> 'a1234567890_-AXZaxz' , 'z1234567890_-AXZaxz' )",
"@(z1234567890_-AZaz->'z1234567890_-AZaz','a1234567890_-AZaz')",
"@(A1234567890_-AZaz ->'A1234567890_-AZaz' , '!@#$%^&*)(_+'))",
"@(_X->'_X','X')",
"@(a->'a' , 'a')",
"@(_->'@#$%$%^&*&*)','@#$%$%^&*&*)')"
};
private string[] invalidItemVectorsWithTransforms = new string[]
{
"@(z123456.7890_-AXZaxz -> '%(a1234567890_-AXZaxz).%(adfas)' )",
"@(a1234:567890_-AZaz->'z1234567890_-AZaz')",
"@(.A1234567890_-AZaz ->'A1234567890_-AZaz')",
"@(:Z1234567890_-AZaz -> 'Z1234567890_-AZaz')",
"@(x123 4567890_-AZaz->'x1234567890_-AZaz')",
"@(-x->'_X')",
"@(1->'a')",
"@(1x->'@#$%$%^&*&*)')"
};
/// <summary>
/// Ensure that valid item list expressions are matched.
/// This tests "itemVectorPattern".
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ItemizeItemVectorsWithValidNames()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
foreach (string candidate in validItemVectors)
{
Assertion.AssertNotNull(candidate, ItemExpander.ItemizeItemVector(candidate, null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup));
}
foreach (string candidate in validItemVectorsWithTransforms)
{
Assertion.AssertNotNull(candidate, ItemExpander.ItemizeItemVector(candidate, null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup));
}
}
/// <summary>
/// Ensure that leading sand trailing pace is ignored for the item name
/// This tests "itemVectorPattern".
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ItemizeItemVectorsWithLeadingAndTrailingSpaces()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
// Spaces around are fine, but it's ignored for the item name
BuildItemGroup items = ItemExpander.ItemizeItemVector("@( Compile )", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals("Resulting item group should have 2 items", 2, items.Count);
}
/// <summary>
/// Ensure that invalid item list expressions are not matched.
/// This tests "itemVectorPattern".
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ItemizeItemVectorsWithInvalidNames()
{
Hashtable itemGroupsByType = this.GenerateTestItems();
// First, verify that a valid but simply non-existent item list returns an empty BuildItemGroup,
// not just null.
BuildItemGroup control = ItemExpander.ItemizeItemVector("@(nonexistent)", null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup);
Assertion.AssertEquals(0, control.Count);
foreach (string candidate in invalidItemVectors)
{
Assertion.AssertNull(candidate, ItemExpander.ItemizeItemVector(candidate, null, LookupHelpers.CreateLookup(itemGroupsByType).ReadOnlyLookup));
}
}
/// <summary>
/// This tests "listOfItemVectorsWithoutSeparatorsPattern"
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ListOfItemVectorsWithoutSeparatorsPattern()
{
// Positive cases
foreach (string candidate in validItemVectorsWithTransforms)
{
Assertion.Assert(candidate, ItemExpander.listOfItemVectorsWithoutSeparatorsPattern.IsMatch(candidate));
}
// Negative cases
foreach (string candidate in invalidItemVectors)
{
Assertion.Assert(candidate, !ItemExpander.listOfItemVectorsWithoutSeparatorsPattern.IsMatch(candidate));
}
}
/// <summary>
/// This tests "itemVectorPattern"
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ItemVectorPattern()
{
// Positive cases
foreach (string candidate in validItemVectorsWithTransforms)
{
Assertion.Assert(candidate, ItemExpander.itemVectorPattern.IsMatch(candidate));
}
foreach (string candidate in validItemVectorsWithSeparators)
{
Assertion.Assert(candidate, ItemExpander.itemVectorPattern.IsMatch(candidate));
}
foreach (string candidate in validItemVectorsWithTransformsAndSeparators)
{
Assertion.Assert(candidate, ItemExpander.itemVectorPattern.IsMatch(candidate));
}
}
/// <summary>
/// This tests "itemMetadataPattern"
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ItemMetadataPattern()
{
// Positive cases
foreach (string candidate in validMetadataExpressions)
{
Assertion.Assert(candidate, ItemExpander.itemMetadataPattern.IsMatch(candidate));
}
// Negative cases
foreach (string candidate in invalidMetadataExpressions)
{
Assertion.Assert(candidate, !ItemExpander.itemMetadataPattern.IsMatch(candidate));
}
}
// ProjectWriter has regular expressions that must match these same expressions. Test them here,
// too, so we can re-use the same sample expressions.
/// <summary>
/// ItemVectorTransformPattern should match any item expressions containing transforms.
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ProjectWriterItemVectorTransformPattern()
{
// Positive cases
foreach (string candidate in validItemVectorsWithTransforms)
{
Assertion.Assert(candidate, ProjectWriter.itemVectorTransformPattern.IsMatch(candidate));
}
foreach (string candidate in validItemVectorsWithTransformsAndSeparators)
{
Assertion.Assert(candidate, ProjectWriter.itemVectorTransformPattern.IsMatch(candidate));
}
}
/// <summary>
/// itemVectorTransformRawPattern should match any item expressions containing transforms.
/// </summary>
/// <owner>danmose</owner>
[Test]
public void ProjectWriterItemVectorTransformRawPattern()
{
// Positive cases
foreach (string candidate in validItemVectorsWithTransforms)
{
Assertion.Assert(candidate, ProjectWriter.itemVectorTransformRawPattern.IsMatch(candidate));
}
foreach (string candidate in validItemVectorsWithTransformsAndSeparators)
{
Assertion.Assert(candidate, ProjectWriter.itemVectorTransformRawPattern.IsMatch(candidate));
}
// Negative cases
foreach (string candidate in invalidItemVectorsWithTransforms)
{
Assertion.Assert(candidate, !ProjectWriter.itemVectorTransformRawPattern.IsMatch(candidate));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using global::System;
using global::System.Reflection;
using global::System.Diagnostics;
using global::System.Collections.Generic;
using global::System.Runtime.CompilerServices;
using global::System.Reflection.Runtime.General;
using global::System.Reflection.Runtime.Types;
using global::System.Reflection.Runtime.MethodInfos;
using global::System.Reflection.Runtime.FieldInfos;
using global::System.Reflection.Runtime.PropertyInfos;
using global::System.Reflection.Runtime.EventInfos;
using global::Internal.LowLevelLinq;
using global::Internal.Reflection.Core;
using global::Internal.Reflection.Core.Execution;
using global::Internal.Reflection.Core.NonPortable;
using global::Internal.Reflection.Extensibility;
using global::Internal.Reflection.Tracing;
using global::Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.TypeInfos
{
//
// Abstract base class for all TypeInfo's implemented by the runtime.
//
// This base class performs several services:
//
// - Provides default implementations that delegate to AsType() when possible and
// returns the "common" error result for narrowly applicable properties (such as those
// that apply only to generic parameters.)
//
// - Inverts the DeclaredMembers/DeclaredX relationship (DeclaredMembers is auto-implemented, others
// are overriden as abstract. This ordering makes more sense when reading from metadata.)
//
// - Overrides many "NotImplemented" members in TypeInfo with abstracts so failure to implement
// shows up as build error.
//
[DebuggerDisplay("{_debugName}")]
internal abstract partial class RuntimeTypeInfo : ExtensibleTypeInfo, ITraceableTypeMember
{
protected RuntimeTypeInfo()
{
}
public sealed override String AssemblyQualifiedName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_AssemblyQualifiedName(this);
#endif
return AsType().AssemblyQualifiedName;
}
}
public sealed override Type AsType()
{
return this.RuntimeType;
}
public sealed override bool IsCOMObject
{
get
{
return ReflectionCoreExecution.ExecutionEnvironment.IsCOMObject(this.RuntimeType);
}
}
public sealed override Type BaseType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_BaseType(this);
#endif
// If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata.
RuntimeTypeHandle typeHandle;
if (this.RuntimeType.InternalTryGetTypeHandle(out typeHandle))
{
RuntimeTypeHandle baseTypeHandle;
if (ReflectionCoreExecution.ExecutionEnvironment.TryGetBaseType(typeHandle, out baseTypeHandle))
return Type.GetTypeFromHandle(baseTypeHandle);
}
Type baseType = BaseTypeWithoutTheGenericParameterQuirk;
if (baseType != null && baseType.IsGenericParameter)
{
// Desktop quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object
// unless that other generic parameter has a "class" constraint.
GenericParameterAttributes genericParameterAttributes = baseType.GetTypeInfo().GenericParameterAttributes;
if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint))
baseType = this.ReflectionDomain.FoundationTypes.SystemObject;
}
return baseType;
}
}
public sealed override bool ContainsGenericParameters
{
get
{
return this.RuntimeType.InternalIsOpen;
}
}
//
// Left unsealed so that RuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo and RuntimeGenericParameterTypeInfo can override.
//
public override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_CustomAttributes(this);
#endif
Debug.Assert(IsArray || IsByRef || IsPointer);
return Empty<CustomAttributeData>.Enumerable;
}
}
public sealed override IEnumerable<ConstructorInfo> DeclaredConstructors
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredConstructors(this);
#endif
return GetDeclaredConstructorsInternal(this.AnchoringTypeDefinitionForDeclaredMembers);
}
}
public sealed override IEnumerable<EventInfo> DeclaredEvents
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredEvents(this);
#endif
return GetDeclaredEventsInternal(this.AnchoringTypeDefinitionForDeclaredMembers, null);
}
}
public sealed override IEnumerable<FieldInfo> DeclaredFields
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredFields(this);
#endif
return GetDeclaredFieldsInternal(this.AnchoringTypeDefinitionForDeclaredMembers, null);
}
}
public sealed override IEnumerable<MemberInfo> DeclaredMembers
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredMembers(this);
#endif
return GetDeclaredMembersInternal(
this.DeclaredMethods,
this.DeclaredConstructors,
this.DeclaredProperties,
this.DeclaredEvents,
this.DeclaredFields,
this.DeclaredNestedTypes);
}
}
public sealed override IEnumerable<MethodInfo> DeclaredMethods
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredMethods(this);
#endif
return GetDeclaredMethodsInternal(this.AnchoringTypeDefinitionForDeclaredMembers, null);
}
}
//
// Left unsealed as named types must override.
//
public override IEnumerable<TypeInfo> DeclaredNestedTypes
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredNestedTypes(this);
#endif
Debug.Assert(!(this is RuntimeNamedTypeInfo));
return Empty<TypeInfo>.Enumerable;
}
}
public sealed override IEnumerable<PropertyInfo> DeclaredProperties
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_DeclaredProperties(this);
#endif
return GetDeclaredPropertiesInternal(this.AnchoringTypeDefinitionForDeclaredMembers, null);
}
}
//
// Left unsealed as generic parameter types must override.
//
public override MethodBase DeclaringMethod
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
public abstract override bool Equals(Object obj);
public abstract override int GetHashCode();
public sealed override String FullName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_FullName(this);
#endif
return AsType().FullName;
}
}
//
// Left unsealed as generic parameter types must override.
//
public override GenericParameterAttributes GenericParameterAttributes
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
public sealed override int GenericParameterPosition
{
get
{
return AsType().GenericParameterPosition;
}
}
public sealed override Type[] GenericTypeArguments
{
get
{
return AsType().GenericTypeArguments;
}
}
public sealed override EventInfo GetDeclaredEvent(String name)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_GetDeclaredEvent(this, name);
#endif
if (name == null)
throw new ArgumentNullException("name");
TypeInfoCachedData cachedData = this.TypeInfoCachedData;
return cachedData.GetDeclaredEvent(name);
}
public sealed override FieldInfo GetDeclaredField(String name)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_GetDeclaredField(this, name);
#endif
if (name == null)
throw new ArgumentNullException("name");
TypeInfoCachedData cachedData = this.TypeInfoCachedData;
return cachedData.GetDeclaredField(name);
}
public sealed override MethodInfo GetDeclaredMethod(String name)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_GetDeclaredMethod(this, name);
#endif
if (name == null)
throw new ArgumentNullException("name");
TypeInfoCachedData cachedData = this.TypeInfoCachedData;
return cachedData.GetDeclaredMethod(name);
}
public sealed override PropertyInfo GetDeclaredProperty(String name)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_GetDeclaredProperty(this, name);
#endif
if (name == null)
throw new ArgumentNullException("name");
TypeInfoCachedData cachedData = this.TypeInfoCachedData;
return cachedData.GetDeclaredProperty(name);
}
//
// Implements the correct GUID behavior for all "constructed" types (i.e. returning an all-zero GUID.) Left unsealed
// so that RuntimeNamedTypeInfo can override.
//
public override Guid GUID
{
get
{
return Guid.Empty;
}
}
public sealed override IEnumerable<Type> ImplementedInterfaces
{
get
{
LowLevelListWithIList<Type> result = new LowLevelListWithIList<Type>();
bool done = false;
// If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata.
RuntimeTypeHandle typeHandle;
if (this.RuntimeType.InternalTryGetTypeHandle(out typeHandle))
{
IEnumerable<RuntimeTypeHandle> implementedInterfaces = ReflectionCoreExecution.ExecutionEnvironment.TryGetImplementedInterfaces(typeHandle);
if (implementedInterfaces != null)
{
done = true;
foreach (RuntimeTypeHandle th in implementedInterfaces)
{
result.Add(Type.GetTypeFromHandle(th));
}
}
}
if (!done)
{
TypeContext typeContext = this.TypeContext;
Type baseType = this.BaseTypeWithoutTheGenericParameterQuirk;
if (baseType != null)
result.AddRange(baseType.GetTypeInfo().ImplementedInterfaces);
ReflectionDomain reflectionDomain = this.ReflectionDomain;
foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces)
{
Type ifc = reflectionDomain.Resolve(directlyImplementedInterface.Reader, directlyImplementedInterface.Handle, typeContext);
if (result.Contains(ifc))
continue;
result.Add(ifc);
foreach (Type indirectIfc in ifc.GetTypeInfo().ImplementedInterfaces)
{
if (result.Contains(indirectIfc))
continue;
result.Add(indirectIfc);
}
}
}
return result.AsNothingButIEnumerable();
}
}
public sealed override bool IsAssignableFrom(TypeInfo typeInfo)
{
RuntimeTypeInfo toTypeInfo = this;
RuntimeTypeInfo fromTypeInfo = typeInfo as RuntimeTypeInfo;
if (fromTypeInfo == null)
return false; // Desktop compat: If typeInfo is null, or implemented by a different Reflection implementation, return "false."
if (toTypeInfo.ReflectionDomain != fromTypeInfo.ReflectionDomain)
return false;
if (toTypeInfo.Equals(fromTypeInfo))
return true;
RuntimeTypeHandle toTypeHandle = default(RuntimeTypeHandle);
RuntimeTypeHandle fromTypeHandle = default(RuntimeTypeHandle);
bool haveTypeHandles = toTypeInfo.RuntimeType.InternalTryGetTypeHandle(out toTypeHandle) && fromTypeInfo.RuntimeType.InternalTryGetTypeHandle(out fromTypeHandle);
if (haveTypeHandles)
{
// If both types have type handles, let MRT handle this. It's not dependent on metadata.
if (ReflectionCoreExecution.ExecutionEnvironment.IsAssignableFrom(toTypeHandle, fromTypeHandle))
return true;
// Runtime IsAssignableFrom does not handle casts from generic type definitions: always returns false. For those, we fall through to the
// managed implementation. For everyone else, return "false".
//
// Runtime IsAssignableFrom does not handle pointer -> UIntPtr cast.
if (!(fromTypeInfo.IsGenericTypeDefinition || fromTypeInfo.IsPointer))
return false;
}
// If we got here, the types are open, or reduced away, or otherwise lacking in type handles. Perform the IsAssignability check in managed code.
return Assignability.IsAssignableFrom(this, typeInfo, fromTypeInfo.ReflectionDomain.FoundationTypes);
}
public sealed override bool IsEnum
{
get
{
return 0 != (Classification & TypeClassification.IsEnum);
}
}
public sealed override bool IsGenericParameter
{
get
{
return AsType().IsGenericParameter;
}
}
//
// Left unsealed as generic type definitions and constructed generic types must override.
//
public override bool IsGenericType
{
get
{
return false;
}
}
//
// Left unsealed as generic type definitions must override.
//
public override bool IsGenericTypeDefinition
{
get
{
return false;
}
}
public sealed override bool IsPrimitive
{
get
{
return 0 != (Classification & TypeClassification.IsPrimitive);
}
}
public sealed override bool IsSerializable
{
get
{
return 0 != (this.Attributes & TypeAttributes.Serializable);
}
}
public sealed override bool IsValueType
{
get
{
return 0 != (Classification & TypeClassification.IsValueType);
}
}
public sealed override Module Module
{
get
{
return Assembly.ManifestModule;
}
}
public sealed override String Namespace
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_Namespace(this);
#endif
return AsType().Namespace;
}
}
public sealed override Type[] GenericTypeParameters
{
get
{
RuntimeType[] genericTypeParameters = RuntimeGenericTypeParameters;
if (genericTypeParameters.Length == 0)
return Array.Empty<Type>();
Type[] result = new Type[genericTypeParameters.Length];
for (int i = 0; i < genericTypeParameters.Length; i++)
result[i] = genericTypeParameters[i];
return result;
}
}
public sealed override int GetArrayRank()
{
return AsType().GetArrayRank();
}
public sealed override Type GetElementType()
{
return AsType().GetElementType();
}
//
// Left unsealed as generic parameter types must override.
//
public override Type[] GetGenericParameterConstraints()
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
public sealed override Type GetGenericTypeDefinition()
{
return AsType().GetGenericTypeDefinition();
}
public sealed override Type MakeArrayType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeArrayType(this);
#endif
return AsType().MakeArrayType();
}
public sealed override Type MakeArrayType(int rank)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeArrayType(this, rank);
#endif
return AsType().MakeArrayType(rank);
}
public sealed override Type MakeByRefType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeByRefType(this);
#endif
return AsType().MakeByRefType();
}
public sealed override Type MakeGenericType(params Type[] typeArguments)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeGenericType(this, typeArguments);
#endif
return AsType().MakeGenericType(typeArguments);
}
public sealed override Type MakePointerType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakePointerType(this);
#endif
return AsType().MakePointerType();
}
public sealed override Type DeclaringType
{
get
{
return this.InternalDeclaringType;
}
}
public sealed override String Name
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_Name(this);
#endif
return this.InternalName;
}
}
public sealed override String ToString()
{
return AsType().ToString();
}
String ITraceableTypeMember.MemberName
{
get
{
return this.InternalName;
}
}
Type ITraceableTypeMember.ContainingType
{
get
{
return this.InternalDeclaringType;
}
}
//
// The non-public version of AsType().
//
internal abstract RuntimeType RuntimeType { get; }
internal ReflectionDomain ReflectionDomain
{
get
{
return ReflectionCoreExecution.ExecutionDomain; //@todo: User Reflection Domains not yet supported.
}
}
//
// Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties.
// The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this"
// and substituting the value of this.TypeContext into any generic parameters.
//
// Default implementation returns null which causes the Declared*** properties to return no members.
//
// Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments
// (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does
// - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.)
//
// Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return
// a base class and interface list based on its constraints.
//
internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers
{
get
{
return null;
}
}
//
// Return all declared events whose name matches "optionalNameFilter". If optionalNameFilter is null, return them all.
//
internal IEnumerable<RuntimeEventInfo> GetDeclaredEventsInternal(RuntimeNamedTypeInfo definingType, String optionalNameFilter)
{
if (definingType != null)
{
// We require the caller to pass a value that we could calculate ourselves because we're an iterator and we
// don't want any MissingMetadataException that AnchoringType throws to be deferred.
Debug.Assert(definingType.Equals(this.AnchoringTypeDefinitionForDeclaredMembers));
MetadataReader reader = definingType.Reader;
foreach (EventHandle eventHandle in definingType.DeclaredEventHandles)
{
if (optionalNameFilter == null || eventHandle.GetEvent(reader).Name.StringEquals(optionalNameFilter, reader))
yield return RuntimeEventInfo.GetRuntimeEventInfo(eventHandle, definingType, this);
}
}
}
//
// Return all declared fields whose name matches "optionalNameFilter". If optionalNameFilter is null, return them all.
//
internal IEnumerable<RuntimeFieldInfo> GetDeclaredFieldsInternal(RuntimeNamedTypeInfo definingType, String optionalNameFilter)
{
if (definingType != null)
{
// We require the caller to pass a value that we could calculate ourselves because we're an iterator and we
// don't want any MissingMetadataException that AnchoringType throws to be deferred.
Debug.Assert(definingType.Equals(this.AnchoringTypeDefinitionForDeclaredMembers));
MetadataReader reader = definingType.Reader;
foreach (FieldHandle fieldHandle in definingType.DeclaredFieldHandles)
{
if (optionalNameFilter == null || fieldHandle.GetField(reader).Name.StringEquals(optionalNameFilter, reader))
yield return RuntimeFieldInfo.GetRuntimeFieldInfo(fieldHandle, definingType, this);
}
}
}
//
// Return all declared methods whose name matches "optionalNameFilter". If optionalNameFilter is null, return them all.
//
internal IEnumerable<RuntimeMethodInfo> GetDeclaredMethodsInternal(RuntimeNamedTypeInfo definingType, String optionalNameFilter)
{
if (definingType != null)
{
// We require the caller to pass a value that we could calculate ourselves because we're an iterator and we
// don't want any MissingMetadataException that AnchoringType throws to be deferred.
Debug.Assert(definingType.Equals(this.AnchoringTypeDefinitionForDeclaredMembers));
MetadataReader reader = definingType.Reader;
foreach (MethodHandle methodHandle in definingType.DeclaredMethodAndConstructorHandles)
{
Method method = methodHandle.GetMethod(reader);
if ((optionalNameFilter != null) && !method.Name.StringEquals(optionalNameFilter, reader))
continue;
if (MetadataReaderExtensions.IsConstructor(ref method, reader))
continue;
yield return RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodHandle, definingType, this);
}
}
foreach (RuntimeMethodInfo syntheticMethod in SyntheticMethods)
{
if (optionalNameFilter == null || optionalNameFilter == syntheticMethod.Name)
{
yield return syntheticMethod;
}
}
}
//
// Return all declared properties whose name matches "optionalNameFilter". If optionalNameFilter is null, return them all.
//
internal IEnumerable<RuntimePropertyInfo> GetDeclaredPropertiesInternal(RuntimeNamedTypeInfo definingType, String optionalNameFilter)
{
if (definingType != null)
{
// We require the caller to pass a value that we could calculate ourselves because we're an iterator and we
// don't want any MissingMetadataException that AnchoringType throws to be deferred.
Debug.Assert(definingType.Equals(this.AnchoringTypeDefinitionForDeclaredMembers));
MetadataReader reader = definingType.Reader;
foreach (PropertyHandle propertyHandle in definingType.DeclaredPropertyHandles)
{
if (optionalNameFilter == null || propertyHandle.GetProperty(reader).Name.StringEquals(optionalNameFilter, reader))
yield return RuntimePropertyInfo.GetRuntimePropertyInfo(propertyHandle, definingType, this);
}
}
}
//
// The non-public version of TypeInfo.GenericTypeParameters (does not array-copy.)
//
internal virtual RuntimeType[] RuntimeGenericTypeParameters
{
get
{
Debug.Assert(!(this is RuntimeNamedTypeInfo));
return Array.Empty<RuntimeType>();
}
}
//
// Normally returns empty: Overridden by array types to return constructors.
//
internal virtual IEnumerable<RuntimeConstructorInfo> SyntheticConstructors
{
get
{
return Empty<RuntimeConstructorInfo>.Enumerable;
}
}
//
// Normally returns empty: Overridden by array types to return the "Get" and "Set" methods.
//
internal virtual IEnumerable<RuntimeMethodInfo> SyntheticMethods
{
get
{
return Empty<RuntimeMethodInfo>.Enumerable;
}
}
//
// Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null.
//
internal virtual QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType
{
get
{
return QTypeDefRefOrSpec.Null;
}
}
//
// Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and
// insertion of the TypeContext.
//
internal virtual QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces
{
get
{
return Array.Empty<QTypeDefRefOrSpec>();
}
}
//
// Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces.
//
internal virtual TypeContext TypeContext
{
get
{
return new TypeContext(null, null);
}
}
//
// Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString()
// in the constructor causes some serious recursion issues.
//
internal void EstablishDebugName()
{
bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled;
#if DEBUG
populateDebugNames = true;
#endif
if (!populateDebugNames)
return;
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
String debugName;
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace.
else
#endif
debugName = this.ToString();
if (debugName == null)
debugName = "";
_debugName = debugName;
}
return;
}
private String InternalName
{
get
{
return this.RuntimeType.Name;
}
}
private Type InternalDeclaringType
{
get
{
return this.RuntimeType.DeclaringType;
}
}
//
// This internal method implements BaseType without the following desktop quirk:
//
// class Foo<X,Y>
// where X:Y
// where Y:MyReferenceClass
//
// The desktop reports "X"'s base type as "System.Object" rather than "Y", even though it does
// report any interfaces that are in MyReferenceClass's interface list.
//
// This seriously messes up the implementation of RuntimeTypeInfo.ImplementedInterfaces which assumes
// that it can recover the transitive interface closure by combining the directly mentioned interfaces and
// the BaseType's own interface closure.
//
// To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here
// and make the special-case adjustment in the public version of BaseType.
//
private RuntimeType BaseTypeWithoutTheGenericParameterQuirk
{
get
{
QTypeDefRefOrSpec baseTypeDefRefOrSpec = TypeRefDefOrSpecForBaseType;
MetadataReader reader = baseTypeDefRefOrSpec.Reader;
RuntimeType baseType = null;
ReflectionDomain reflectionDomain = this.ReflectionDomain;
if (reader != null)
{
Handle typeDefRefOrSpec = baseTypeDefRefOrSpec.Handle;
baseType = reflectionDomain.Resolve(reader, typeDefRefOrSpec, this.TypeContext);
}
return baseType;
}
}
//
// Returns a latched set of flags indicating the value of IsValueType, IsEnum, etc.
//
private TypeClassification Classification
{
get
{
if (_lazyClassification == 0)
{
TypeClassification classification = TypeClassification.Computed;
Type baseType = this.BaseType;
if (baseType != null)
{
FoundationTypes foundationTypes = this.ReflectionDomain.FoundationTypes;
Type enumType = foundationTypes.SystemEnum;
Type valueType = foundationTypes.SystemValueType;
if (baseType.Equals(enumType))
classification |= TypeClassification.IsEnum | TypeClassification.IsValueType;
if (baseType.Equals(valueType) && !(this.AsType().Equals(enumType)))
{
classification |= TypeClassification.IsValueType;
Type thisType = this.AsType();
foreach (Type primitiveType in this.ReflectionDomain.PrimitiveTypes)
{
if (thisType.Equals(primitiveType))
{
classification |= TypeClassification.IsPrimitive;
break;
}
}
}
}
_lazyClassification = classification;
}
return _lazyClassification;
}
}
[Flags]
private enum TypeClassification
{
Computed = 0x00000001, // Always set (to indicate that the lazy evaluation has occurred)
IsValueType = 0x00000002,
IsEnum = 0x00000004,
IsPrimitive = 0x00000008,
}
//
// Return all declared members. This may look like a silly code sequence to wrap inside a helper but we want to separate the iterator from
// the actual calls to get the sub-enumerations as we want any MissingMetadataException thrown by those
// calls to happen at the time DeclaredMembers is called.
//
private IEnumerable<MemberInfo> GetDeclaredMembersInternal(
IEnumerable<MethodInfo> methods,
IEnumerable<ConstructorInfo> constructors,
IEnumerable<PropertyInfo> properties,
IEnumerable<EventInfo> events,
IEnumerable<FieldInfo> fields,
IEnumerable<TypeInfo> nestedTypes
)
{
foreach (MemberInfo member in methods)
yield return member;
foreach (MemberInfo member in constructors)
yield return member;
foreach (MemberInfo member in properties)
yield return member;
foreach (MemberInfo member in events)
yield return member;
foreach (MemberInfo member in fields)
yield return member;
foreach (MemberInfo member in nestedTypes)
yield return member;
}
//
// Return all declared constructors.
//
private IEnumerable<RuntimeConstructorInfo> GetDeclaredConstructorsInternal(RuntimeNamedTypeInfo definingType)
{
if (definingType != null)
{
// We require the caller to pass a value that we could calculate ourselves because we're an iterator and we
// don't want any MissingMetadataException that AnchoringType throws to be deferred.
Debug.Assert(definingType.Equals(this.AnchoringTypeDefinitionForDeclaredMembers));
RuntimeTypeInfo contextType = this;
foreach (MethodHandle methodHandle in definingType.DeclaredConstructorHandles)
{
yield return RuntimePlainConstructorInfo.GetRuntimePlainConstructorInfo(methodHandle, definingType, contextType);
}
}
foreach (RuntimeConstructorInfo syntheticConstructor in SyntheticConstructors)
{
yield return syntheticConstructor;
}
}
private volatile TypeClassification _lazyClassification;
private TypeInfoCachedData TypeInfoCachedData
{
get
{
TypeInfoCachedData cachedData = _lazyTypeInfoCachedData;
if (cachedData != null)
return cachedData;
_lazyTypeInfoCachedData = cachedData = new TypeInfoCachedData(this);
return cachedData;
}
}
private volatile TypeInfoCachedData _lazyTypeInfoCachedData;
private String _debugName;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TripsServer.Areas.HelpPage.ModelDescriptions;
using TripsServer.Areas.HelpPage.Models;
namespace TripsServer.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Reflection;
//using PCSAssemblyLoader;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using PCSUtils;
using Utils = PCSComUtils.DataAccess.Utils;
using PCSUtils.Utils;
using C1.Win.C1Preview;
namespace InventoryDetailByProductReport
{
/// <summary>
/// </summary>
[Serializable]
public class InventoryDetailByProductReport : MarshalByRefObject, IDynamicReport
{
#region IDynamicReport Implementation
private string mConnectionString;
private ReportBuilder mReportBuilder = new ReportBuilder();
private C1PrintPreviewControl mReportViewer;
private object mResult;
private bool mUseReportViewerRenderEngine = false;
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport
/// or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get
{
return mUseReportViewerRenderEngine;
}
set
{
mUseReportViewerRenderEngine = value;
}
}
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get
{
return mstrReportDefinitionFolder;
}
set
{
mstrReportDefinitionFolder = value;
}
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get
{
return mstrReportLayoutFile;
}
set
{
mstrReportLayoutFile = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="pstrMethod"></param>
/// <param name="pobjParameters"></param>
/// <returns></returns>
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
#endregion
PCSComUtils.Common.BO.UtilsBO objUtilBO = new PCSComUtils.Common.BO.UtilsBO();
const string TABLE_NAME = "InventoryDetailByProductReport";
public InventoryDetailByProductReport()
{
}
/// <summary>
/// Thachnn: 28/10/2005
/// Preview the report for this form
/// Using the "InventoryDetailByProductReport.xml" layout
/// </summary>
/// <history>Thachnn: 29/12/2005: Add parameter display to the report. Change USECASE.</history>
/// <param name="sender"></param>
/// <param name="e"></param>
public DataTable ExecuteReport(string pstrCCNID, string pstrMasterLocationID, string pstrLocationID,string pstrBinID , string pstrCategoryID, string pstrParameterModel)
{
#region Constants
string mstrReportDefFolder = mstrReportDefinitionFolder;
const string REPORT_LAYOUT_FILE = "InventoryDetailByProductReport.xml";
const string REPORT_NAME = "Inventory Detail By Product";
const string PAGE = "Page";
const string HEADER = "Header";
const string REPORTFLD_TITLE = "fldTitle";
const string REPORTFLD_COMPANY = "fldCompany";
const string REPORTFLD_ADDRESS = "fldAddress";
const string REPORTFLD_TEL = "fldTel";
const string REPORTFLD_FAX = "fldFax";
const string REPORTFLD_DATETIME = "fldDateTime";
#endregion
#region GETTING THE PARAMETER
PCSComUtils.Common.BO.UtilsBO boUtil = new PCSComUtils.Common.BO.UtilsBO();
PCSComUtils.Framework.ReportFrame.BO.C1PrintPreviewDialogBO objBO = new PCSComUtils.Framework.ReportFrame.BO.C1PrintPreviewDialogBO();
string strCCN = boUtil.GetCCNCodeFromID(int.Parse(pstrCCNID));
string strMasterLocation = objBO.GetMasterLocationCodeFromID(int.Parse(pstrMasterLocationID)) + ": " + objBO.GetMasterLocationNameFromID(int.Parse(pstrMasterLocationID));
string strLocation = string.Empty;
try
{
strLocation = objBO.GetLocationCodeFromID(int.Parse(pstrLocationID));
}
catch{}
string strBin = string.Empty;
try
{
strBin = objBO.GetBinCodeFromID(int.Parse(pstrBinID));
}
catch{}
string strCategory = string.Empty;
try
{
strCategory = objBO.GetCategoryCodeFromID(pstrCategoryID);
}
catch{}
#endregion
float fActualPageSize = 9000f;
#region Build dtbResult DataTable
DataTable dtbResult;
try
{
dtbResult = GetInventoryDetailByProductData(pstrCCNID, pstrMasterLocationID, pstrLocationID, pstrBinID, pstrCategoryID, pstrParameterModel);
}
catch
{
dtbResult = new DataTable();
}
#endregion
ReportBuilder objRB;
objRB = new ReportBuilder();
objRB.ReportName = REPORT_NAME;
objRB.SourceDataTable = dtbResult;
#region INIT REPORT BUIDER OBJECT
try
{
objRB.ReportDefinitionFolder = mstrReportDefinitionFolder;
objRB.ReportLayoutFile = REPORT_LAYOUT_FILE;
if(objRB.AnalyseLayoutFile() == false)
{
// PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
return new DataTable();
}
//objRB.UseLayoutFile = objRB.AnalyseLayoutFile(); // use layout file if any , auto drawing if not found layout file
objRB.UseLayoutFile = true; // always use layout file
}
catch
{
objRB.UseLayoutFile = false;
// PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND,MessageBoxIcon.Error);
}
C1.C1Report.Layout objLayout = objRB.Report.Layout;
fActualPageSize = objLayout.PageSize.Width - (float)objLayout.MarginLeft - (float)objLayout.MarginRight;
#endregion
objRB.MakeDataTableForRender();
//grid.DataSource = objRB.RenderDataTable;
#region RENDER TO PRINT PREVIEW
// and show it in preview dialog
PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog();
printPreview.FormTitle = REPORT_NAME;
objRB.ReportViewer = printPreview.ReportViewer;
objRB.RenderReport();
#region COMPANY INFO header information get from system params
// try
// {
// objRB.DrawPredefinedField(REPORTFLD_COMPANY,SystemProperty.SytemParams.Get(SystemParam.COMPANY_NAME));
// }
// catch{}
// try
// {
// objRB.DrawPredefinedField(REPORTFLD_ADDRESS,SystemProperty.SytemParams.Get(SystemParam.ADDRESS));
// }
// catch{}
// try
// {
// objRB.DrawPredefinedField(REPORTFLD_TEL,SystemProperty.SytemParams.Get(SystemParam.TEL));
// }
// catch{}
// try
// {
// objRB.DrawPredefinedField(REPORTFLD_FAX,SystemProperty.SytemParams.Get(SystemParam.FAX));
// }
// catch{}
#endregion
#region DRAW Parameters
const string CCN = "CCN";
const string MASTER_LOCATION = "Master Location";
const string LOCATION = "Location";
const string BIN = "Bin";
const string CATEGORY = "Category";
const string MODEL = "Model";
System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection();
arrParamAndValue.Add(CCN, strCCN);
arrParamAndValue.Add(MASTER_LOCATION, strMasterLocation);
if(pstrLocationID.Trim() != string.Empty)
{
arrParamAndValue.Add(LOCATION, strLocation);
}
if(pstrBinID.Trim() != string.Empty)
{
arrParamAndValue.Add(BIN, strBin);
}
if(pstrCategoryID.Trim() != string.Empty)
{
arrParamAndValue.Add(CATEGORY, strCategory);
}
if(pstrParameterModel.Trim() != string.Empty)
{
arrParamAndValue.Add(MODEL, pstrParameterModel);
}
/// anchor the Parameter drawing canvas cordinate to the fldTitle
C1.C1Report.Field fldTitle = objRB.GetFieldByName(REPORTFLD_TITLE);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3*fldTitle.RenderHeight;
//objRB.GetSectionByName(PAGE + HEADER).CanGrow = true;
objRB.DrawParameters( objRB.GetSectionByName(PAGE + HEADER) ,dblStartX , dblStartY , arrParamAndValue, objRB.Report.Font.Size);
#endregion
/// there are some hardcode numbers here
/// but these numbers are use ONLY ONE and ONLY USED HERE, so we don't need to define constant for it.
objRB.DrawBoxGroup_Madeby_Checkedby_Approvedby(objRB.GetSectionByName(PAGE + HEADER), 16035 -1400-1400-1400, 600, 1400, 1400, 200);
#region DAY--MONTH--YEAR INFO
DateTime dtm;
try
{
dtm = objUtilBO.GetDBDate();
}
catch
{
dtm = DateTime.Now;
}
try
{
objRB.DrawPredefinedField(REPORTFLD_DATETIME,dtm.ToString("dd-MM-yyyy hh:mm"));
}
catch{}
#endregion
objRB.RefreshReport();
printPreview.Show();
#endregion
UseReportViewerRenderEngine = false;
mResult = dtbResult;
return dtbResult;
}
/// <summary>
/// Thachnn: 28/10/2005 - my bd
/// Return data for Inventory Detail By Product Report
/// </summary>
/// <param name="pnCCNID"></param>
/// <param name="pnMasterLocationID"></param>
/// <param name="pnLocationID"></param>
/// <param name="pnCategoryID"></param>
/// <returns></returns>
public DataTable GetInventoryDetailByProductData(string pstrCCNID, string pstrMasterLocationID, string pstrLocationID, string pstrBinID, string pstrCategoryID, string pstrModel)
{
//const string METHOD_NAME = ".GetInventoryDetailByProductFromCCNMasLocLocationCategory()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
string strSql =
" Declare @CCNID int " +
" Declare @MasterLocationID int " +
" Declare @LocationID int " +
" Declare @BinID int " +
" Declare @CategoryID int " +
" Declare @Model varchar(50) " +
" /*-----------------------------------*/ " +
" Set @CCNID = " +pstrCCNID+ " " +
" Set @MasterLocationID = " +pstrMasterLocationID+ " " +
" Set @LocationID = '" +pstrLocationID+ "' " +
" Set @BinID = '" +pstrBinID+ "' " +
" Set @CategoryID = '" +pstrCategoryID+ "' " +
" Set @Model = '" +pstrModel+ "' " +
" /*-----------------------------------*/ " +
" " +
" SELECT " +
" MST_Location.Code AS [Location], " +
" ENM_BinType.Name as [BinType], " +
" MST_Bin.Code AS [Bin], " +
" ITM_Category.Code AS [Category], " +
" ITM_Product.ProductID as [ProductID], " +
" ITM_Product.Code as [PartNumber], " +
" ITM_Product.Description as [PartName], " +
" ITM_Product.Revision as [Model], " +
" MST_UnitOfMeasure.Code AS [StockUM], " +
" IV_BinCache.OHQuantity AS [OHQuantity], " +
" IV_BinCache.CommitQuantity AS [CommitQuantity], " +
" isnull(IV_BinCache.OHQuantity,0) - isnull(IV_BinCache.CommitQuantity,0) AS [AvailableQuantity] " +
" " +
" " +
" FROM ITM_Product " +
" join IV_BinCache on ITM_Product.ProductID = IV_BinCache.ProductID " +
" /* and not (IV_BinCache.OHQuantity = 0 and IV_BinCache.CommitQuantity = 0) */ " + /* If you don't want to display the empty OHQuantity, just remove the comment in SQL Sentence */
" join MST_Location ON IV_BinCache.LocationID = MST_Location.LocationID " +
" join MST_Bin on IV_BinCache.BinID = MST_Bin.BinID " +
" left join ENM_BinType on MST_Bin.BinTypeID = ENM_BinType.BinTypeID " +
" left join ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID " +
" join MST_UnitOfMeasure ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID " +
" " +
" WHERE " +
" ITM_Product.CCNID = @CCNID and " +
" MST_Location.MasterLocationID = @MasterLocationID and " +
(pstrLocationID.Trim() == string.Empty ? (string.Empty) : (" MST_Location.LocationID = @LocationID and ") ) +
(pstrBinID.Trim() == string.Empty ? (string.Empty) : (" MST_Bin.BinID = @BinID and ") ) +
(pstrCategoryID.Trim() == string.Empty ? (string.Empty) : (" ITM_Product.CategoryID IN (" + pstrCategoryID + ") and ") ) +
(pstrModel.Trim() == string.Empty ? (string.Empty) : (" ITM_Product.Revision IN (" + pstrModel + ") and ") ) +
" IV_BinCache.CCNID = @CCNID " +
" " +
" " +
" /* Bin Condition */ " +
" " +
" ORDER BY " +
" [Location], " +
" [BinType], " +
" [Bin], " +
" [Category], " +
" [PartNumber], " +
" [PartName], " +
" [Model], " +
" [StockUM] "
;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, TABLE_NAME);
if(dstPCS.Tables.Count > 0)
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
return dstPCS.Tables[TABLE_NAME];
}
else
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
return new DataTable();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using FluentSecurity.Caching;
using FluentSecurity.Configuration;
using FluentSecurity.Internals;
using FluentSecurity.Policy;
using FluentSecurity.ServiceLocation;
using FluentSecurity.Specification.Helpers;
using FluentSecurity.Specification.TestData;
using Moq;
using NUnit.Framework;
using Rhino.Mocks;
using MockRepository = Rhino.Mocks.MockRepository;
namespace FluentSecurity.Specification
{
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_I_create_an_invalid_policycontainer
{
private string _validControllerName;
private string _validActionName;
private IPolicyAppender _validPolicyAppender;
[SetUp]
public void SetUp()
{
_validControllerName = TestDataFactory.ValidControllerName;
_validActionName = TestDataFactory.ValidActionName;
_validPolicyAppender = TestDataFactory.CreateValidPolicyAppender();
}
[Test]
public void Should_throw_ArgumentException_when_the_controllername_is_null()
{
Assert.Throws<ArgumentException>(() =>
new PolicyContainer(null, _validActionName, _validPolicyAppender)
);
}
[Test]
public void Should_throw_ArgumentException_when_controllername_is_empty()
{
Assert.Throws<ArgumentException>(() =>
new PolicyContainer(string.Empty, _validActionName, _validPolicyAppender)
);
}
[Test]
public void Should_throw_ArgumentException_when_actionname_is_null()
{
Assert.Throws<ArgumentException>(() =>
new PolicyContainer(_validControllerName, null, _validPolicyAppender)
);
}
[Test]
public void Should_throw_ArgumentException_when_actionname_is_empty()
{
Assert.Throws<ArgumentException>(() =>
new PolicyContainer(_validControllerName, string.Empty, _validPolicyAppender)
);
}
[Test]
public void Should_throw_ArgumentException_when_policy_manager_is_null()
{
// Arrange
const IPolicyAppender policyAppender = null;
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
new PolicyContainer(_validControllerName, _validActionName, policyAppender)
);
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_I_create_a_valid_PolicyContainer
{
private IPolicyAppender _expectedPolicyAppender = new DefaultPolicyAppender();
private string _expectedControllerName = "SomeController";
private string _expectedActionName = "SomeAction";
[SetUp]
public void SetUp()
{
_expectedControllerName = TestDataFactory.ValidControllerName;
_expectedActionName = TestDataFactory.ValidActionName;
_expectedPolicyAppender = TestDataFactory.CreateValidPolicyAppender();
}
private IPolicyContainer Because()
{
return new PolicyContainer(_expectedControllerName, _expectedActionName, _expectedPolicyAppender);
}
[Test]
public void Should_have_controller_name_set_to_SomeController()
{
// Act
var policyContainer = Because();
// Assert
Assert.That(policyContainer.ControllerName, Is.EqualTo(_expectedControllerName));
}
[Test]
public void Should_have_action_name_set_to_SomeAction()
{
// Act
var policyContainer = Because();
// Assert
Assert.That(policyContainer.ActionName, Is.EqualTo(_expectedActionName));
}
[Test]
public void Should_have_PolicyAppender_set_to_DefaultPolicyAppender()
{
// Act
var policyContainer = (PolicyContainer) Because();
// Assert
Assert.That(policyContainer.PolicyAppender, Is.EqualTo(_expectedPolicyAppender));
}
[Test]
public void Should_override_ToString()
{
// Act
var policyContainer = (PolicyContainer)Because();
// Assert
Assert.That(policyContainer.ToString(), Is.EqualTo("FluentSecurity.PolicyContainer - SomeController - SomeAction"));
}
}
[TestFixture]
[Category("PolicContainerExtensionsSpec")]
public class When_adding_a_policy_instance_to_a_policycontainer
{
private ISecurityPolicy _policy;
private PolicyContainer _policyContainer;
private IPolicyContainerConfiguration _return;
[SetUp]
public void SetUp()
{
// Arrange
_policy = new DenyAnonymousAccessPolicy();
_policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
_return = _policyContainer.AddPolicy(_policy);
}
[Test]
public void Should_have_1_policy()
{
Assert.That(_policyContainer.GetPolicies().Single(), Is.EqualTo(_policy));
}
[Test]
public void Should_return_IPolicyContainerConfiguration()
{
Assert.That(_return, Is.Not.Null);
Assert.That(_return, Is.AssignableTo<IPolicyContainerConfiguration>());
}
}
[TestFixture]
[Category("PolicContainerExtensionsSpec")]
public class When_adding_a_policy_of_T_to_a_policycontainer
{
private PolicyContainer _policyContainer;
private IPolicyContainerConfiguration _return;
[SetUp]
public void SetUp()
{
// Arrange
_policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
_return = _policyContainer.AddPolicy<SomePolicy>();
}
[Test]
public void Should_have_a_lazy_policy_of_type_SomePolicy()
{
Assert.That(_policyContainer.GetPolicies().Single().GetType(), Is.EqualTo(typeof(LazySecurityPolicy<SomePolicy>)));
}
[Test]
public void Should_return_IPolicyContainerConfiguration_of_T()
{
Assert.That(_return, Is.Not.Null);
Assert.That(_return, Is.AssignableTo<IPolicyContainerConfiguration>());
Assert.That(_return, Is.AssignableTo<IPolicyContainerConfiguration<SomePolicy>>());
}
public class SomePolicy : ISecurityPolicy
{
public PolicyResult Enforce(ISecurityContext context)
{
throw new NotImplementedException();
}
}
}
[TestFixture]
[Category("PolicContainerExtensionsSpec")]
public class When_adding_two_policies_of_the_same_type_to_a_policycontainer
{
[Test]
public void Should_have_1_policy_when_adding_policy_instances()
{
// Arrange
var policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
policyContainer
.AddPolicy(new DenyAnonymousAccessPolicy())
.AddPolicy(new DenyAnonymousAccessPolicy());
// Assert
Assert.That(policyContainer.GetPolicies().Count(), Is.EqualTo(1));
}
[Test]
public void Should_have_1_policy_when_adding_policies_of_T()
{
// Arrange
var policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
policyContainer
.AddPolicy<DenyAnonymousAccessPolicy>()
.AddPolicy<DenyAnonymousAccessPolicy>();
// Assert
Assert.That(policyContainer.GetPolicies().Count(), Is.EqualTo(1));
}
[Test]
public void Should_have_1_policy_when_adding_policy_instance_and_policy_of_T()
{
// Arrange
var policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
policyContainer
.AddPolicy(new DenyAnonymousAccessPolicy())
.AddPolicy<DenyAnonymousAccessPolicy>();
// Assert
Assert.That(policyContainer.GetPolicies().Count(), Is.EqualTo(1));
}
[Test]
public void Should_have_1_policy_when_adding_policy_of_T_and_policy_instance()
{
// Arrange
var policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act
policyContainer
.AddPolicy<DenyAnonymousAccessPolicy>()
.AddPolicy(new DenyAnonymousAccessPolicy());
// Assert
Assert.That(policyContainer.GetPolicies().Count(), Is.EqualTo(1));
}
}
[TestFixture]
[Category("PolicContainerExtensionsSpec")]
public class When_removing_policies_from_a_policy_container
{
private PolicyContainer _policyContainer;
private readonly Policy1 _policy1 = new Policy1();
private readonly Policy2 _policy2 = new Policy2();
[SetUp]
public void SetUp()
{
// Arrange
_policyContainer = TestDataFactory.CreateValidPolicyContainer();
_policyContainer
.AddPolicy(_policy1)
.AddPolicy(_policy2);
}
[Test]
public void Should_remove_policy1()
{
// Act
_policyContainer.RemovePolicy<Policy1>();
// Assert
Assert.That(_policyContainer.GetPolicies().Single(), Is.EqualTo(_policy2));
}
[Test]
public void Should_remove_policy2()
{
// Act
_policyContainer.RemovePolicy<Policy2>();
// Assert
Assert.That(_policyContainer.GetPolicies().Single(), Is.EqualTo(_policy1));
}
[Test]
public void Should_remove_lazy_policy()
{
// Arrange
_policyContainer.AddPolicy<Policy3>();
// Act
_policyContainer.RemovePolicy<Policy3>();
// Assert
Assert.That(_policyContainer.GetPolicies().First(), Is.EqualTo(_policy1));
Assert.That(_policyContainer.GetPolicies().Last(), Is.EqualTo(_policy2));
Assert.That(_policyContainer.GetPolicies().Count(), Is.EqualTo(2));
}
[Test]
public void Should_remove_policy_matching_predicate()
{
// Act
_policyContainer.RemovePolicy<Policy1>(p => p.Name == "Policy1");
// Assert
Assert.That(_policyContainer.GetPolicies().Single(), Is.EqualTo(_policy2));
}
[Test]
public void Should_remove_lazy_policy_matching_predicate()
{
// Arrange
_policyContainer.AddPolicy<Policy3>();
// Act
_policyContainer.RemovePolicy<Policy3>(p => p.Value == "SomeValue");
// Assert
Assert.That(_policyContainer.GetPolicies().First(), Is.EqualTo(_policy1));
Assert.That(_policyContainer.GetPolicies().Last(), Is.EqualTo(_policy2));
Assert.That(_policyContainer.GetPolicies().Count(), Is.EqualTo(2));
}
[Test]
public void Should_not_remove_policies_not_matching_predicate()
{
// Act
_policyContainer.RemovePolicy<Policy1>(p => p.Name == "X");
// Assert
Assert.That(_policyContainer.GetPolicies().Count(), Is.EqualTo(2));
}
[Test]
public void Should_not_remove_lazy_policy_not_matching_predicate()
{
// Arrange
_policyContainer.AddPolicy<Policy3>();
// Act
_policyContainer.RemovePolicy<Policy3>(p => p.Value == "X");
// Assert
Assert.That(_policyContainer.GetPolicies().ElementAt(0), Is.EqualTo(_policy1));
Assert.That(_policyContainer.GetPolicies().ElementAt(1), Is.EqualTo(_policy2));
Assert.That(_policyContainer.GetPolicies().ElementAt(2).GetPolicyType(), Is.EqualTo(typeof(Policy3)));
Assert.That(_policyContainer.GetPolicies().Count(), Is.EqualTo(3));
}
[Test]
public void Should_remove_all_policies()
{
// Act
_policyContainer.RemovePolicy<ISecurityPolicy>();
// Assert
Assert.That(_policyContainer.GetPolicies().Any(), Is.False);
}
[Test]
public void Should_not_remove_any_policies()
{
// Act
_policyContainer.RemovePolicy<DenyAnonymousAccessPolicy>();
// Assert
Assert.That(_policyContainer.GetPolicies().Count(), Is.EqualTo(2));
Assert.That(_policyContainer.GetPolicies().First(), Is.EqualTo(_policy1));
Assert.That(_policyContainer.GetPolicies().Last(), Is.EqualTo(_policy2));
}
public class Policy1 : ISecurityPolicy
{
public PolicyResult Enforce(ISecurityContext context)
{
return PolicyResult.CreateSuccessResult(this);
}
public string Name = "Policy1";
}
public class Policy2 : ISecurityPolicy
{
public PolicyResult Enforce(ISecurityContext context)
{
return PolicyResult.CreateSuccessResult(this);
}
}
public class Policy3 : ISecurityPolicy
{
public string Value = "SomeValue";
public PolicyResult Enforce(ISecurityContext context)
{
return PolicyResult.CreateSuccessResult(this);
}
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_enforcing_policies
{
[Test]
public void Should_invoke_the_isautheticated_and_roles_functions()
{
// Arrange
var context = MockRepository.GenerateMock<ISecurityContext>();
context.Expect(x => x.Runtime).Return(TestDataFactory.CreateSecurityRuntime()).Repeat.Once();
context.Expect(x => x.CurrentUserIsAuthenticated()).Return(true).Repeat.Once();
context.Expect(x => x.CurrentUserRoles()).Return(new List<object> { UserRole.Owner }.ToArray()).Repeat.Once();
context.Replay();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(new TestPolicy());
// Act
policyContainer.EnforcePolicies(context);
// Assert
context.VerifyAllExpectations();
}
[Test]
public void Should_enforce_policies_with_context()
{
// Arrange
var roles = new List<object> { UserRole.Owner }.ToArray();
const bool isAuthenticated = true;
var context = new Mock<ISecurityContext>();
context.Setup(x => x.Runtime).Returns(TestDataFactory.CreateSecurityRuntime());
context.Setup(x => x.CurrentUserIsAuthenticated()).Returns(isAuthenticated);
context.Setup(x => x.CurrentUserRoles()).Returns(roles);
var policy = new Mock<ISecurityPolicy>();
policy.Setup(x => x.Enforce(It.Is<ISecurityContext>(c => c.CurrentUserIsAuthenticated() == isAuthenticated && c.CurrentUserRoles() == roles))).Returns(PolicyResult.CreateSuccessResult(policy.Object));
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(policy.Object);
// Act
policyContainer.EnforcePolicies(context.Object);
// Assert
policy.VerifyAll();
}
[Test]
public void Should_return_results()
{
// Arrange
var roles = new List<object> { UserRole.Owner }.ToArray();
const bool isAuthenticated = true;
const string failureOccured = "Failure occured";
var context = TestDataFactory.CreateSecurityContext(isAuthenticated, roles);
var policy = new Mock<ISecurityPolicy>();
policy.Setup(x => x.Enforce(It.IsAny<ISecurityContext>())).Returns(PolicyResult.CreateFailureResult(policy.Object, failureOccured));
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(policy.Object);
// Act
var results = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results.Count(), Is.EqualTo(1));
Assert.That(results.Single().ViolationOccured, Is.True);
Assert.That(results.Single().Message, Is.EqualTo(failureOccured));
}
[Test]
public void Should_stop_on_first_violation_and_return_1_result()
{
// Arrange
var context = TestDataFactory.CreateSecurityContext(false);
var firstPolicy = new Mock<ISecurityPolicy>();
firstPolicy.Setup(x => x.Enforce(It.IsAny<ISecurityContext>())).Returns(PolicyResult.CreateFailureResult(firstPolicy.Object, "Failure occured"));
var secondPolicy = new Mock<ISecurityPolicy>();
secondPolicy.Setup(x => x.Enforce(It.IsAny<ISecurityContext>())).Returns(PolicyResult.CreateSuccessResult(secondPolicy.Object));
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(firstPolicy.Object).AddPolicy(secondPolicy.Object);
// Act
var results = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results.Count(), Is.EqualTo(1));
Assert.That(results.Single().ViolationOccured, Is.True);
}
[Test]
public void Should_stop_on_first_violation_and_return_2_results()
{
// Arrange
var context = TestDataFactory.CreateSecurityContext(false);
var firstPolicy = new TestPolicy();
var secondPolicy = new Mock<ISecurityPolicy>();
secondPolicy.Setup(x => x.Enforce(It.IsAny<ISecurityContext>())).Returns(PolicyResult.CreateFailureResult(secondPolicy.Object, "Failure occured"));
var thirdPolicy = new TestPolicy();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(firstPolicy).AddPolicy(secondPolicy.Object).AddPolicy(thirdPolicy);
// Act
var results = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results.Count(), Is.EqualTo(2));
Assert.That(results.First().ViolationOccured, Is.False);
Assert.That(results.Last().ViolationOccured, Is.True);
}
[Test]
public void Should_throw_ConfigurationErrorsException_when_a_container_has_no_policies()
{
// Arrange
ExceptionFactory.RequestDescriptionProvider = () => TestDataFactory.CreateRequestDescription();
var context = TestDataFactory.CreateSecurityContext(false);
var policyContainer = TestDataFactory.CreateValidPolicyContainer();
// Act & Assert
Assert.Throws<ConfigurationErrorsException>(() => policyContainer.EnforcePolicies(context));
}
private class TestPolicy : ISecurityPolicy
{
public PolicyResult Enforce(ISecurityContext context)
{
// NOTE: OK to leave like this as tests depends on it.
var authenticated = context.CurrentUserIsAuthenticated();
var roles = context.CurrentUserRoles();
return PolicyResult.CreateSuccessResult(this);
}
}
}
[Category("PolicyContainerSpec")]
public class When_enforcing_lazy_policies
{
[Test]
public void Should_load_lazy_policy_exactly_twice_during_execution_with_caching_off()
{
// Arrange
var callsToContainer = 0;
var policy = new LazyLoadedPolicy();
FakeIoC.GetAllInstancesProvider = () =>
{
callsToContainer++;
return new List<object> { policy };
};
SecurityConfigurator.Configure(configuration =>
{
configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction);
configuration.ResolveServicesUsing(FakeIoC.GetAllInstances);
});
var context = new MockSecurityContext();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy<LazyLoadedPolicy>();
// Act
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
// Assert
Assert.That(callsToContainer, Is.EqualTo(2));
Assert.That(policy.EnforceCallCount, Is.EqualTo(2), "Did not call enforce the expected amount of times");
}
[Test]
public void Should_load_lazy_policy_exactly_once_during_execution_and_caching_on()
{
// Arrange
var callsToContainer = 0;
var policy = new LazyLoadedPolicy();
FakeIoC.GetAllInstancesProvider = () =>
{
callsToContainer++;
return new List<object> { policy };
};
SecurityConfigurator.Configure(configuration =>
{
configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction);
configuration.ResolveServicesUsing(FakeIoC.GetAllInstances);
configuration.Advanced.SetDefaultResultsCacheLifecycle(Cache.PerHttpRequest);
});
var context = new MockSecurityContext(runtime: SecurityConfiguration.Current.Runtime);
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy<LazyLoadedPolicy>();
// Act
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
// Assert
Assert.That(callsToContainer, Is.EqualTo(1));
Assert.That(policy.EnforceCallCount, Is.EqualTo(1), "Did not call enforce the expected amount of times");
}
[Test]
public void Should_load_lazy_policy_with_cache_key_exactly_twice_during_execution_with_caching_off()
{
// Arrange
var callsToContainer = 0;
var policy = new LazyLoadedPolicyWithCacheKey();
FakeIoC.GetAllInstancesProvider = () =>
{
callsToContainer++;
return new List<object> { policy };
};
SecurityConfigurator.Configure(configuration =>
{
configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction);
configuration.ResolveServicesUsing(FakeIoC.GetAllInstances);
});
var context = new MockSecurityContext();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy<LazyLoadedPolicyWithCacheKey>();
// Act
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
// Assert
Assert.That(callsToContainer, Is.EqualTo(2));
Assert.That(policy.CacheKeyCallCount, Is.EqualTo(2), "Did not get the custom cache key the expected amount of times");
Assert.That(policy.EnforceCallCount, Is.EqualTo(2), "Did not call enforce the expected amount of times");
}
[Test]
public void Should_load_lazy_policy_with_cache_key_exactly_twice_during_execution_with_caching_on()
{
// Arrange
var callsToContainer = 0;
var policy = new LazyLoadedPolicyWithCacheKey();
FakeIoC.GetAllInstancesProvider = () =>
{
callsToContainer++;
return new List<object> { policy };
};
SecurityConfigurator.Configure(configuration =>
{
configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction);
configuration.ResolveServicesUsing(FakeIoC.GetAllInstances);
configuration.Advanced.SetDefaultResultsCacheLifecycle(Cache.PerHttpRequest);
});
var context = new MockSecurityContext(runtime: SecurityConfiguration.Current.Runtime);
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy<LazyLoadedPolicyWithCacheKey>();
// Act
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
// Assert
Assert.That(callsToContainer, Is.EqualTo(2));
Assert.That(policy.CacheKeyCallCount, Is.EqualTo(2), "Did not get the custom cache key the expected amount of times");
Assert.That(policy.EnforceCallCount, Is.EqualTo(1), "Did not call enforce the expected amount of times");
}
[Test]
public void Should_enforce_lazy_policy_with_cache_key_exactly_twice_during_execution_with_caching_on()
{
// Arrange
var callsToContainer = 0;
var policy = new LazyLoadedPolicyWithCacheKey();
FakeIoC.GetAllInstancesProvider = () =>
{
callsToContainer++;
return new List<object> { policy };
};
SecurityConfigurator.Configure(configuration =>
{
configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction);
configuration.ResolveServicesUsing(FakeIoC.GetAllInstances);
configuration.Advanced.SetDefaultResultsCacheLifecycle(Cache.PerHttpRequest);
});
var context = new MockSecurityContext(runtime: SecurityConfiguration.Current.Runtime);
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy<LazyLoadedPolicyWithCacheKey>();
// Act
policy.CacheKey = "101";
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
policy.CacheKey = "102";
policyContainer.EnforcePolicies(context);
policyContainer.EnforcePolicies(context);
// Assert
Assert.That(callsToContainer, Is.EqualTo(5));
Assert.That(policy.CacheKeyCallCount, Is.EqualTo(5), "Did not get the custom cache key the expected amount of times");
Assert.That(policy.EnforceCallCount, Is.EqualTo(2), "Did not call enforce the expected amount of times");
}
public class LazyLoadedPolicy : ISecurityPolicy
{
public int EnforceCallCount { get; private set; }
public PolicyResult Enforce(ISecurityContext context)
{
EnforceCallCount++;
return PolicyResult.CreateSuccessResult(this);
}
}
public class LazyLoadedPolicyWithCacheKey : ISecurityPolicy, ICacheKeyProvider
{
public string CacheKey { get; set; }
public int EnforceCallCount { get; private set; }
public int CacheKeyCallCount { get; private set; }
public LazyLoadedPolicyWithCacheKey()
{
CacheKey = "1";
}
public PolicyResult Enforce(ISecurityContext context)
{
EnforceCallCount++;
return PolicyResult.CreateSuccessResult(this);
}
public string Get(ISecurityContext securityContext)
{
CacheKeyCallCount++;
return CacheKey;
}
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_enforcing_policies_with_default_cache_lifecycle_set_to_DoNotCache
{
[Test]
public void Should_return_unique_results()
{
// Arrange
var context = TestDataFactory.CreateSecurityContext(false);
context.Runtime.As<SecurityRuntime>().DefaultResultsCacheLifecycle = Cache.DoNotCache;
var firstPolicy = new IgnorePolicy();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(firstPolicy);
// Act
var results1 = policyContainer.EnforcePolicies(context);
var results2 = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results1.Single(), Is.Not.EqualTo(results2.Single()));
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_enforcing_policies_with_default_cache_lifecycle_set_to_PerHttpRequest
{
[Test]
public void Should_return_the_same_results()
{
// Arrange
var context = TestDataFactory.CreateSecurityContext(false);
context.Runtime.As<SecurityRuntime>().DefaultResultsCacheLifecycle = Cache.PerHttpRequest;
var firstPolicy = new IgnorePolicy();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(firstPolicy);
// Act
var results1 = policyContainer.EnforcePolicies(context);
var results2 = policyContainer.EnforcePolicies(context);
SecurityCache.ClearCache(Lifecycle.HybridHttpContext);;
var results3 = policyContainer.EnforcePolicies(context);
var results4 = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results1.Single(), Is.EqualTo(results2.Single()));
Assert.That(results3.Single(), Is.EqualTo(results4.Single()));
Assert.That(results1.Single(), Is.Not.EqualTo(results3.Single()), "Results should not be equal across requests.");
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_enforcing_policies_with_default_cache_lifecycle_set_to_PerHttpSession
{
[Test]
public void Should_return_the_same_results()
{
// Arrange
var context = TestDataFactory.CreateSecurityContext(false);
context.Runtime.As<SecurityRuntime>().DefaultResultsCacheLifecycle = Cache.PerHttpSession;
var firstPolicy = new IgnorePolicy();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(firstPolicy);
// Act
var results1 = policyContainer.EnforcePolicies(context);
var results2 = policyContainer.EnforcePolicies(context);
SecurityCache.ClearCache(Lifecycle.HybridHttpSession); ;
var results3 = policyContainer.EnforcePolicies(context);
var results4 = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results1.Single(), Is.EqualTo(results2.Single()));
Assert.That(results3.Single(), Is.EqualTo(results4.Single()));
Assert.That(results1.Single(), Is.Not.EqualTo(results3.Single()), "Results should not be equal across sessions.");
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_setting_the_cache_lifecycle
{
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_lifecycle_set_to_DoNotCache()
{
const Cache expectedLifecycle = Cache.DoNotCache;
const string expectedControllerName = "Controller1";
const string expectedActionName = "Action1";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(expectedLifecycle);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_DoNotCache()
{
const Cache expectedLifecycle = Cache.DoNotCache;
const string expectedControllerName = "Controller1";
const string expectedActionName = "Action1";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().DoNotCache();
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_lifecycle_set_to_PerHttpRequest()
{
const Cache expectedLifecycle = Cache.PerHttpRequest;
const string expectedControllerName = "Controller2";
const string expectedActionName = "Action2";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(expectedLifecycle);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_PerHttpRequest()
{
const Cache expectedLifecycle = Cache.PerHttpRequest;
const string expectedControllerName = "Controller2";
const string expectedActionName = "Action2";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().CachePerHttpRequest();
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_lifecycle_set_to_PerHttpSession()
{
const Cache expectedLifecycle = Cache.PerHttpSession;
const string expectedControllerName = "Controller3";
const string expectedActionName = "Action3";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(expectedLifecycle);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_PerHttpSession()
{
const Cache expectedLifecycle = Cache.PerHttpSession;
const string expectedControllerName = "Controller3";
const string expectedActionName = "Action3";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().CachePerHttpSession();
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_DenyAnonymousAccessPolicy_with_lifecycle_set_to_PerHttpRequest()
{
const Cache expectedLifecycle = Cache.PerHttpRequest;
const string expectedControllerName = "Controller4";
const string expectedActionName = "Action4";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<DenyAnonymousAccessPolicy>(expectedLifecycle);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(DenyAnonymousAccessPolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_add_policyresult_cache_strategies_for_each_policy_type()
{
// Arrange
const string expectedControllerName = "Controller5";
const string expectedActionName = "Action5";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer
.Cache<RequireAllRolesPolicy>(Cache.PerHttpRequest)
.Cache<RequireAnyRolePolicy>(Cache.PerHttpSession);
// Assert
Assert.That(policyContainer.CacheStrategies.Count, Is.EqualTo(2));
var strategy1 = policyContainer.CacheStrategies.First();
Assert.That(strategy1.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(strategy1.ActionName, Is.EqualTo(expectedActionName));
Assert.That(strategy1.PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
Assert.That(strategy1.CacheLifecycle, Is.EqualTo(Cache.PerHttpRequest));
Assert.That(strategy1.CacheLevel, Is.EqualTo(By.ControllerAction));
var strategy2 = policyContainer.CacheStrategies.Last();
Assert.That(strategy2.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(strategy2.ActionName, Is.EqualTo(expectedActionName));
Assert.That(strategy2.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(strategy2.CacheLifecycle, Is.EqualTo(Cache.PerHttpSession));
Assert.That(strategy2.CacheLevel, Is.EqualTo(By.ControllerAction));
}
[Test]
public void Should_update_existing_policyresult_cache_strategies()
{
// Arrange
const Cache expectedLifecycle = Cache.PerHttpSession;
const string expectedControllerName = "Controller6";
const string expectedActionName = "Action6";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer
.Cache<RequireAllRolesPolicy>(Cache.PerHttpRequest)
.Cache<RequireAllRolesPolicy>(Cache.PerHttpSession);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.ControllerAction));
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_setting_the_cache_lifecycle_and_cache_level
{
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_level_set_to_ControllerAction()
{
const By expectedLevel = By.ControllerAction;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest, expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_level_set_to_Controller()
{
const By expectedLevel = By.Controller;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest, expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_RequireAnyRolePolicy_with_level_set_to_Policy()
{
const By expectedLevel = By.Policy;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest, expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_DoNotCache_and_level_set_to_ControllerAction()
{
const By expectedLevel = By.ControllerAction;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().DoNotCache(expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(Cache.DoNotCache));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_PerHttpRequest_and_level_set_to_Controller()
{
const By expectedLevel = By.Controller;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().CachePerHttpRequest(expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(Cache.PerHttpRequest));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_add_policyresult_cache_strategy_for_Policy_T_with_lifecycle_set_to_PerHttpSession_and_level_set_to_Policy()
{
const By expectedLevel = By.Policy;
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer.AddPolicy<RequireAnyRolePolicy>().CachePerHttpSession(expectedLevel);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAnyRolePolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(Cache.PerHttpSession));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(expectedLevel));
}
[Test]
public void Should_update_existing_policyresult_cache_strategies()
{
// Arrange
const Cache expectedLifecycle = Cache.PerHttpSession;
const string expectedControllerName = "Controller6";
const string expectedActionName = "Action6";
var policyContainer = new PolicyContainer(expectedControllerName, expectedActionName, TestDataFactory.CreateValidPolicyAppender());
// Act
policyContainer
.Cache<RequireAllRolesPolicy>(Cache.PerHttpRequest, By.Controller)
.Cache<RequireAllRolesPolicy>(Cache.PerHttpSession, By.Policy);
// Assert
var policyResultCacheStrategy = policyContainer.CacheStrategies.Single();
Assert.That(policyResultCacheStrategy.ControllerName, Is.EqualTo(expectedControllerName));
Assert.That(policyResultCacheStrategy.ActionName, Is.EqualTo(expectedActionName));
Assert.That(policyResultCacheStrategy.PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
Assert.That(policyResultCacheStrategy.CacheLifecycle, Is.EqualTo(expectedLifecycle));
Assert.That(policyResultCacheStrategy.CacheLevel, Is.EqualTo(By.Policy));
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_clearing_the_cache_strategy
{
[Test]
public void Should_clear_all_cache_strategies()
{
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
policyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest);
// Act
policyContainer.ClearCacheStrategies();
// Assert
Assert.That(policyContainer.CacheStrategies.Any(), Is.False);
}
[Test]
public void Should_clear_all_cache_strategies_for_policy()
{
var policyContainer = new PolicyContainer("Controller", "Action", TestDataFactory.CreateValidPolicyAppender());
policyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest);
policyContainer.Cache<RequireAllRolesPolicy>(Cache.PerHttpRequest);
// Act
policyContainer.ClearCacheStrategyFor<RequireAnyRolePolicy>();
// Assert
Assert.That(policyContainer.CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
}
}
[TestFixture]
[Category("PolicyContainerSpec")]
public class When_enforcing_policies_with_default_cache_lifecycle_set
{
[Test]
public void Should_use_cache_lifecycle_specified_when_adding_a_policy()
{
// Arrange
const Cache defaultCacheLifecycle = Cache.PerHttpSession;
const Cache specifiedCacheLifecycle = Cache.PerHttpRequest;
var context = TestDataFactory.CreateSecurityContext(false);
context.Runtime.As<SecurityRuntime>().DefaultResultsCacheLifecycle = defaultCacheLifecycle;
var securityPolicy = new IgnorePolicy();
var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());
policyContainer.AddPolicy(securityPolicy).Cache<IgnorePolicy>(specifiedCacheLifecycle);
// Act
var results1 = policyContainer.EnforcePolicies(context);
var results2 = policyContainer.EnforcePolicies(context);
SecurityCache.ClearCache(Lifecycle.HybridHttpContext); ;
var results3 = policyContainer.EnforcePolicies(context);
var results4 = policyContainer.EnforcePolicies(context);
// Assert
Assert.That(results1.Single(), Is.EqualTo(results2.Single()));
Assert.That(results3.Single(), Is.EqualTo(results4.Single()));
Assert.That(results1.Single(), Is.Not.EqualTo(results3.Single()), "Results should not be equal across requests.");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Web;
using com.eforceglobal.DBAdmin.Constants;
using com.eforceglobal.DBAdmin.Utils;
namespace com.eforceglobal.DBAdmin.DAL
{
public abstract class DBHelper
{
#region Private Fields
private DbConnection _connectionWithTransaction = null;
private DbCommand _commandWithTransaction = null;
string connectionString = null;
string providerName = null;
private bool transactionOn = false;
private int? _commandTimeout;
#endregion
#region Protected Members
protected string ConnectionString
{
get
{
// make sure conection string is not empty
if (connectionString == string.Empty || connectionString.Length == 0)
throw new ArgumentException("Invalid database connection string.");
return connectionString;
}
set
{
connectionString = value;
}
}
protected string ProviderName
{
get
{
//as of now, we are dealing with sql server only
providerName = "System.Data.SqlClient";
return providerName;
}
set
{
providerName = value;
}
}
#endregion
#region Public Properties
public int? CommandTimeout
{
get
{
return _commandTimeout;
}
set
{
_commandTimeout = value;
}
}
public string UserQueryInput
{
get;
set;
}
#endregion
#region Public Methods
/// <summary>
/// Begins a transaction.
/// </summary>
public void BeginTransaction()
{
transactionOn = true;
}
/// <summary>
/// Commits the transaction
/// </summary>
public void CommitTransaction()
{
_commandWithTransaction.Transaction.Commit();
_connectionWithTransaction.Close();
transactionOn = false;
}
/// <summary>
/// Rollbacks the transaction.
/// </summary>
public void RollbackTransaction()
{
if (_commandWithTransaction != null)
{
if (_connectionWithTransaction != null)
{
if (_connectionWithTransaction.State == ConnectionState.Open)
{
_commandWithTransaction.Transaction.Rollback();
_connectionWithTransaction.Close();
transactionOn = false;
}
}
}
}
/// <summary>
/// Adds or refreshes rows in a DataTable within the DataSet using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Param.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Param"></param>
/// <param name="Dataset"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, DBCommandParam Param, T Dataset) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, Param, DatabaseName), Dataset, null);
}
/// <summary>
/// Adds or refreshes rows in a DataTable within the DataSet using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Params.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Params"></param>
/// <param name="Dataset"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, List<DBCommandParam> Params, T Dataset) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, Params, DatabaseName), Dataset, null);
}
/// <summary>
/// Adds or refreshes rows in a DataTable within the DataSet using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Dataset"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, T Dataset) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, DatabaseName), Dataset, null);
}
/// <summary>
/// Adds or refreshes rows in a DataTable, name of which is provided, using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Param.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Param"></param>
/// <param name="Dataset"></param>
/// <param name="TableName"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, DBCommandParam Param, T Dataset, string TableName) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, Param, DatabaseName), Dataset, TableName);
}
/// <summary>
/// Adds or refreshes rows in a DataTable, name of which is provided, using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Params.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Params"></param>
/// <param name="Dataset"></param>
/// <param name="TableName"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, List<DBCommandParam> Params, T Dataset, string TableName) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, Params, DatabaseName), Dataset, TableName);
}
/// <summary>
/// Adds or refreshes rows in a DataTable, name of which is provided, using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Dataset"></param>
/// <param name="TableName"></param>
public void FillDataSet<T>(string CommandKey, string DatabaseName, T Dataset, string TableName) where T : DataSet
{
FillDS<T>(GetDbCommand(CommandKey, DatabaseName), Dataset, TableName);
}
/// <summary>
/// Adds or refreshes rows in a DataTable using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Param.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Param"></param>
/// <param name="Datatable"></param>
public void FillDataTable<T>(string CommandKey, string DatabaseName, DBCommandParam Param, T Datatable) where T : DataTable
{
FillDT<T>(GetDbCommand(CommandKey, Param, DatabaseName), Datatable);
}
/// <summary>
/// Adds or refreshes rows in a DataTable using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey and Params.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Params"></param>
/// <param name="Datatable"></param>
public void FillDataTable<T>(string CommandKey, string DatabaseName, List<DBCommandParam> Params, T Datatable) where T : DataTable
{
FillDT<T>(GetDbCommand(CommandKey, Params, DatabaseName), Datatable);
}
/// <summary>
/// Adds or refreshes rows in a DataTable using the specified SQL SELECT statement retrieved / generated
/// with the help of the CommandKey.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Datatable"></param>
public void FillDataTable<T>(string CommandKey, string DatabaseName, T Datatable) where T : DataTable
{
FillDT<T>(GetDbCommand(CommandKey, DatabaseName), Datatable);
}
/// <summary>
/// Executes a SQL statement against a connection object.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Params"></param>
/// <returns>The number of rows affected.</returns>
public int ExecuteNonQuery(string CommandKey, string DatabaseName, List<DBCommandParam> Params)
{
return ExecuteNQuery(GetDbCommand(CommandKey, Params, DatabaseName));
}
/// <summary>
/// Executes a SQL statement against a connection object.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Param"></param>
/// <returns>The number of rows affected.</returns>
public int ExecuteNonQuery(string CommandKey, string DatabaseName, DBCommandParam Param)
{
return ExecuteNQuery(GetDbCommand(CommandKey, Param, DatabaseName));
}
/// <summary>
/// Executes a SQL statement against a connection object.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <returns>The number of rows affected.</returns>
public int ExecuteNonQuery(string CommandKey, string DatabaseName)
{
return ExecuteNQuery(GetDbCommand(CommandKey, DatabaseName));
}
/// <summary>
/// Executes the query and returns the first column of the first row in the result
/// set returned by the query. All other columns and rows are ignored.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Params"></param>
/// <returns>The first column of the first row in the result set.</returns>
public object ExecuteScalar(string CommandKey, string DatabaseName, List<DBCommandParam> Params)
{
return ExecuteScalarCommand(GetDbCommand(CommandKey, Params, DatabaseName));
}
/// <summary>
/// Executes the query and returns the first column of the first row in the result
/// set returned by the query. All other columns and rows are ignored.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <param name="Param"></param>
/// <returns>The first column of the first row in the result set.</returns>
public object ExecuteScalar(string CommandKey, string DatabaseName, DBCommandParam Param)
{
return ExecuteScalarCommand(GetDbCommand(CommandKey, Param, DatabaseName));
}
/// <summary>
/// Executes the query and returns the first column of the first row in the result
/// set returned by the query. All other columns and rows are ignored.
/// </summary>
/// <param name="CommandKey"></param>
/// <param name="DatabaseName"></param>
/// <returns>The first column of the first row in the result set.</returns>
public object ExecuteScalar(string CommandKey, string DatabaseName)
{
return ExecuteScalarCommand(GetDbCommand(CommandKey, DatabaseName));
}
#endregion
#region Private Methods
private DbCommand GetDbCommand(string commandKey, string databaseName)
{
DBCommandLibStruct cmdLibStruct = new DBCommandLibStruct();
if (commandKey == ConnectionConfig.UserCommandKey)
cmdLibStruct.CommandText = UserQueryInput;
else
cmdLibStruct = DBCommandParser.GetCommandDetails(commandKey);
cmdLibStruct.DatabaseName = string.IsNullOrEmpty(databaseName) ? string.Empty : databaseName;
DbCommand command = GetCommand(cmdLibStruct);
command.CommandType = cmdLibStruct.CommandType;
command.Parameters.Clear();
command.CommandText = SetParamPrefix(cmdLibStruct.CommandText);
return command;
}
private DbCommand GetDbCommand(string commandKey, DBCommandParam dbCommandparameter, string databaseName)
{
DbCommand command = GetDbCommand(commandKey, databaseName);
if (dbCommandparameter != null)
SetDBParameters(command, dbCommandparameter);
return command;
}
private DbCommand GetDbCommand(string commandKey, List<DBCommandParam> dbCommandparameters, string databaseName)
{
DbCommand command = GetDbCommand(commandKey, databaseName);
if (dbCommandparameters != null)
{
foreach (DBCommandParam param in dbCommandparameters)
SetDBParameters(command, param);
}
return command;
}
private void SetDBParameters(DbCommand dbCommand, DBCommandParam param)
{
if (param.IsCsvParam)
{
if (param.CsvList != null)
{
string valueList = string.Empty;
for (int i = 0; i < param.CsvList.Count; i++)
valueList += (i == 0 ? "'" : ",'") + param.CsvList[i].Trim() + "'";
dbCommand.CommandText = dbCommand.CommandText.Replace(SetParamPrefix(param.Name), valueList);
}
}
else
dbCommand.Parameters.Add(GetParameter(param));
}
private void FillDS<T>(DbCommand dbCommand, T Dataset, string TableName) where T : DataSet
{
DbDataAdapter adapter = DataAdapter;
adapter.SelectCommand = dbCommand;
if (TableName != null && TableName != string.Empty)
adapter.Fill(Dataset, TableName);
else
adapter.Fill(Dataset);
}
private void FillDT<T>(DbCommand dbCommand, T Datatable) where T : DataTable
{
DbDataAdapter adapter = DataAdapter;
adapter.SelectCommand = dbCommand;
adapter.Fill(Datatable);
}
private int ExecuteNQuery(DbCommand dbCommand)
{
//dbCommand.Connection.Open();
OpenConnection(dbCommand);
int returnVal = dbCommand.ExecuteNonQuery();
CloseConnection(dbCommand);//dbCommand.Connection.Close();
return returnVal;
}
private object ExecuteScalarCommand(DbCommand dbCommand)
{
OpenConnection(dbCommand);//dbCommand.Connection.Open();
object returnVal = dbCommand.ExecuteScalar();
CloseConnection(dbCommand);//dbCommand.Connection.Close();
return returnVal;
}
/// <summary>
/// Opens a closed connection.
/// </summary>
/// <param name="command">The command to which the connection belongs.</param>
private void OpenConnection(DbCommand command)
{
if (!transactionOn)
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
}
}
/// <summary>
/// Closes an open connection.
/// </summary>
/// <param name="command">The command to which the connection belongs.</param>
private void CloseConnection(DbCommand command)
{
if (!transactionOn)
{
if (command.Connection.State == ConnectionState.Open)
command.Connection.Close();
}
}
/// <summary>
/// Gets an instance of DbConnection.
/// </summary>
/// <param name="cmdLibStruct"></param>
/// <returns></returns>
private DbConnection GetConnection(DBCommandLibStruct cmdLibStruct)
{
DbConnection connection = null;
ConnectionString = GetConnectionString(cmdLibStruct.DatabaseName);
//ProviderName = conSettings.ProviderName;
if (transactionOn)
{
//if _connectionWithTransaction is not initialized, then create a connection with
//transaction and assign to it.
if (_connectionWithTransaction == null)
{
_connectionWithTransaction = Connection;
_connectionWithTransaction.Open();
}
if (_connectionWithTransaction.ConnectionString != ConnectionString)
connection = _connectionWithTransaction;
}
else
{
connection = Connection;
}
return connection;
}
private static string GetConnectionString(string DatabaseName)
{
string connString = ConnectionConfig.GetConnectionStringForLoggedInUser();
if (!string.IsNullOrEmpty(DatabaseName))
connString += string.Format("Database={0};", DatabaseName);
return connString;
}
/// <summary>
/// Gets an instance of the command.
/// </summary>
/// <param name="cmdLibStruct"></param>
/// <returns></returns>
private DbCommand GetCommand(DBCommandLibStruct cmdLibStruct)
{
DbCommand command;
DbConnection connection = GetConnection(cmdLibStruct);
if (transactionOn)
{
//If _commandWithTransaction is not initialized, then create it and open the transaction.
if (_commandWithTransaction == null)
{
_commandWithTransaction = connection.CreateCommand();
_commandWithTransaction.Transaction = connection.BeginTransaction();
}
command = _commandWithTransaction;
}
else
{
command = connection.CreateCommand();
}
if (CommandTimeout.HasValue)
command.CommandTimeout = CommandTimeout.Value;
return command;
}
#endregion
#region Abstract methods / properties
internal abstract DbDataAdapter DataAdapter
{
get;
}
internal abstract DbConnection Connection
{
get;
}
internal abstract string SetParamPrefix(string text);
internal abstract IDbDataParameter GetParameter(DBCommandParam dbCommandParam);
#endregion
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Orleans;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.TestingHost;
using UnitTests.GrainInterfaces;
using UnitTests.Tester;
namespace UnitTests.StreamingTests
{
[DeploymentItem("OrleansConfigurationForStreamingUnitTests.xml")]
[DeploymentItem("ClientConfigurationForStreamTesting.xml")]
[DeploymentItem("OrleansProviders.dll")]
[TestClass]
public class SampleStreamingTests : UnitTestSiloHost
{
private const string StreamNamespace = "SampleStreamNamespace";
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
private Guid streamId;
private string streamProvider;
public SampleStreamingTests()
: base(new TestingSiloOptions
{
StartFreshOrleans = true,
SiloConfigFile = new FileInfo("OrleansConfigurationForStreamingUnitTests.xml"),
},
new TestingClientOptions()
{
ClientConfigFile = new FileInfo("ClientConfigurationForStreamTesting.xml")
})
{
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup]
public static void MyClassCleanup()
{
StopAllSilos();
}
[TestCleanup]
public void TestCleanup()
{
if (streamProvider != null && streamProvider.Equals(StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME))
{
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME, DeploymentId, StorageTestConstants.DataConnectionString, logger).Wait();
}
}
[TestMethod, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming")]
public async Task SampleStreamingTests_1()
{
logger.Info("************************ SampleStreamingTests_1 *********************************");
streamId = Guid.NewGuid();
streamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
await StreamingTests_Consumer_Producer(streamId, streamProvider);
}
[TestMethod, TestCategory("Functional"), TestCategory("Streaming")]
public async Task SampleStreamingTests_2()
{
logger.Info("************************ SampleStreamingTests_2 *********************************");
streamId = Guid.NewGuid();
streamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
await StreamingTests_Producer_Consumer(streamId, streamProvider);
}
[TestMethod, TestCategory("Functional"), TestCategory("Streaming" )]
public async Task SampleStreamingTests_3()
{
logger.Info("************************ SampleStreamingTests_3 *********************************" );
streamId = Guid.NewGuid();
streamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
await StreamingTests_Producer_InlineConsumer(streamId, streamProvider );
}
[TestMethod, TestCategory("Functional"), TestCategory("Streaming")]
public async Task SampleStreamingTests_4()
{
logger.Info("************************ SampleStreamingTests_4 *********************************");
streamId = Guid.NewGuid();
streamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
await StreamingTests_Consumer_Producer(streamId, streamProvider);
}
[TestMethod, TestCategory("Functional"), TestCategory("Streaming")]
public async Task SampleStreamingTests_5()
{
logger.Info("************************ SampleStreamingTests_5 *********************************");
streamId = Guid.NewGuid();
streamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
await StreamingTests_Producer_Consumer(streamId, streamProvider);
}
[TestMethod, TestCategory("Functional"), TestCategory("Streaming")]
public async Task MultipleImplicitSubscriptionTest()
{
logger.Info("************************ MultipleImplicitSubscriptionTest *********************************");
streamId = Guid.NewGuid();
const int nRedEvents = 5, nBlueEvents = 3;
var provider = GrainClient.GetStreamProvider(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME);
var redStream = provider.GetStream<int>(streamId, "red");
var blueStream = provider.GetStream<int>(streamId, "blue");
for (int i = 0; i < nRedEvents; i++)
await redStream.OnNextAsync(i);
for (int i = 0; i < nBlueEvents; i++)
await blueStream.OnNextAsync(i);
var grain = GrainClient.GrainFactory.GetGrain<IMultipleImplicitSubscriptionGrain>(streamId);
var counters = await grain.GetCounters();
Assert.AreEqual(nRedEvents, counters.Item1);
Assert.AreEqual(nBlueEvents, counters.Item2);
}
private async Task StreamingTests_Consumer_Producer(Guid streamId, string streamProvider)
{
// consumer joins first, producer later
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
private async Task StreamingTests_Producer_Consumer(Guid streamId, string streamProvider)
{
// producer joins first, consumer later
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
private async Task StreamingTests_Producer_InlineConsumer(Guid streamId, string streamProvider)
{
// producer joins first, consumer later
var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_InlineConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, ISampleStreaming_ConsumerGrain consumer, bool assertIsTrue)
{
var numProduced = await producer.GetNumberProduced();
var numConsumed = await consumer.GetNumberConsumed();
logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed);
if (assertIsTrue)
{
Assert.AreEqual(numProduced, numConsumed, String.Format("numProduced = {0}, numConsumed = {1}", numProduced, numConsumed));
return true;
}
else
{
return numProduced == numConsumed;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.