context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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 System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenSim.Capabilities.Handlers;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Region.ClientStack.Linden
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GetTextureModule")]
public class GetTextureModule : INonSharedRegionModule
{
class APollRequest
{
public PollServiceTextureEventArgs thepoll;
public UUID reqID;
public Hashtable request;
public bool send503;
}
public class APollResponse
{
public Hashtable response;
public int bytes;
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private static GetTextureHandler m_getTextureHandler;
private IAssetService m_assetService = null;
private Dictionary<UUID, string> m_capsDict = new Dictionary<UUID, string>();
private static Thread[] m_workerThreads = null;
private static int m_NumberScenes = 0;
private static BlockingCollection<APollRequest> m_queue = new BlockingCollection<APollRequest>();
private Dictionary<UUID,PollServiceTextureEventArgs> m_pollservices = new Dictionary<UUID,PollServiceTextureEventArgs>();
private string m_Url = "localhost";
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["ClientStack.LindenCaps"];
if (config == null)
return;
/*
m_URL = config.GetString("Cap_GetTexture", string.Empty);
// Cap doesn't exist
if (m_URL != string.Empty)
{
m_Enabled = true;
m_RedirectURL = config.GetString("GetTextureRedirectURL");
}
*/
m_Url = config.GetString("Cap_GetTexture", "localhost");
}
public void AddRegion(Scene s)
{
m_scene = s;
}
public void RemoveRegion(Scene s)
{
s.EventManager.OnRegisterCaps -= RegisterCaps;
s.EventManager.OnDeregisterCaps -= DeregisterCaps;
m_NumberScenes--;
m_scene = null;
}
public void RegionLoaded(Scene s)
{
if(m_assetService == null)
{
m_assetService = s.RequestModuleInterface<IAssetService>();
// We'll reuse the same handler for all requests.
m_getTextureHandler = new GetTextureHandler(m_assetService);
}
s.EventManager.OnRegisterCaps += RegisterCaps;
s.EventManager.OnDeregisterCaps += DeregisterCaps;
m_NumberScenes++;
if (m_workerThreads == null)
{
m_workerThreads = new Thread[2];
for (uint i = 0; i < 2; i++)
{
m_workerThreads[i] = WorkManager.StartThread(DoTextureRequests,
String.Format("GetTextureWorker{0}", i),
ThreadPriority.Normal,
true,
false,
null,
int.MaxValue);
}
}
}
public void PostInitialise()
{
}
public void Close()
{
if(m_NumberScenes <= 0 && m_workerThreads != null)
{
m_log.DebugFormat("[GetTextureModule] Closing");
foreach (Thread t in m_workerThreads)
Watchdog.AbortThread(t.ManagedThreadId);
m_queue.Dispose();
}
}
public string Name { get { return "GetTextureModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private class PollServiceTextureEventArgs : PollServiceEventArgs
{
private List<Hashtable> requests =
new List<Hashtable>();
private Dictionary<UUID, APollResponse> responses =
new Dictionary<UUID, APollResponse>();
private HashSet<UUID> dropedResponses = new HashSet<UUID>();
private Scene m_scene;
private ScenePresence m_presence;
public PollServiceTextureEventArgs(UUID pId, Scene scene) :
base(null, "", null, null, null, null, pId, int.MaxValue)
{
m_scene = scene;
// x is request id, y is userid
HasEvents = (x, y) =>
{
lock (responses)
{
APollResponse response;
if (responses.TryGetValue(x, out response))
{
if (m_presence == null)
m_presence = m_scene.GetScenePresence(pId);
if (m_presence == null || m_presence.IsDeleted)
return true;
return m_presence.CapCanSendAsset(0, response.bytes);
}
return false;
}
};
Drop = (x, y) =>
{
lock (responses)
{
responses.Remove(x);
dropedResponses.Add(x);
}
};
GetEvents = (x, y) =>
{
lock (responses)
{
try
{
return responses[x].response;
}
finally
{
responses.Remove(x);
}
}
};
// x is request id, y is request data hashtable
Request = (x, y) =>
{
APollRequest reqinfo = new APollRequest();
reqinfo.thepoll = this;
reqinfo.reqID = x;
reqinfo.request = y;
reqinfo.send503 = false;
lock (responses)
{
if (responses.Count > 0)
{
if (m_queue.Count >= 4)
{
// Never allow more than 4 fetches to wait
reqinfo.send503 = true;
}
}
}
m_queue.Add(reqinfo);
};
// this should never happen except possible on shutdown
NoEvents = (x, y) =>
{
/*
lock (requests)
{
Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
requests.Remove(request);
}
*/
Hashtable response = new Hashtable();
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
return response;
};
}
public void Process(APollRequest requestinfo)
{
Hashtable response;
UUID requestID = requestinfo.reqID;
if(m_scene.ShuttingDown)
return;
lock (responses)
{
lock(dropedResponses)
{
if(dropedResponses.Contains(requestID))
{
dropedResponses.Remove(requestID);
return;
}
}
if (requestinfo.send503)
{
response = new Hashtable();
response["int_response_code"] = 503;
response["str_response_string"] = "Throttled";
response["content_type"] = "text/plain";
response["keepalive"] = false;
Hashtable headers = new Hashtable();
headers["Retry-After"] = 30;
response["headers"] = headers;
responses[requestID] = new APollResponse() {bytes = 0, response = response};
return;
}
// If the avatar is gone, don't bother to get the texture
if (m_scene.GetScenePresence(Id) == null)
{
response = new Hashtable();
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
responses[requestID] = new APollResponse() {bytes = 0, response = response};
return;
}
}
response = m_getTextureHandler.Handle(requestinfo.request);
lock (responses)
{
lock(dropedResponses)
{
if(dropedResponses.Contains(requestID))
{
dropedResponses.Remove(requestID);
return;
}
}
responses[requestID] = new APollResponse()
{
bytes = (int) response["int_bytes"],
response = response
};
}
}
}
private void RegisterCaps(UUID agentID, Caps caps)
{
if (m_Url == "localhost")
{
string capUrl = "/CAPS/" + UUID.Random() + "/";
// Register this as a poll service
PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene);
args.Type = PollServiceEventArgs.EventType.Texture;
MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args);
string hostName = m_scene.RegionInfo.ExternalHostName;
uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
string protocol = "http";
if (MainServer.Instance.UseSSL)
{
hostName = MainServer.Instance.SSLCommonName;
port = MainServer.Instance.SSLPort;
protocol = "https";
}
IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>();
if (handler != null)
handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl);
else
caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
m_pollservices[agentID] = args;
m_capsDict[agentID] = capUrl;
}
else
{
caps.RegisterHandler("GetTexture", m_Url);
}
}
private void DeregisterCaps(UUID agentID, Caps caps)
{
PollServiceTextureEventArgs args;
MainServer.Instance.RemoveHTTPHandler("", m_Url);
m_capsDict.Remove(agentID);
if (m_pollservices.TryGetValue(agentID, out args))
{
m_pollservices.Remove(agentID);
}
}
private static void DoTextureRequests()
{
APollRequest poolreq;
while (m_NumberScenes > 0)
{
poolreq = null;
if(!m_queue.TryTake(out poolreq, 4500) || poolreq == null)
{
Watchdog.UpdateThread();
continue;
}
if(m_NumberScenes <= 0)
break;
Watchdog.UpdateThread();
if(poolreq.reqID != UUID.Zero)
poolreq.thepoll.Process(poolreq);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GGJ_2014.Graphics;
using GGJ_2014.MenuSystemNS;
using GGJ_2014.Levels;
using GGJ_2014.Creatures;
namespace GGJ_2014
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public const int PLAYER_SPAWN_X = 100;
public const int PLAYER_SPAWN_Y = 100;
public const int POPUP_DISPLAY_POSITION_X = 10;
public const int POPUP_DISPLAY_POSITION_Y = 10;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState keyState;
KeyboardState prevKeyState;
MouseState mouseState;
MouseState prevMouseState;
SpriteFont myFont;
Player player;
EggFallWindow eggFall;
MenuBorderedTextItem eggCounter;
MenuBorderedTextItem eggTimer;
MenuBorderedTextItem playerStats;
MenuBorderedTextItem healthBar;
int timeElaspsed;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.ApplyChanges();
Camera.ScreenSize = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
Camera.Focus(0, 0);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.MAIN_MENU, Color.Black));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.QUESTIONS_MENU, Color.Black));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.GAMEPLAY, Color.CornflowerBlue));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.PAUSED, Color.CornflowerBlue));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.PAUSE_MENU, Color.Black));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.CREDITS_MENU, Color.CornflowerBlue));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.WIN_MENU, Color.Black));
MenuSystem.GetInstance()
.AddMenuScreen(
new MenuScreen(MenuScreenType.LOSE_MENU, Color.Black));
keyState = Keyboard.GetState();
prevKeyState = keyState;
mouseState = Mouse.GetState();
prevMouseState = mouseState;
//NEEDS TO CHANGE
//TextureStorage.GetInstance().LoadContent(Content);
#region Load_Generated_Textures
TextureStorage.GetInstance().AddTexture(Textures.NONE, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.NONE, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_DIRT, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_DIRT, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_GRASS, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_GRASS, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_COBBLESTONE, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_COBBLESTONE, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_PAVEMENT, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_PAVEMENT, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_TREE_ON_GRASS, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_TREE_ON_GRASS, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_PINETREE_ON_GRASS, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_PINETREE_ON_GRASS, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_PINETREE_STUMP, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_PINETREE_STUMP, null));
TextureStorage.GetInstance().AddTexture(Textures.CREATURE_CHICKEN, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.CREATURE_CHICKEN, null));
TextureStorage.GetInstance().AddTexture(Textures.CHICKEN_EGG, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.CHICKEN_EGG, null));
TextureStorage.GetInstance().AddTexture(Textures.CREATURE_GENERIC, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.CREATURE_GENERIC, null, 12, 12));
TextureStorage.GetInstance().AddTexture(Textures.CREATURE_VILLAGER, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.CREATURE_VILLAGER, null, 14, 14));
TextureStorage.GetInstance().AddTexture(Textures.TILE_BRICK_WALL, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_BRICK_WALL, null));
TextureStorage.GetInstance().AddTexture(Textures.TILE_WOOD_PLANK, TextureGenerator.GenerateTexture(GraphicsDevice, Textures.TILE_WOOD_PLANK, null));
#endregion
//player = new Player(TextureStorage.GetInstance().GetTexture(Textures.CREATURE_GENERIC), new Vector2(PLAYER_SPAWN_X, PLAYER_SPAWN_Y));
eggFall = new EggFallWindow();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
myFont = Content.Load<SpriteFont>("SpriteFont1");
MenuSystem.GetInstance().LoadContent(myFont, GraphicsDevice);
#region GameplayLoadContent
Level.GetInstance().AddCreature(player);
//MenuSystemNS.MenuSystem.GetInstance()
// .GetMenuScreenOfType(MenuSystemNS.MenuScreenType.GAMEPLAY)
// .AddControl(
// new MenuSystemNS.MenuButton(
// Vector2.Zero,
// "Regen Map!",
// Color.White,
// () => { ResetGame(); }
// ));
eggCounter = new MenuBorderedTextItem(
new Vector2(
graphics.PreferredBackBufferWidth * 0.01f,
graphics.PreferredBackBufferHeight * 0.9f
),
Color.PeachPuff,
string.Empty
);
MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuScreenType.GAMEPLAY)
.AddControl(eggCounter);
eggTimer = new MenuBorderedTextItem(
new Vector2(
graphics.PreferredBackBufferWidth * .65f,
graphics.PreferredBackBufferHeight * .9f
),
Color.PeachPuff,
string.Empty
);
MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuScreenType.GAMEPLAY)
.AddControl(eggTimer);
playerStats = new MenuBorderedTextItem(
new Vector2(
graphics.PreferredBackBufferWidth * 0.72f,
graphics.PreferredBackBufferHeight * 0.01f
),
Color.PeachPuff,
string.Empty
);
MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuScreenType.GAMEPLAY)
.AddControl(playerStats);
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuScreenType.GAMEPLAY)
.AddControl(
new MenuHiddenButton(
new List<Keys>(new[] { Keys.Escape }),
() => { MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.PAUSE_MENU); }
));
healthBar = new MenuBorderedTextItem(
new Vector2(
graphics.PreferredBackBufferWidth * 0.8f,
graphics.PreferredBackBufferHeight * 0.8f
),
Color.PeachPuff,
"Health: 100"
);
MenuSystem.GetInstance().GetMenuScreenOfType(MenuScreenType.GAMEPLAY).AddControl(healthBar);
#endregion
#region MainMenuLoadContent
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.MAIN_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 500),
"[Space] Let's Play!",
Color.White,
() =>
{
MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.QUESTIONS_MENU);
ResetGame();
MenuSystem.GetInstance().GetMenuScreenOfType(MenuScreenType.QUESTIONS_MENU).AddControl(new MultipleChoiceQuiz());
},
new List<Keys>(
new[]{
Keys.Space
})
));
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.MAIN_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 550),
"[Escape] Exit Game",
Color.White,
() =>
{
Exit();
},
new List<Keys>(
new[]{
Keys.Escape
})
));
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.MAIN_MENU)
.AddControl(
new MenuBorderedTextItem(Vector2.Zero, Color.White, "Russian Chicken Inspector"));
#endregion
#region WIN_MENU
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.WIN_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 500),
"[Enter] Return to Main Menu",
Color.White,
() => { MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.MAIN_MENU); },
new List<Keys>(
new[] {
Keys.Enter
})
));
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.WIN_MENU)
.AddControl(
new MenuBorderedTextItem(Vector2.Zero, Color.White, "You Win!"));
#endregion
#region LOSE_MENU
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.LOSE_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 500),
"[Enter] Return to Main Menu",
Color.White,
() => { MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.MAIN_MENU); },
new List<Keys>(
new[] {
Keys.Enter
})
));
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.LOSE_MENU)
.AddControl(
new MenuBorderedTextItem(Vector2.Zero, Color.White, "You Lose."));
#endregion
#region PAUSE_MENU
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.PAUSE_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 500),
"[Space] Continue Playing!",
Color.White,
() =>
{
MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.GAMEPLAY);
},
new List<Keys>(
new[] {
Keys.Space
})
));
MenuSystemNS.MenuSystem.GetInstance()
.GetMenuScreenOfType(MenuSystemNS.MenuScreenType.PAUSE_MENU)
.AddControl(
new MenuSystemNS.MenuButton(
new Vector2(10, 450),
"[Esc] Return to the Main Menu (Resets Game)!",
Color.White,
() =>
{
MenuSystem.GetInstance().SwitchToMenuScreenOfType(MenuScreenType.MAIN_MENU);
},
new List<Keys>(
new[] {
Keys.Escape
})
));
#endregion
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
private void ResetGame()
{
Level.GetInstance().LoadLevel();
player = new Player(TextureStorage.GetInstance().GetTexture(Textures.CREATURE_GENERIC), new Vector2(PLAYER_SPAWN_X, PLAYER_SPAWN_Y));
Level.GetInstance().AddCreature(player);
Player.Eggs = 0;
timeElaspsed = 0;
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
if (eggFall != null)
{
eggFall.Update(gameTime);
}
switch (MenuSystem.GetInstance().CurrentScreenType)
{
case MenuScreenType.MAIN_MENU:
{
eggFall.isActive = true;
break;
}
case MenuScreenType.GAMEPLAY:
{
timeElaspsed += gameTime.ElapsedGameTime.Milliseconds;
eggFall.isActive = false;
Level.GetInstance().Update(gameTime);
player.HandleInput(keyState);
Camera.Focus(player.MiddlePosition);
eggCounter.Text = string.Format("{0:000000} x Eggs Collected", Player.Eggs);
eggTimer.Text = string.Format("{0:000.0} Seconds Remaining", Player.TimeRemaining);
playerStats.Text = string.Format("Compassion: {0:F2}\nLuck: {1:F2}\nStrength: {2:F2}", Player.Compassion, Player.Luck, Player.Strength);
healthBar.Text = string.Format("Health: {0}%", Player.Health);
break;
}
case MenuScreenType.PAUSED:
{
eggFall.isActive = false;
break;
}
case MenuScreenType.PAUSE_MENU:
{
eggFall.isActive = true;
break;
}
case MenuScreenType.CREDITS_MENU:
{
eggFall.isActive = true;
break;
}
default:
eggFall.isActive = true;
break;
}
MenuSystem.GetInstance().Update(keyState, prevKeyState, mouseState, prevMouseState, gameTime);
prevKeyState = keyState;
keyState = Keyboard.GetState();
prevMouseState = mouseState;
mouseState = Mouse.GetState();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
MenuSystem.GetInstance().DrawUnderlay();
if (eggFall != null)
{
spriteBatch.Begin();
eggFall.Draw(spriteBatch);
spriteBatch.End();
}
switch (MenuSystem.GetInstance().CurrentScreenType)
{
case MenuScreenType.MAIN_MENU:
{
spriteBatch.Begin();
spriteBatch.DrawString(myFont, "[WASD] or Arrow Keys to move.\n"
+ "[Space Bar] to interact with things and chop down trees.\n\n"
+ "Collect eggs by doing various tasks.\n"
+ "Collect more eggs by completing secret acheivments!\n"
+ "\tInteract with Villagers!\n"
+ "\tChop Down Trees!\n"
+ "\tDiscover Golden Eggs!\n"
+ "You need " + Player.PLAYER_EGG_GOAL + " eggs to win.\nLevels are randomly generated.\n"
+ "Press [Escape] to pause and view the instructions during gameplay.", new Vector2(10, 100), Color.White);
spriteBatch.DrawString(myFont, "Liam Middlebrook, Alec Linder", new Vector2(476, 570), Color.White);
spriteBatch.End();
break;
}
case MenuScreenType.GAMEPLAY:
case MenuScreenType.PAUSED:
{
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, Camera.CameraMatrix);
//Add Game Draw code Here
Level.GetInstance().Draw(spriteBatch);
spriteBatch.End();
break;
}
case MenuScreenType.PAUSE_MENU:
{
spriteBatch.Begin();
spriteBatch.DrawString(myFont, "[WASD] or Arrow Keys to move.\n"
+ "[Space Bar] to interact with things and chop down trees.\n\n"
+ "Collect eggs by doing various tasks.\n"
+ "Collect more eggs by completing secret acheivments!\n"
+ "\tInteract with Villagers!\n"
+ "\tChop Down Trees!\n"
+ "\tDiscover Golden Eggs!\n"
+ "You need " + Player.PLAYER_EGG_GOAL + " eggs to win.\nLevels are randomly generated.\n"
+ "Press [Escape] to pause the game during gameplay.", new Vector2(10, 100), Color.White);
spriteBatch.DrawString(myFont, "Liam Middlebrook, Alec Linder", new Vector2(476, 570), Color.White);
spriteBatch.End();
break;
}
case MenuScreenType.CREDITS_MENU:
{
break;
}
case MenuScreenType.WIN_MENU:
{
spriteBatch.Begin();
spriteBatch.DrawString(myFont, string.Format("You beat the game in {0:mms}!", TimeInMillisecondsToString(timeElaspsed)), new Vector2(20, 100), Color.White);
spriteBatch.End();
break;
}
case MenuScreenType.LOSE_MENU:
{
spriteBatch.Begin();
bool outOfTime = timeElaspsed == (int)Player.PLAYER_ROUND_TIME;
string loseString = string.Empty;
if (outOfTime)
{
loseString += string.Format("You took {0:mms}!\nAnd died due to being attacked!", TimeInMillisecondsToString(timeElaspsed));
}
else
{
loseString += string.Format("You ran out of time!\nYou had {0} health remaining!", Player.Health);
}
spriteBatch.DrawString(myFont, loseString, new Vector2(20, 100), Color.White);
spriteBatch.End();
break;
}
}
spriteBatch.Begin();
MenuSystem.GetInstance().DrawOverlay(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
public static string TimeInMillisecondsToString(double time)
{
double seconds = time / 1000.0;
time %= 1000.0;
double minutes = seconds / 60.0;
seconds %= 60.0;
return string.Format("{0:0} minutes and {1:00} seconds", minutes, seconds);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Email Message
///<para>SObject Name: EmailMessage</para>
///<para>Custom Object: False</para>
///</summary>
public class SfEmailMessage : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "EmailMessage"; }
}
///<summary>
/// Email Message ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Case ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(true)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Case
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfCase Parent { get; set; }
///<summary>
/// Activity ID
/// <para>Name: ActivityId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activityId")]
[Updateable(false), Createable(true)]
public string ActivityId { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Text Body
/// <para>Name: TextBody</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "textBody")]
public string TextBody { get; set; }
///<summary>
/// HTML Body
/// <para>Name: HtmlBody</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "htmlBody")]
public string HtmlBody { get; set; }
///<summary>
/// Headers
/// <para>Name: Headers</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "headers")]
public string Headers { get; set; }
///<summary>
/// Subject
/// <para>Name: Subject</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
///<summary>
/// From Name
/// <para>Name: FromName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fromName")]
public string FromName { get; set; }
///<summary>
/// From Address
/// <para>Name: FromAddress</para>
/// <para>SF Type: email</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fromAddress")]
public string FromAddress { get; set; }
///<summary>
/// From
/// <para>Name: ValidatedFromAddress</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "validatedFromAddress")]
public string ValidatedFromAddress { get; set; }
///<summary>
/// To Address
/// <para>Name: ToAddress</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "toAddress")]
public string ToAddress { get; set; }
///<summary>
/// CC Address
/// <para>Name: CcAddress</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "ccAddress")]
public string CcAddress { get; set; }
///<summary>
/// BCC Address
/// <para>Name: BccAddress</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bccAddress")]
public string BccAddress { get; set; }
///<summary>
/// Is Incoming
/// <para>Name: Incoming</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "incoming")]
[Updateable(false), Createable(true)]
public bool? Incoming { get; set; }
///<summary>
/// Has Attachment
/// <para>Name: HasAttachment</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasAttachment")]
[Updateable(false), Createable(false)]
public bool? HasAttachment { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
///<summary>
/// Message Date
/// <para>Name: MessageDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "messageDate")]
public DateTimeOffset? MessageDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Email Message ID
/// <para>Name: ReplyToEmailMessageId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "replyToEmailMessageId")]
[Updateable(false), Createable(true)]
public string ReplyToEmailMessageId { get; set; }
///<summary>
/// ReferenceTo: EmailMessage
/// <para>RelationshipName: ReplyToEmailMessage</para>
///</summary>
[JsonProperty(PropertyName = "replyToEmailMessage")]
[Updateable(false), Createable(false)]
public SfEmailMessage ReplyToEmailMessage { get; set; }
///<summary>
/// Is Externally Visible
/// <para>Name: IsExternallyVisible</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isExternallyVisible")]
[Updateable(false), Createable(false)]
public bool? IsExternallyVisible { get; set; }
///<summary>
/// Message ID
/// <para>Name: MessageIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "messageIdentifier")]
public string MessageIdentifier { get; set; }
///<summary>
/// Thread ID
/// <para>Name: ThreadIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "threadIdentifier")]
public string ThreadIdentifier { get; set; }
///<summary>
/// Is Client Managed
/// <para>Name: IsClientManaged</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isClientManaged")]
[Updateable(false), Createable(true)]
public bool? IsClientManaged { get; set; }
///<summary>
/// Related To ID
/// <para>Name: RelatedToId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedToId")]
[Updateable(false), Createable(true)]
public string RelatedToId { get; set; }
///<summary>
/// Is Tracked
/// <para>Name: IsTracked</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isTracked")]
public bool? IsTracked { get; set; }
///<summary>
/// Opened?
/// <para>Name: IsOpened</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isOpened")]
[Updateable(false), Createable(false)]
public bool? IsOpened { get; set; }
///<summary>
/// First Opened
/// <para>Name: FirstOpenedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "firstOpenedDate")]
public DateTimeOffset? FirstOpenedDate { get; set; }
///<summary>
/// Last Opened
/// <para>Name: LastOpenedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastOpenedDate")]
public DateTimeOffset? LastOpenedDate { get; set; }
///<summary>
/// Bounced?
/// <para>Name: IsBounced</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isBounced")]
public bool? IsBounced { get; set; }
///<summary>
/// Email Template ID
/// <para>Name: EmailTemplateId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "emailTemplateId")]
public string EmailTemplateId { get; set; }
///<summary>
/// ReferenceTo: EmailTemplate
/// <para>RelationshipName: EmailTemplate</para>
///</summary>
[JsonProperty(PropertyName = "emailTemplate")]
[Updateable(false), Createable(false)]
public SfEmailTemplate EmailTemplate { get; set; }
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
private string _path;
private PipeDirection _direction;
private PipeOptions _options;
private int _inBufferSize;
private int _outBufferSize;
private HandleInheritability _inheritability;
[SecurityCritical]
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
if (transmissionMode == PipeTransmissionMode.Message)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
// It's a Windows-specific concept.
_path = GetPipePath(".", pipeName);
_direction = direction;
_options = options;
_inBufferSize = inBufferSize;
_outBufferSize = outBufferSize;
_inheritability = inheritability;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
public void WaitForConnection()
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// Binding to an existing path fails, so we need to remove anything left over at this location.
// There's of course a race condition here, where it could be recreated by someone else between this
// deletion and the bind below, in which case we'll simply let the bind fail and throw.
Interop.Sys.Unlink(_path); // ignore any failures
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
try
{
socket.Bind(new UnixDomainSocketEndPoint(_path));
socket.Listen(1);
Socket acceptedSocket = socket.Accept();
SafePipeHandle serverHandle = new SafePipeHandle(acceptedSocket);
try
{
ConfigureSocket(acceptedSocket, serverHandle, _direction, _inBufferSize, _outBufferSize, _inheritability);
}
catch
{
serverHandle.Dispose();
acceptedSocket.Dispose();
throw;
}
InitializeHandle(serverHandle, isExposed: false, isAsync: (_options & PipeOptions.Asynchronous) != 0);
State = PipeState.Connected;
}
finally
{
// Bind will have created a file. Now that the client is connected, it's no longer necessary, so get rid of it.
Interop.Sys.Unlink(_path); // ignore any failures; worst case is we leave a tmp file
// Clean up the listening socket
socket.Dispose();
}
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
WaitForConnectionAsyncCore();
}
private async Task WaitForConnectionAsyncCore()
{
// This is the same implementation as is in WaitForConnection(), but using Socket.AcceptAsync
// instead of Socket.Accept.
// Binding to an existing path fails, so we need to remove anything left over at this location.
// There's of course a race condition here, where it could be recreated by someone else between this
// deletion and the bind below, in which case we'll simply let the bind fail and throw.
Interop.Sys.Unlink(_path); // ignore any failures
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
try
{
socket.Bind(new UnixDomainSocketEndPoint(_path));
socket.Listen(1);
Socket acceptedSocket = await socket.AcceptAsync().ConfigureAwait(false);
SafePipeHandle serverHandle = new SafePipeHandle(acceptedSocket);
ConfigureSocket(acceptedSocket, serverHandle, _direction, _inBufferSize, _outBufferSize, _inheritability);
InitializeHandle(serverHandle, isExposed: false, isAsync: (_options & PipeOptions.Asynchronous) != 0);
State = PipeState.Connected;
}
finally
{
// Bind will have created a file. Now that the client is connected, it's no longer necessary, so get rid of it.
Interop.Sys.Unlink(_path); // ignore any failures; worst case is we leave a tmp file
// Clean up the listening socket
socket.Dispose();
}
}
[SecurityCritical]
public void Disconnect()
{
CheckDisconnectOperations();
State = PipeState.Disconnected;
InternalHandle.Dispose();
InitializeHandle(null, false, false);
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
[SecurityCritical]
public string GetImpersonationUserName()
{
CheckWriteOperations();
SafeHandle handle = InternalHandle?.NamedPipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
string name = Interop.Sys.GetPeerUserName(handle);
if (name != null)
{
return name;
}
throw CreateExceptionForLastError();
}
public override int InBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream);
return InternalHandle?.NamedPipeSocket?.ReceiveBufferSize ?? _inBufferSize;
}
}
public override int OutBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream);
return InternalHandle?.NamedPipeSocket?.SendBufferSize ?? _outBufferSize;
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// This method calls a delegate while impersonating the client.
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
SafeHandle handle = InternalHandle?.NamedPipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// Get the current effective ID to fallback to after the impersonationWorker is run
uint currentEUID = Interop.Sys.GetEUid();
// Get the userid of the client process at the end of the pipe
uint peerID;
if (Interop.Sys.GetPeerID(handle, out peerID) == -1)
{
throw CreateExceptionForLastError();
}
// set the effective userid of the current (server) process to the clientid
if (Interop.Sys.SetEUid(peerID) == -1)
{
throw CreateExceptionForLastError();
}
try
{
impersonationWorker();
}
finally
{
// set the userid of the current (server) process back to its original value
Interop.Sys.SetEUid(currentEUID);
}
}
private Exception CreateExceptionForLastError()
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
return error.Error == Interop.Error.ENOTSUP ?
new PlatformNotSupportedException(SR.Format(SR.PlatformNotSupported_OperatingSystemError, nameof(Interop.Error.ENOTSUP))) :
Interop.GetExceptionForIoErrno(error, _path);
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Web;
using SuperPutty.Data;
using SuperPutty.Utils;
using SuperPutty.Gui;
using log4net;
namespace SuperPutty
{
public partial class dlgEditSession : Form
{
private static readonly ILog Log = LogManager.GetLogger(typeof(dlgEditSession));
public delegate bool SessionNameValidationHandler(string name, out string error);
private SessionData Session;
private String OldHostname;
private bool isInitialized = false;
private ImageListPopup imgPopup = null;
public dlgEditSession(SessionData session, ImageList iconList)
{
Session = session;
InitializeComponent();
// get putty saved settings from the registry to populate
// the dropdown
PopulatePuttySettings();
if (!String.IsNullOrEmpty(Session.SessionName))
{
this.Text = "Edit session: " + session.SessionName;
this.textBoxSessionName.Text = Session.SessionName;
this.textBoxHostname.Text = Session.Host;
this.textBoxPort.Text = Session.Port.ToString();
this.textBoxExtraArgs.Text = Session.ExtraArgs;
this.textBoxUsername.Text = Session.Username;
switch (Session.Proto)
{
case ConnectionProtocol.Raw:
radioButtonRaw.Checked = true;
break;
case ConnectionProtocol.Rlogin:
radioButtonRlogin.Checked = true;
break;
case ConnectionProtocol.Serial:
radioButtonSerial.Checked = true;
break;
case ConnectionProtocol.SSH:
radioButtonSSH.Checked = true;
break;
case ConnectionProtocol.Telnet:
radioButtonTelnet.Checked = true;
break;
case ConnectionProtocol.Cygterm:
radioButtonCygterm.Checked = true;
break;
case ConnectionProtocol.Mintty:
radioButtonMintty.Checked = true;
break;
default:
radioButtonSSH.Checked = true;
break;
}
foreach(String settings in this.comboBoxPuttyProfile.Items){
if (settings == session.PuttySession)
{
this.comboBoxPuttyProfile.SelectedItem = settings;
break;
}
}
this.buttonSave.Enabled = true;
}
else
{
this.Text = "Create new session";
radioButtonSSH.Checked = true;
this.buttonSave.Enabled = false;
}
// Setup icon chooser
this.buttonImageSelect.ImageList = iconList;
this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey)
? SessionTreeview.ImageKeySession
: Session.ImageKey;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
this.isInitialized = true;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BeginInvoke(new MethodInvoker(delegate { this.textBoxSessionName.Focus(); }));
}
private void PopulatePuttySettings()
{
foreach (String sessionName in PuttyDataHelper.GetSessionNames())
{
comboBoxPuttyProfile.Items.Add(sessionName);
}
comboBoxPuttyProfile.SelectedItem = PuttyDataHelper.SessionDefaultSettings;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void buttonSave_Click(object sender, EventArgs e)
{
Session.SessionName = textBoxSessionName.Text.Trim();
Session.PuttySession = comboBoxPuttyProfile.Text.Trim();
Session.Host = textBoxHostname.Text.Trim();
Session.ExtraArgs = textBoxExtraArgs.Text.Trim();
Session.Port = int.Parse(textBoxPort.Text.Trim());
Session.Username = textBoxUsername.Text.Trim();
Session.SessionId = SessionData.CombineSessionIds(SessionData.GetSessionParentId(Session.SessionId), Session.SessionName);
Session.ImageKey = buttonImageSelect.ImageKey;
for (int i = 0; i < groupBox1.Controls.Count; i++)
{
RadioButton rb = (RadioButton)groupBox1.Controls[i];
if (rb.Checked)
{
Session.Proto = (ConnectionProtocol)rb.Tag;
}
}
DialogResult = DialogResult.OK;
}
/// <summary>
/// Special UI handling for cygterm or mintty sessions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonCygterm_CheckedChanged(object sender, EventArgs e)
{
string host = this.textBoxHostname.Text;
bool isLocalShell = this.radioButtonCygterm.Checked || this.radioButtonMintty.Checked;
this.textBoxPort.Enabled = !isLocalShell;
this.textBoxExtraArgs.Enabled = !isLocalShell;
this.textBoxUsername.Enabled = !isLocalShell;
if (isLocalShell)
{
if (String.IsNullOrEmpty(host) || !host.StartsWith(CygtermStartInfo.LocalHost))
{
OldHostname = this.textBoxHostname.Text;
this.textBoxHostname.Text = CygtermStartInfo.LocalHost;
}
}
}
private void radioButtonRaw_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRaw.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
}
}
private void radioButtonTelnet_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonTelnet.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "23";
}
}
private void radioButtonRlogin_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRlogin.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "513";
}
}
private void radioButtonSSH_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonSSH.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "22";
}
}
public static int GetDefaultPort(ConnectionProtocol protocol)
{
int port = 22;
switch (protocol)
{
case ConnectionProtocol.Raw:
break;
case ConnectionProtocol.Rlogin:
port = 513;
break;
case ConnectionProtocol.Serial:
break;
case ConnectionProtocol.Telnet:
port = 23;
break;
}
return port;
}
#region Icon
private void buttonImageSelect_Click(object sender, EventArgs e)
{
if (this.imgPopup == null)
{
int n = buttonImageSelect.ImageList.Images.Count;
int x = (int) Math.Floor(Math.Sqrt(n)) + 1;
int cols = x;
int rows = x;
imgPopup = new ImageListPopup();
imgPopup.BackgroundColor = Color.FromArgb(241, 241, 241);
imgPopup.BackgroundOverColor = Color.FromArgb(102, 154, 204);
imgPopup.Init(this.buttonImageSelect.ImageList, 8, 8, cols, rows);
imgPopup.ItemClick += new ImageListPopupEventHandler(this.OnItemClicked);
}
Point pt = PointToScreen(new Point(buttonImageSelect.Left, buttonImageSelect.Bottom));
imgPopup.Show(pt.X + 2, pt.Y);
}
private void OnItemClicked(object sender, ImageListPopupEventArgs e)
{
if (imgPopup == sender)
{
buttonImageSelect.ImageKey = e.SelectedItem;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
}
}
#endregion
#region Validation Logic
public SessionNameValidationHandler SessionNameValidator { get; set; }
private void textBoxSessionName_Validating(object sender, CancelEventArgs e)
{
if (this.SessionNameValidator != null)
{
string error;
if (!this.SessionNameValidator(this.textBoxSessionName.Text, out error))
{
e.Cancel = true;
this.SetError(this.textBoxSessionName, error ?? "Invalid Session Name");
}
}
}
private void textBoxSessionName_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxSessionName, String.Empty);
}
private void textBoxPort_Validating(object sender, CancelEventArgs e)
{
int val;
if (!Int32.TryParse(this.textBoxPort.Text, out val))
{
e.Cancel = true;
this.SetError(this.textBoxPort, "Invalid Port");
}
}
private void textBoxPort_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxPort, String.Empty);
}
private void textBoxHostname_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty((string)this.comboBoxPuttyProfile.SelectedItem) &&
string.IsNullOrEmpty(this.textBoxHostname.Text.Trim()))
{
if (sender == this.textBoxHostname)
{
this.SetError(this.textBoxHostname, "A host name must be specified if a Putty Session Profile is not selected");
}
else if (sender == this.comboBoxPuttyProfile)
{
this.SetError(this.comboBoxPuttyProfile, "A Putty Session Profile must be selected if a Host Name is not provided");
}
}
else
{
this.SetError(this.textBoxHostname, String.Empty);
this.SetError(this.comboBoxPuttyProfile, String.Empty);
}
}
private void comboBoxPuttyProfile_Validating(object sender, CancelEventArgs e)
{
this.textBoxHostname_Validating(sender, e);
}
private void comboBoxPuttyProfile_SelectedIndexChanged(object sender, EventArgs e)
{
this.ValidateChildren(ValidationConstraints.ImmediateChildren);
}
void SetError(Control control, string error)
{
this.errorProvider.SetError(control, error);
this.EnableDisableSaveButton();
}
void EnableDisableSaveButton()
{
this.buttonSave.Enabled = (
this.errorProvider.GetError(this.textBoxSessionName) == String.Empty &&
this.errorProvider.GetError(this.textBoxHostname) == String.Empty &&
this.errorProvider.GetError(this.textBoxPort) == String.Empty &&
this.errorProvider.GetError(this.comboBoxPuttyProfile) == String.Empty);
}
#endregion
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using OpenTK.Platform;
namespace OpenTK.Graphics
{
/// <summary>
/// Represents and provides methods to manipulate an OpenGL render context.
/// </summary>
public sealed class GraphicsContext : IGraphicsContext, IGraphicsContextInternal
{
#region --- Fields ---
IGraphicsContext implementation; // The actual render context implementation for the underlying platform.
bool disposed;
// Indicates that this context was created through external means, e.g. Tao.Sdl or GLWidget#.
// In this case, We'll assume that the external program will manage the lifetime of this
// context - we'll not destroy it manually.
readonly bool IsExternal;
bool check_errors = true;
static bool share_contexts = true;
static bool direct_rendering = true;
readonly static object SyncRoot = new object();
// Maps OS-specific context handles to GraphicsContext weak references.
readonly static Dictionary<ContextHandle, WeakReference> available_contexts = new Dictionary<ContextHandle, WeakReference>();
#endregion
#region --- Constructors ---
// Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method).
GraphicsContext(ContextHandle handle)
{
implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);
lock (SyncRoot)
{
available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this));
}
}
/// <summary>
/// Constructs a new GraphicsContext with the specified GraphicsMode and attaches it to the specified window.
/// </summary>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
/// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
public GraphicsContext(GraphicsMode mode, IWindowInfo window)
: this(mode, window, 1, 0, GraphicsContextFlags.Default)
{ }
/// <summary>
/// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags, and attaches it to the specified window.
/// </summary>
/// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
/// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
/// <param name="major">The major version of the new GraphicsContext.</param>
/// <param name="minor">The minor version of the new GraphicsContext.</param>
/// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param>
/// <remarks>
/// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored.
/// </remarks>
public GraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags)
{
lock (SyncRoot)
{
bool designMode = false;
if (mode == null && window == null)
designMode = true;
else if (mode == null) throw new ArgumentNullException("mode", "Must be a valid GraphicsMode.");
else if (window == null) throw new ArgumentNullException("window", "Must point to a valid window.");
// Silently ignore invalid major and minor versions.
if (major <= 0)
major = 1;
if (minor < 0)
minor = 0;
Debug.Print("Creating GraphicsContext.");
try
{
Debug.Indent();
Debug.Print("GraphicsMode: {0}", mode);
Debug.Print("IWindowInfo: {0}", window);
Debug.Print("GraphicsContextFlags: {0}", flags);
Debug.Print("Requested version: {0}.{1}", major, minor);
IGraphicsContext shareContext = shareContext = FindSharedContext();
// Todo: Add a DummyFactory implementing IPlatformFactory.
if (designMode)
{
implementation = new Platform.Dummy.DummyGLContext();
}
else
{
IPlatformFactory factory = null;
switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded)
{
case false: factory = Factory.Default; break;
case true: factory = Factory.Embedded; break;
}
implementation = factory.CreateGLContext(mode, window, shareContext, direct_rendering, major, minor, flags);
// Note: this approach does not allow us to mix native and EGL contexts in the same process.
// This should not be a problem, as this use-case is not interesting for regular applications.
// Note 2: some platforms may not support a direct way of getting the current context
// (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which
// iterates through all known contexts and checks if any is current (check GetCurrentContext
// declaration).
if (GetCurrentContext == null)
{
GetCurrentContextDelegate temp = factory.CreateGetCurrentGraphicsContext();
if (temp != null)
{
GetCurrentContext = temp;
}
}
}
available_contexts.Add((this as IGraphicsContextInternal).Context, new WeakReference(this));
}
finally
{
Debug.Unindent();
}
}
}
/// <summary>
/// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK.
/// </summary>
/// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
/// <param name="window">The window this context is bound to. This must be a valid window obtained through Utilities.CreateWindowInfo.</param>
/// <exception cref="GraphicsContextException">Occurs if handle is identical to a context already registered with OpenTK.</exception>
public GraphicsContext(ContextHandle handle, IWindowInfo window)
: this(handle, window, null, 1, 0, GraphicsContextFlags.Default)
{ }
/// <summary>
/// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK.
/// </summary>
/// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
/// <param name="window">The window this context is bound to. This must be a valid window obtained through Utilities.CreateWindowInfo.</param>
/// <param name="shareContext">A different context that shares resources with this instance, if any.
/// Pass null if the context is not shared or if this is the first GraphicsContext instruct you construct.</param>
/// <param name="major">The major version of the context (e.g. "2" for "2.1").</param>
/// <param name="minor">The minor version of the context (e.g. "1" for "2.1").</param>
/// <param name="flags">A bitwise combination of <see cref="GraphicsContextFlags"/> that describe this context.</param>
/// <exception cref="GraphicsContextException">Occurs if handle is identical to a context already registered with OpenTK.</exception>
public GraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags)
{
lock (SyncRoot)
{
IsExternal = true;
if (handle == ContextHandle.Zero)
{
implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);
}
else if (available_contexts.ContainsKey(handle))
{
throw new GraphicsContextException("Context already exists.");
}
else
{
switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded)
{
case false: implementation = Factory.Default.CreateGLContext(handle, window, shareContext, direct_rendering, major, minor, flags); break;
case true: implementation = Factory.Embedded.CreateGLContext(handle, window, shareContext, direct_rendering, major, minor, flags); break;
}
}
available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this));
(this as IGraphicsContextInternal).LoadAll();
}
}
#endregion
#region Public Members
/// <summary>
/// Returns a <see cref="System.String"/> representing this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that contains a string representation of this instance.</returns>
public override string ToString()
{
return (this as IGraphicsContextInternal).Context.ToString();
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A System.Int32 with the hash code of this instance.</returns>
public override int GetHashCode()
{
return (this as IGraphicsContextInternal).Context.GetHashCode();
}
/// <summary>
/// Compares two instances.
/// </summary>
/// <param name="obj">The instance to compare to.</param>
/// <returns>True, if obj is equal to this instance; false otherwise.</returns>
public override bool Equals(object obj)
{
return (obj is GraphicsContext) &&
(this as IGraphicsContextInternal).Context == (obj as IGraphicsContextInternal).Context;
}
#endregion
#region Private Members
static IGraphicsContext FindSharedContext()
{
if (GraphicsContext.ShareContexts)
{
// A small hack to create a shared context with the first available context.
foreach (WeakReference r in GraphicsContext.available_contexts.Values)
{
// Fix for bug 1874: if a GraphicsContext gets finalized
// (but not disposed), it won't be removed from available_contexts
// making this return null even if another valid context exists.
// The workaround is to simply ignore null targets.
IGraphicsContext target = r.Target as IGraphicsContext;
if (target != null)
return target;
}
}
return null;
}
#endregion
#region --- Static Members ---
#region public static GraphicsContext CreateDummyContext()
/// <summary>
/// Creates a dummy GraphicsContext to allow OpenTK to work with contexts created by external libraries.
/// </summary>
/// <returns>A new, dummy GraphicsContext instance.</returns>
/// <remarks>
/// <para>Instances created by this method will not be functional. Instance methods will have no effect.</para>
/// <para>This method requires that a context is current on the calling thread.</para>
/// </remarks>
public static GraphicsContext CreateDummyContext()
{
ContextHandle handle = GetCurrentContext();
if (handle == ContextHandle.Zero)
throw new InvalidOperationException("No GraphicsContext is current on the calling thread.");
return CreateDummyContext(handle);
}
/// <summary>
/// Creates a dummy GraphicsContext to allow OpenTK to work with contexts created by external libraries.
/// </summary>
/// <param name="handle">The handle of a context.</param>
/// <returns>A new, dummy GraphicsContext instance.</returns>
/// <remarks>
/// <para>Instances created by this method will not be functional. Instance methods will have no effect.</para>
/// </remarks>
public static GraphicsContext CreateDummyContext(ContextHandle handle)
{
if (handle == ContextHandle.Zero)
throw new ArgumentOutOfRangeException("handle");
return new GraphicsContext(handle);
}
#endregion
#region public static void Assert()
/// <summary>
/// Checks if a GraphicsContext exists in the calling thread and throws a GraphicsContextMissingException if it doesn't.
/// </summary>
/// <exception cref="GraphicsContextMissingException">Generated when no GraphicsContext is current in the calling thread.</exception>
public static void Assert()
{
if (GraphicsContext.CurrentContext == null)
throw new GraphicsContextMissingException();
}
#endregion
#region public static IGraphicsContext CurrentContext
internal delegate ContextHandle GetCurrentContextDelegate();
internal static GetCurrentContextDelegate GetCurrentContext =
Platform.Factory.Default.CreateGetCurrentGraphicsContext();
/// <summary>
/// Gets the GraphicsContext that is current in the calling thread.
/// </summary>
/// <remarks>
/// Note: this property will not function correctly when both desktop and EGL contexts are
/// available in the same process. This scenario is very unlikely to appear in practice.
/// </remarks>
public static IGraphicsContext CurrentContext
{
get
{
lock (SyncRoot)
{
if (available_contexts.Count > 0)
{
ContextHandle handle = GetCurrentContext();
if (handle.Handle != IntPtr.Zero)
return (GraphicsContext)available_contexts[handle].Target;
}
return null;
}
}
}
#endregion
#region public static bool ShareContexts
/// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContext resources are shared</summary>
/// <remarks>
/// <para>If ShareContexts is true, new GLContexts will share resources. If this value is
/// false, new GLContexts will not share resources.</para>
/// <para>Changing this value will not affect already created GLContexts.</para>
/// </remarks>
public static bool ShareContexts { get { return share_contexts; } set { share_contexts = value; } }
#endregion
#region public static bool DirectRendering
/// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContexts will perform direct rendering.</summary>
/// <remarks>
/// <para>
/// If DirectRendering is true, new contexts will be constructed with direct rendering capabilities, if possible.
/// If DirectRendering is false, new contexts will be constructed with indirect rendering capabilities.
/// </para>
/// <para>This property does not affect existing GraphicsContexts, unless they are recreated.</para>
/// <para>
/// This property is ignored on Operating Systems without support for indirect rendering, like Windows and OS X.
/// </para>
/// </remarks>
public static bool DirectRendering
{
get { return direct_rendering; }
set { direct_rendering = value; }
}
#endregion
#endregion
#region --- IGraphicsContext Members ---
/// <summary>
/// Gets or sets a System.Boolean, indicating whether automatic error checking should be performed.
/// Influences the debug version of OpenTK.dll, only.
/// </summary>
/// <remarks>Automatic error checking will clear the OpenGL error state. Set CheckErrors to false if you use
/// the OpenGL error state in your code flow (e.g. for checking supported texture formats).</remarks>
public bool ErrorChecking
{
get { return check_errors; }
set { check_errors = value; }
}
/// <summary>
/// Creates an OpenGL context with the specified direct/indirect rendering mode and sharing state with the
/// specified IGraphicsContext.
/// </summary>
/// <param name="direct">Set to true for direct rendering or false otherwise.</param>
/// <param name="source">The source IGraphicsContext to share state from.</param>.
/// <remarks>
/// <para>
/// Direct rendering is the default rendering mode for OpenTK, since it can provide higher performance
/// in some circumastances.
/// </para>
/// <para>
/// The 'direct' parameter is a hint, and will ignored if the specified mode is not supported (e.g. setting
/// indirect rendering on Windows platforms).
/// </para>
/// </remarks>
void CreateContext(bool direct, IGraphicsContext source)
{
lock (SyncRoot)
{
available_contexts.Add((this as IGraphicsContextInternal).Context, new WeakReference(this));
}
}
/// <summary>
/// Swaps buffers on a context. This presents the rendered scene to the user.
/// </summary>
public void SwapBuffers()
{
implementation.SwapBuffers();
}
/// <summary>
/// Makes the GraphicsContext the current rendering target.
/// </summary>
/// <param name="window">A valid <see cref="OpenTK.Platform.IWindowInfo" /> structure.</param>
/// <remarks>
/// You can use this method to bind the GraphicsContext to a different window than the one it was created from.
/// </remarks>
public void MakeCurrent(IWindowInfo window)
{
implementation.MakeCurrent(window);
}
/// <summary>
/// Gets a <see cref="System.Boolean"/> indicating whether this instance is current in the calling thread.
/// </summary>
public bool IsCurrent
{
get { return implementation.IsCurrent; }
}
/// <summary>
/// Gets a <see cref="System.Boolean"/> indicating whether this instance has been disposed.
/// It is an error to access any instance methods if this property returns true.
/// </summary>
public bool IsDisposed
{
get { return disposed && implementation.IsDisposed; }
private set { disposed = value; }
}
/// <summary>
/// [obsolete] Use SwapInterval property instead.
/// Gets or sets a value indicating whether VSync is enabled. When VSync is
/// enabled, <see cref="SwapBuffers()"/> calls will be synced to the refresh
/// rate of the <see cref="DisplayDevice"/> that contains improving visual
/// quality and reducing CPU usage. However, systems that cannot maintain
/// the requested rendering rate will suffer from large jumps in performance.
/// This can be counteracted by increasing the <see cref="SwapInterval"/>
/// value.
/// </summary>
[Obsolete("Use SwapInterval property instead.")]
public bool VSync
{
get { return implementation.VSync; }
set { implementation.VSync = value; }
}
/// <summary>
/// Gets or sets a positive integer in the range [1, n), indicating the number of
/// <see cref="DisplayDevice"/> refreshes between consecutive
/// <see cref="SwapBuffers()"/> calls. The maximum value for n is
/// implementation-dependent. The default value is 1.
/// This value will only affect instances where <see cref="VSync"/> is enabled.
/// Invalid values will be clamped to the valid range.
/// </summary>
public int SwapInterval
{
get { return implementation.SwapInterval; }
set { implementation.SwapInterval = value; }
}
/// <summary>
/// Updates the graphics context. This must be called when the render target
/// is resized for proper behavior on Mac OS X.
/// </summary>
/// <param name="window"></param>
public void Update(IWindowInfo window)
{
implementation.Update(window);
}
/// <summary>
/// Loads all OpenGL entry points.
/// </summary>
/// <exception cref="OpenTK.Graphics.GraphicsContextException">
/// Occurs when this instance is not current on the calling thread.
/// </exception>
public void LoadAll()
{
if (GraphicsContext.CurrentContext != this)
throw new GraphicsContextException();
implementation.LoadAll();
}
#endregion
#region --- IGraphicsContextInternal Members ---
/// <summary>
/// Gets the platform-specific implementation of this IGraphicsContext.
/// </summary>
IGraphicsContext IGraphicsContextInternal.Implementation
{
get { return implementation; }
}
/// <summary>
/// Gets a handle to the OpenGL rendering context.
/// </summary>
ContextHandle IGraphicsContextInternal.Context
{
get { return ((IGraphicsContextInternal)implementation).Context; }
}
/// <summary>
/// Gets the GraphicsMode of the context.
/// </summary>
public GraphicsMode GraphicsMode
{
get { return (implementation as IGraphicsContext).GraphicsMode; }
}
/// <summary>
/// Gets the address of an OpenGL extension function.
/// </summary>
/// <param name="function">The name of the OpenGL function (e.g. "glGetString")</param>
/// <returns>
/// A pointer to the specified function or IntPtr.Zero if the function isn't
/// available in the current opengl context.
/// </returns>
IntPtr IGraphicsContextInternal.GetAddress(string function)
{
return (implementation as IGraphicsContextInternal).GetAddress(function);
}
#endregion
#region --- IDisposable Members ---
/// <summary>
/// Disposes of the GraphicsContext.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool manual)
{
if (!IsDisposed)
{
Debug.Print("Disposing context {0}.", (this as IGraphicsContextInternal).Context.ToString());
lock (SyncRoot)
{
available_contexts.Remove((this as IGraphicsContextInternal).Context);
}
if (manual && !IsExternal)
{
if (implementation != null)
implementation.Dispose();
}
IsDisposed = true;
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SourceSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Dsl
{
public class SourceSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public SourceSpec(ITestOutputHelper helper) : base(helper)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void Single_Source_must_produce_element()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
c.ExpectComplete();
}
[Fact]
public void Single_Source_must_reject_later_subscriber()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(1);
c1.ExpectNext(1);
c1.ExpectComplete();
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Empty_Source_must_complete_immediately()
{
var p = Source.Empty<int>().RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
c.ExpectSubscriptionAndComplete();
//reject additional subscriber
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Failed_Source_must_emit_error_immediately()
{
var ex = new SystemException();
var p = Source.Failed<int>(ex).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c);
c.ExpectSubscriptionAndError();
//reject additional subscriber
var c2 = TestSubscriber.CreateManualProbe<int>(this);
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Maybe_Source_must_complete_materialized_future_with_None_when_stream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<object>();
var pubSink = Sink.AsPublisher<object>(false);
var t = neverSource.ToMaterialized(pubSink, Keep.Both).Run(Materializer);
var f = t.Item1;
var neverPub = t.Item2;
var c = TestSubscriber.CreateManualProbe<object>(this);
neverPub.Subscribe(c);
var subs = c.ExpectSubscription();
subs.Request(1000);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
subs.Cancel();
f.Task.Wait(500).Should().BeTrue();
f.Task.Result.Should().Be(null);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>().Where(_ => false);
var counterSink = Sink.Aggregate<int, int>(0, (acc, _) => acc + 1);
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(0).Should().BeTrue();
counterFuture.Wait(500).Should().BeTrue();
counterFuture.Result.Should().Be(0);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_non_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(6).Should().BeTrue();
counterFuture.Wait(500).Should().BeTrue();
counterFuture.Result.Should().Be(6);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_OnError()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.SetException(new Exception("Boom"));
counterFuture.Invoking(f => f.Wait(500)).ShouldThrow<Exception>()
.WithMessage("Boom");
}, Materializer);
}
[Fact]
public void Composite_Source_must_merge_from_many_inputs()
{
var probes = Enumerable.Range(1, 5).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = Source.AsSubscriber<int>();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
var s =
Source.FromGraph(GraphDsl.Create(source, source, source, source, source,
(a, b, c, d, e) => new[] {a, b, c, d, e},
(b, i0, i1, i2, i3, i4) =>
{
var m = b.Add(new Merge<int>(5));
b.From(i0.Outlet).To(m.In(0));
b.From(i1.Outlet).To(m.In(1));
b.From(i2.Outlet).To(m.In(2));
b.From(i3.Outlet).To(m.In(3));
b.From(i4.Outlet).To(m.In(4));
return new SourceShape<int>(m.Out);
})).To(Sink.FromSubscriber(outProbe)).Run(Materializer);
for (var i = 0; i < 5; i++)
probes[i].Subscribe(s[i]);
var sub = outProbe.ExpectSubscription();
sub.Request(10);
for (var i = 0; i < 5; i++)
{
var subscription = probes[i].ExpectSubscription();
subscription.ExpectRequest();
subscription.SendNext(i);
subscription.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 5; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2, 3, 4});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_many_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 3).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
Source.Combine(source[0], source[1], i => new Merge<int, int>(i), source[2])
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 3; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 3; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_two_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 2).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = TestSubscriber.CreateManualProbe<int>(this);
Source.Combine(source[0], source[1], i => new Merge<int, int>(i))
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 2; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 2; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1});
outProbe.ExpectComplete();
}
[Fact]
public void Repeat_Source_must_repeat_as_long_as_it_takes()
{
var f = Source.Repeat(42).Grouped(1000).RunWith(Sink.First<IEnumerable<int>>(), Materializer);
f.Result.Should().HaveCount(1000).And.Match(x => x.All(i => i == 42));
}
private static readonly int[] Expected = {
9227465, 5702887, 3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711,
10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0
};
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return null;
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_terminate_with_a_failure_if_there_is_an_exception_thrown()
{
EventFilter.Exception<SystemException>(message: "expected").ExpectOne(() =>
{
var task = Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
throw new SystemException("expected");
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<SystemException>()
.WithMessage("expected");
});
}
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence_asynchronously()
{
Source.UnfoldAsync(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return Task.FromResult<Tuple<Tuple<int, int>, int>>(null);
return Task.FromResult(Tuple.Create(Tuple.Create(b, a + b), a));
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_generate_a_unboundeed_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
return Tuple.Create(Tuple.Create(b, a + b), a);
})
.Take(36)
.RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Iterator_Source_must_properly_iterate()
{
var expected = new[] {false, true, false, true, false, true, false, true, false, true }.ToList();
Source.FromEnumerator(() => expected.GetEnumerator())
.Grouped(10)
.RunWith(Sink.First<IEnumerable<bool>>(), Materializer)
.Result.Should()
.Equal(expected);
}
[Fact]
public void A_Source_must_suitably_override_attribute_handling_methods()
{
Source.Single(42).Async().AddAttributes(Attributes.None).Named("");
}
}
}
| |
using System;
using System.Collections.Generic;
namespace CocosSharp
{
public delegate void CCFocusChangeDelegate(ICCFocusable prev, ICCFocusable current);
public class CCFocusManager
{
// Scrolling focus delay used to slow down automatic focus changes when the dpad is held.
public static float MenuScrollDelay = 50f;
static CCFocusManager instance = new CCFocusManager();
public event CCFocusChangeDelegate OnFocusChanged;
bool scrollingPrevious = false;
bool scrollingNext = false;
long timeOfLastFocus = 0L;
LinkedList<ICCFocusable> focusList = new LinkedList<ICCFocusable>();
LinkedListNode<ICCFocusable> current = null;
#region Properties
public static CCFocusManager Instance
{
get { return instance; }
}
// When false, the focus will not traverse on the keyboard or dpad events.
public bool Enabled { get; set; }
// Returns the item with the current focus. This test will create a copy
// of the master item list.
public ICCFocusable ItemWithFocus
{
get { return (current != null ? current.Value : null); }
}
#endregion Properties
#region Constructors
private CCFocusManager()
{
}
#endregion Constructors
// Removes the given focusable node
public void Remove(params ICCFocusable[] focusItems)
{
foreach (ICCFocusable f in focusItems)
{
focusList.Remove(f);
}
}
// Adds the given node to the list of focus nodes. If the node has the focus, then it is
// given the current focused item status. If there is already a focused item and the
// given node has focus, the focus is disabled.
public void Add(params ICCFocusable[] focusItems)
{
foreach (ICCFocusable f in focusItems)
{
LinkedListNode<ICCFocusable> i = focusList.AddLast(f);
if (f.HasFocus)
{
if (current == null)
{
current = i;
}
else
{
f.HasFocus = false;
}
}
}
}
// Scroll to the next item in the focus list.
public void FocusNextItem()
{
if (current == null && focusList.Count > 0)
{
current = focusList.First;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, current.Value);
}
}
else if (current != null)
{
ICCFocusable lostItem = current.Value;
// Search for the next node.
LinkedListNode<ICCFocusable> nextItem = null;
for (LinkedListNode<ICCFocusable> p = current.Next; p != null; p = p.Next)
{
if (p.Value.CanReceiveFocus)
{
nextItem = p;
}
}
if (nextItem != null)
{
current = nextItem;
}
else
{
current = focusList.First;
}
lostItem.HasFocus = false;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, current.Value);
}
}
else
{
current = null;
}
}
// Scroll to the previous item in the focus list.
public void FocusPreviousItem()
{
if (ItemWithFocus == null && focusList.Count > 0)
{
current = focusList.Last;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, current.Value);
}
}
else if (current != null)
{
ICCFocusable lostItem = current.Value;
// TODO: take a look at the commented out code it does not seem to do anything.
// LinkedListNode<ICCFocusable> nextItem = null;
// for (LinkedListNode<ICCFocusable> p = current.Previous; p != null; p = p.Previous)
// {
// if (p.Value.CanReceiveFocus)
// {
// nextItem = p;
// }
// }
if (current.Previous != null)
{
current = current.Previous;
}
else
{
current = focusList.Last;
}
lostItem.HasFocus = false;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, current.Value);
}
}
else
{
current = null;
}
}
void SharedApplication_GamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton,
CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player)
{
if (!Enabled)
{
return;
}
if (leftButton == CCGamePadButtonStatus.Released || upButton == CCGamePadButtonStatus.Released || rightButton == CCGamePadButtonStatus.Released || downButton == CCGamePadButtonStatus.Released)
{
scrollingPrevious = false;
timeOfLastFocus = 0L;
}
// Left and right d-pad shuffle through the menus
else if (leftButton == CCGamePadButtonStatus.Pressed || upButton == CCGamePadButtonStatus.Pressed)
{
if (scrollingPrevious)
{
TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - timeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusPreviousItem();
}
}
else
{
scrollingPrevious = true;
timeOfLastFocus = DateTime.UtcNow.Ticks;
}
}
else if (rightButton == CCGamePadButtonStatus.Pressed || downButton == CCGamePadButtonStatus.Pressed)
{
if (scrollingNext)
{
TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - timeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusNextItem();
}
}
else
{
scrollingNext = true;
timeOfLastFocus = DateTime.UtcNow.Ticks;
}
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.
//
// * Neither the name of Jaroslaw Kowalski 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.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
using System.Collections.Generic;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object lockObject = new object();
private Timer lazyWriterTimer;
private readonly Queue<AsyncContinuation> flushAllContinuations = new Queue<AsyncContinuation>();
private readonly object continuationQueueLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
this.TimeToSleepBetweenBatches = 50;
this.BatchSize = 100;
this.WrappedTarget = wrappedTarget;
this.QueueLimit = queueLimit;
this.OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return this.RequestQueue.OnOverflow; }
set { this.RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return this.RequestQueue.RequestLimit; }
set { this.RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Waits for the lazy writer thread to finish writing messages.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
lock (continuationQueueLock)
{
this.flushAllContinuations.Enqueue(asyncContinuation);
}
}
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
if (this.TimeToSleepBetweenBatches <= 0) {
throw new NLogConfigurationException("The AysncTargetWrapper\'s TimeToSleepBetweenBatches property must be > 0");
}
base.InitializeTarget();
this.RequestQueue.Clear();
InternalLogger.Trace("AsyncWrapper '{0}': start timer", Name);
this.lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
this.StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
this.StopLazyWriterThread();
if (this.RequestQueue.RequestCount > 0)
{
ProcessPendingEvents(null);
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
/// <summary>
/// Stops the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.lazyWriterTimer = null;
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.MergeEventProperties(logEvent.LogEvent);
this.PrecalculateVolatileLayouts(logEvent.LogEvent);
this.RequestQueue.Enqueue(logEvent);
}
private void ProcessPendingEvents(object state)
{
AsyncContinuation[] continuations;
lock (this.continuationQueueLock)
{
continuations = this.flushAllContinuations.Count > 0
? this.flushAllContinuations.ToArray()
: new AsyncContinuation[] { null };
this.flushAllContinuations.Clear();
}
try
{
if (this.WrappedTarget == null)
{
InternalLogger.Error("AsyncWrapper '{0}': WrappedTarget is NULL", Name);
return;
}
foreach (var continuation in continuations)
{
int count = this.BatchSize;
if (continuation != null)
{
count = this.RequestQueue.RequestCount;
}
InternalLogger.Trace("AsyncWrapper '{0}': Flushing {1} events.", Name, count);
if (this.RequestQueue.RequestCount == 0)
{
if (continuation != null)
{
continuation(null);
}
}
AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count);
if (continuation != null)
{
// write all events, then flush, then call the continuation
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation));
}
else
{
// just write all events
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos);
}
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in lazy writer timer procedure.", Name);
if (exception.MustBeRethrown())
{
throw;
}
}
finally
{
this.StartLazyWriterTimer();
}
}
}
}
| |
// 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 Xunit;
using System.Text;
using System.Linq;
using System.Globalization;
namespace System.Buffers.Text.Tests
{
public static partial class ParserTests
{
private static void ValidateParser<T>(ParserTestData<T> testData)
{
ValidateParserHelper(testData);
if (testData.ExpectedSuccess)
{
// Add several bytes of junk after the real text to ensure the parser successfully ignores it. By adding lots of junk, this also
// exercises the "string is too long to rule out overflow based on length" paths of the integer parsers.
ParserTestData<T> testDataWithExtraCharacter = new ParserTestData<T>(testData.Text + "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$", testData.ExpectedValue, testData.FormatSymbol, expectedSuccess: true)
{
ExpectedBytesConsumed = testData.ExpectedBytesConsumed
};
ValidateParserHelper(testDataWithExtraCharacter);
}
}
private static void ValidateParserHelper<T>(ParserTestData<T> testData)
{
ReadOnlySpan<byte> utf8Text = testData.Text.ToUtf8Span();
bool success = TryParseUtf8<T>(utf8Text, out T value, out int bytesConsumed, testData.FormatSymbol);
if (testData.ExpectedSuccess)
{
if (!success)
throw new TestException($"This parse attempt {testData} was expected to succeed: instead, it failed.");
T expected = testData.ExpectedValue;
T actual = value;
if (!IsParsedValueEqual<T>(expected: expected, actual: actual))
{
string expectedString = expected.DisplayString();
string actualString = actual.DisplayString();
throw new TestException($"This parse attempt {testData} succeeded as expected but parsed to the wrong value:\n Expected: {expectedString}\n Actual: {actualString}\n");
}
int expectedBytesConsumed = testData.ExpectedBytesConsumed;
if (expectedBytesConsumed != bytesConsumed)
throw new TestException($"This parse attempt {testData} returned the correct value but the wrong `bytesConsumed` value:\n Expected: {expectedBytesConsumed}\n Actual: {bytesConsumed}\n");
}
else
{
if (success)
throw new TestException($"This parse attempt {testData} was expected to fail: instead, it succeeded and returned {value}.");
if (bytesConsumed != 0)
throw new TestException($"This parse attempt {testData} failed as expected but did not set `bytesConsumed` to 0");
if (!(value.Equals(default(T))))
throw new TestException($"This parse attempt {testData} failed as expected but did not set `value` to default(T)");
}
}
private static bool IsParsedValueEqual<T>(T expected, T actual)
{
if (typeof(T) == typeof(decimal))
{
int[] expectedBits = decimal.GetBits((decimal)(object)expected);
int[] actualBits = decimal.GetBits((decimal)(object)actual);
if (!expectedBits.SequenceEqual(actualBits))
{
// Do not simplify into "return expectedBits.SequenceEqual()". I want to be able to put a breakpoint here.
return false;
}
return true;
}
if (typeof(T) == typeof(DateTime))
{
DateTime expectedDateTime = (DateTime)(object)expected;
DateTime actualDateTime = (DateTime)(object)actual;
if (expectedDateTime.Kind != actualDateTime.Kind)
return false;
if (expectedDateTime.Ticks != actualDateTime.Ticks)
return false;
return true;
}
if (typeof(T) == typeof(DateTimeOffset))
{
DateTimeOffset expectedDateTimeOffset = (DateTimeOffset)(object)expected;
DateTimeOffset actualDateTimeOffset = (DateTimeOffset)(object)actual;
if (expectedDateTimeOffset.Offset != actualDateTimeOffset.Offset)
return false;
if (!IsParsedValueEqual<DateTime>(expectedDateTimeOffset.DateTime, actualDateTimeOffset.DateTime))
return false;
return true;
}
// Parsed floating points are constructed, not computed. Thus, we can do the exact compare.
if (typeof(T) == typeof(double))
{
double expectedDouble = (double)(object)expected;
double actualDouble = (double)(object)actual;
unsafe
{
if (*((ulong*)&expectedDouble) != *((ulong*)&actualDouble))
return false;
return true;
}
}
// Parsed floating points are constructed, not computed. Thus, we can do the exact compare.
if (typeof(T) == typeof(float))
{
float expectedSingle = (float)(object)expected;
float actualSingle = (float)(object)actual;
unsafe
{
if (*((uint*)&expectedSingle) != *((uint*)&actualSingle))
return false;
return true;
}
}
return expected.Equals(actual);
}
private static bool TryParseUtf8<T>(ReadOnlySpan<byte> text, out T value, out int bytesConsumed, char format)
{
if (typeof(T) == typeof(bool))
{
bool success = Utf8Parser.TryParse(text, out bool v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(sbyte))
{
bool success = Utf8Parser.TryParse(text, out sbyte v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(byte))
{
bool success = Utf8Parser.TryParse(text, out byte v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(short))
{
bool success = Utf8Parser.TryParse(text, out short v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(ushort))
{
bool success = Utf8Parser.TryParse(text, out ushort v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(int))
{
bool success = Utf8Parser.TryParse(text, out int v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(uint))
{
bool success = Utf8Parser.TryParse(text, out uint v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(long))
{
bool success = Utf8Parser.TryParse(text, out long v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(ulong))
{
bool success = Utf8Parser.TryParse(text, out ulong v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(decimal))
{
bool success = Utf8Parser.TryParse(text, out decimal v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(Guid))
{
bool success = Utf8Parser.TryParse(text, out Guid v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(float))
{
bool success = Utf8Parser.TryParse(text, out float v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(double))
{
bool success = Utf8Parser.TryParse(text, out double v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(DateTime))
{
bool success = Utf8Parser.TryParse(text, out DateTime v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(DateTimeOffset))
{
bool success = Utf8Parser.TryParse(text, out DateTimeOffset v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
if (typeof(T) == typeof(TimeSpan))
{
bool success = Utf8Parser.TryParse(text, out TimeSpan v, out bytesConsumed, format);
value = (T)(object)v;
return success;
}
throw new Exception("Unsupported type " + typeof(T));
}
private static bool TryParseUtf8(Type type, ReadOnlySpan<byte> text, out object value, out int bytesConsumed, char format)
{
if (type == typeof(bool))
{
bool success = Utf8Parser.TryParse(text, out bool v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(sbyte))
{
bool success = Utf8Parser.TryParse(text, out sbyte v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(byte))
{
bool success = Utf8Parser.TryParse(text, out byte v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(short))
{
bool success = Utf8Parser.TryParse(text, out short v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(ushort))
{
bool success = Utf8Parser.TryParse(text, out ushort v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(int))
{
bool success = Utf8Parser.TryParse(text, out int v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(uint))
{
bool success = Utf8Parser.TryParse(text, out uint v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(long))
{
bool success = Utf8Parser.TryParse(text, out long v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(ulong))
{
bool success = Utf8Parser.TryParse(text, out ulong v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(decimal))
{
bool success = Utf8Parser.TryParse(text, out decimal v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(Guid))
{
bool success = Utf8Parser.TryParse(text, out Guid v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(float))
{
bool success = Utf8Parser.TryParse(text, out float v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(double))
{
bool success = Utf8Parser.TryParse(text, out double v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(DateTime))
{
bool success = Utf8Parser.TryParse(text, out DateTime v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(DateTimeOffset))
{
bool success = Utf8Parser.TryParse(text, out DateTimeOffset v, out bytesConsumed, format);
value = v;
return success;
}
if (type == typeof(TimeSpan))
{
bool success = Utf8Parser.TryParse(text, out TimeSpan v, out bytesConsumed, format);
value = v;
return success;
}
throw new Exception("Unsupported type " + type);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014-2015 Charlie Poole, Rob Prouse
//
// 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 NUnit.Framework.Interfaces;
namespace NUnitLite
{
/// <summary>
/// Helper class used to summarize the result of a test run
/// </summary>
public class ResultSummary
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ResultSummary"/> class.
/// </summary>
/// <param name="result">The result.</param>
public ResultSummary(ITestResult result)
{
InitializeCounters();
ResultState = result.ResultState;
StartTime = result.StartTime;
EndTime = result.EndTime;
Duration = result.Duration;
Summarize(result);
}
#endregion
#region Properties
/// <summary>
/// Gets the number of test cases for which results
/// have been summarized. Any tests excluded by use of
/// Category or Explicit attributes are not counted.
/// </summary>
public int TestCount { get; private set; }
/// <summary>
/// Returns the number of test cases actually run.
/// </summary>
public int RunCount
{
get { return PassCount + ErrorCount + FailureCount + InconclusiveCount; }
}
/// <summary>
/// Gets the number of tests not run for any reason.
/// </summary>
public int NotRunCount
{
get { return InvalidCount + SkipCount + IgnoreCount + ExplicitCount; }
}
/// <summary>
/// Returns the number of failed test cases (including errors and invalid tests)
/// </summary>
public int FailedCount
{
get { return FailureCount + InvalidCount + ErrorCount; }
}
/// <summary>
/// Returns the sum of skipped test cases, including ignored and explicit tests
/// </summary>
public int TotalSkipCount
{
get { return SkipCount + IgnoreCount + ExplicitCount; }
}
/// <summary>
/// Gets the count of passed tests
/// </summary>
public int PassCount { get; private set; }
/// <summary>
/// Gets count of failed tests, excluding errors and invalid tests
/// </summary>
public int FailureCount { get; private set; }
/// <summary>
/// Gets count of tests with warnings
/// </summary>
public int WarningCount { get; private set; }
/// <summary>
/// Gets the error count
/// </summary>
public int ErrorCount { get; private set; }
/// <summary>
/// Gets the count of inconclusive tests
/// </summary>
public int InconclusiveCount { get; private set; }
/// <summary>
/// Returns the number of test cases that were not runnable
/// due to errors in the signature of the class or method.
/// Such tests are also counted as Errors.
/// </summary>
public int InvalidCount { get; private set; }
/// <summary>
/// Gets the count of skipped tests, excluding ignored tests
/// </summary>
public int SkipCount { get; private set; }
/// <summary>
/// Gets the ignore count
/// </summary>
public int IgnoreCount { get; private set; }
/// <summary>
/// Gets the explicit count
/// </summary>
public int ExplicitCount { get; private set; }
/// <summary>
/// Invalid Test Fixtures
/// </summary>
public int InvalidTestFixtures { get; private set; }
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState { get; private set; }
/// <summary>
/// Gets or sets the time the test started running.
/// </summary>
public DateTime StartTime { get; private set; }
/// <summary>
/// Gets or sets the time the test finished running.
/// </summary>
public DateTime EndTime { get; private set; }
/// <summary>
/// Gets or sets the elapsed time for running the test in seconds
/// </summary>
public double Duration { get; private set; }
#endregion
#region Helper Methods
private void InitializeCounters()
{
TestCount = 0;
PassCount = 0;
FailureCount = 0;
WarningCount = 0;
ErrorCount = 0;
InconclusiveCount = 0;
SkipCount = 0;
IgnoreCount = 0;
ExplicitCount = 0;
InvalidCount = 0;
}
private void Summarize(ITestResult result)
{
var label = result.ResultState.Label;
var status = result.ResultState.Status;
if (result.Test.IsSuite)
{
if (status == TestStatus.Failed && label == "Invalid")
InvalidTestFixtures++;
foreach (ITestResult r in result.Children)
Summarize(r);
}
else
{
TestCount++;
switch (status)
{
case TestStatus.Passed:
PassCount++;
break;
case TestStatus.Skipped:
if (label == "Ignored")
IgnoreCount++;
else if (label == "Explicit")
ExplicitCount++;
else
SkipCount++;
break;
case TestStatus.Warning:
WarningCount++; // This is not actually used by the nunit 2 format
break;
case TestStatus.Failed:
if (label == "Invalid")
InvalidCount++;
else if (label == "Error")
ErrorCount++;
else
FailureCount++;
break;
case TestStatus.Inconclusive:
InconclusiveCount++;
break;
}
return;
}
}
#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.Text;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
public enum DomainMode : int
{
Unknown = -1,
Windows2000MixedDomain = 0, // win2000, win2003, NT
Windows2000NativeDomain = 1, // win2000, win2003
Windows2003InterimDomain = 2, // win2003, NT
Windows2003Domain = 3, // win2003
Windows2008Domain = 4, // win2008
Windows2008R2Domain = 5, // win2008 R2
Windows8Domain = 6, //Windows Server 2012
Windows2012R2Domain = 7, //Windows Server 2012 R2
}
public class Domain : ActiveDirectoryPartition
{
/// Private Variables
private string _crossRefDN = null;
private string _trustParent = null;
// internal variables corresponding to public properties
private DomainControllerCollection _cachedDomainControllers = null;
private DomainCollection _cachedChildren = null;
private DomainMode _currentDomainMode = (DomainMode)(-1);
private int _domainModeLevel = -1;
private DomainController _cachedPdcRoleOwner = null;
private DomainController _cachedRidRoleOwner = null;
private DomainController _cachedInfrastructureRoleOwner = null;
private Domain _cachedParent = null;
private Forest _cachedForest = null;
// this is needed because null value for parent is valid
private bool _isParentInitialized = false;
#region constructors
// internal constructors
internal Domain(DirectoryContext context, string domainName, DirectoryEntryManager directoryEntryMgr)
: base(context, domainName)
{
this.directoryEntryMgr = directoryEntryMgr;
}
internal Domain(DirectoryContext context, string domainName)
: this(context, domainName, new DirectoryEntryManager(context))
{
}
#endregion constructors
#region public methods
public static Domain GetDomain(DirectoryContext context)
{
// check that the argument is not null
if (context == null)
throw new ArgumentNullException(nameof(context));
// contexttype should be Domain or DirectoryServer
if ((context.ContextType != DirectoryContextType.Domain) &&
(context.ContextType != DirectoryContextType.DirectoryServer))
{
throw new ArgumentException(SR.TargetShouldBeServerORDomain, nameof(context));
}
if ((context.Name == null) && (!context.isDomain()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(Domain), null);
}
if (context.Name != null)
{
// the target should be a valid domain name or a server
if (!((context.isDomain()) || (context.isServer())))
{
if (context.ContextType == DirectoryContextType.Domain)
{
throw new ActiveDirectoryObjectNotFoundException(SR.DomainNotFound, typeof(Domain), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
}
}
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootDSE of the domain specified in the context
// and get the dns name
DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry rootDSE = null;
string defaultDomainNC = null;
try
{
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
defaultDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DefaultNamingContext);
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
if (context.ContextType == DirectoryContextType.Domain)
{
throw new ActiveDirectoryObjectNotFoundException(SR.DomainNotFound, typeof(Domain), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
// return domain object
return new Domain(context, Utils.GetDnsNameFromDN(defaultDomainNC), directoryEntryMgr);
}
public static Domain GetComputerDomain()
{
string computerDomainName = DirectoryContext.GetDnsDomainName(null);
if (computerDomainName == null)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ComputerNotJoinedToDomain, typeof(Domain), null);
}
return Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, computerDomainName));
}
public void RaiseDomainFunctionalityLevel(int domainMode)
{
int existingDomainModeLevel;
CheckIfDisposed();
// check if domainMode is within the valid range
if (domainMode < 0)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
// get the current domain mode
existingDomainModeLevel = DomainModeLevel;
if (existingDomainModeLevel >= domainMode)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
DomainMode existingDomainMode = DomainMode;
// set the forest mode on AD
DirectoryEntry domainEntry = null;
// CurrentDomain Valid domainMode Action
// -----------------
// Windows2000Mixed 0 ntMixedDomain = 0 msDS-Behavior-Version = 0
// Windows2000Mixed 1 msDS-Behavior-Version = 1
// Windows2000Mixed 2 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2003Interim 2 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Rest 2 or above msDS-Behavior-Version = domainMode
try
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
// set the new functional level
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = domainMode;
switch (existingDomainMode)
{
case DomainMode.Windows2000MixedDomain:
{
if (domainMode == 2 || domainMode == 0)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else if (domainMode > 2) // new level should be less than or equal to Windows2003
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2003InterimDomain:
{
if (domainMode == 2) // only Windows2003 allowed
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
default:
break;
}
// NOTE:
// If the domain controller we are talking to is W2K
// (more specifically the schema is a W2K schema) then the
// msDS-Behavior-Version attribute will not be present.
// If that is the case, the domain functionality cannot be raised
// to Windows2003InterimDomain or Windows2003Domain (which is when we would set this attribute)
// since there are only W2K domain controllers
// So, we catch that exception and throw a more meaningful one.
domainEntry.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007200A))
{
// attribute does not exist which means this is not a W2K3 DC
// cannot raise domain functionality
throw new ArgumentException(SR.NoW2K3DCs, nameof(domainMode));
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
// at this point the raise domain function has succeeded
// invalidate the domain mode so that we get it from the server the next time
_currentDomainMode = (DomainMode)(-1);
_domainModeLevel = -1;
}
public void RaiseDomainFunctionality(DomainMode domainMode)
{
DomainMode existingDomainMode;
CheckIfDisposed();
// check if domain mode is within the valid range
if (domainMode < DomainMode.Windows2000MixedDomain || domainMode > DomainMode.Windows2012R2Domain)
{
throw new InvalidEnumArgumentException(nameof(domainMode), (int)domainMode, typeof(DomainMode));
}
// get the current domain mode
existingDomainMode = GetDomainMode();
// set the forest mode on AD
DirectoryEntry domainEntry = null;
// CurrentDomain Valid RequestedDomain Action
// -----------------
// Windows2000Mixed Windows2000Native ntMixedDomain = 0
// Windows2000Mixed Windows2003Interim msDS-Behavior-Version = 1
// Windows2000Mixed Windows2003 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2003Interim Windows2003 ntMixedDomain = 0, msDS-Behavior-Version = 2
//
// Windows2000Native Windows2003 or above
// Windows2003 Windows2008 or above
// Windows2008 Windows2008R2 or above
// Windows2008R2 Windows2012 or above
// Windows2012 Windows2012R2 or above
// Windows2012R2 ERROR
try
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
switch (existingDomainMode)
{
case DomainMode.Windows2000MixedDomain:
{
if (domainMode == DomainMode.Windows2000NativeDomain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
}
else if (domainMode == DomainMode.Windows2003InterimDomain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 1;
}
else if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2003InterimDomain:
{
if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.NTMixedDomain].Value = 0;
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
break;
}
case DomainMode.Windows2000NativeDomain:
case DomainMode.Windows2003Domain:
case DomainMode.Windows2008Domain:
case DomainMode.Windows2008R2Domain:
case DomainMode.Windows8Domain:
case DomainMode.Windows2012R2Domain:
{
if (existingDomainMode >= domainMode)
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
if (domainMode == DomainMode.Windows2003Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 2;
}
else if (domainMode == DomainMode.Windows2008Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 3;
}
else if (domainMode == DomainMode.Windows2008R2Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 4;
}
else if (domainMode == DomainMode.Windows8Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 5;
}
else if (domainMode == DomainMode.Windows2012R2Domain)
{
domainEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = 6;
}
else
{
throw new ArgumentException(SR.InvalidMode, nameof(domainMode));
}
}
break;
default:
{
// should not happen
throw new ActiveDirectoryOperationException();
}
}
// NOTE:
// If the domain controller we are talking to is W2K
// (more specifically the schema is a W2K schema) then the
// msDS-Behavior-Version attribute will not be present.
// If that is the case, the domain functionality cannot be raised
// to Windows2003InterimDomain or Windows2003Domain (which is when we would set this attribute)
// since there are only W2K domain controllers
// So, we catch that exception and throw a more meaningful one.
domainEntry.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007200A))
{
// attribute does not exist which means this is not a W2K3 DC
// cannot raise domain functionality
throw new ArgumentException(SR.NoW2K3DCs, nameof(domainMode));
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
// at this point the raise domain function has succeeded
// invalidate the domain mode so that we get it from the server the next time
_currentDomainMode = (DomainMode)(-1);
_domainModeLevel = -1;
}
public DomainController FindDomainController()
{
CheckIfDisposed();
return DomainController.FindOneInternal(context, Name, null, 0);
}
public DomainController FindDomainController(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindOneInternal(context, Name, siteName, 0);
}
public DomainController FindDomainController(LocatorOptions flag)
{
CheckIfDisposed();
return DomainController.FindOneInternal(context, Name, null, flag);
}
public DomainController FindDomainController(string siteName, LocatorOptions flag)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindOneInternal(context, Name, siteName, flag);
}
public DomainControllerCollection FindAllDomainControllers()
{
CheckIfDisposed();
return DomainController.FindAllInternal(context, Name, true /*isDnsDomainName */, null);
}
public DomainControllerCollection FindAllDomainControllers(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return DomainController.FindAllInternal(context, Name, true /*isDnsDomainName */, siteName);
}
public DomainControllerCollection FindAllDiscoverableDomainControllers()
{
long flag = (long)PrivateLocatorFlags.DSWriteableRequired;
CheckIfDisposed();
return new DomainControllerCollection(Locator.EnumerateDomainControllers(context, Name, null, (long)flag));
}
public DomainControllerCollection FindAllDiscoverableDomainControllers(string siteName)
{
long flag = (long)PrivateLocatorFlags.DSWriteableRequired;
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
if (siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
return new DomainControllerCollection(Locator.EnumerateDomainControllers(context, Name, siteName, (long)flag));
}
public override DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
return DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
}
public TrustRelationshipInformationCollection GetAllTrustRelationships()
{
CheckIfDisposed();
ArrayList trusts = GetTrustsHelper(null);
TrustRelationshipInformationCollection collection = new TrustRelationshipInformationCollection(context, Name, trusts);
return collection;
}
public TrustRelationshipInformation GetTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
ArrayList trusts = GetTrustsHelper(targetDomainName);
TrustRelationshipInformationCollection collection = new TrustRelationshipInformationCollection(context, Name, trusts);
if (collection.Count == 0)
{
// trust relationship does not exist
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , Name, targetDomainName), typeof(TrustRelationshipInformation), null);
}
else
{
Debug.Assert(collection.Count == 1);
return collection[0];
}
}
public bool GetSelectiveAuthenticationStatus(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
return TrustHelper.GetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, false);
}
public void SetSelectiveAuthenticationStatus(string targetDomainName, bool enable)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.SetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, enable, false);
}
public bool GetSidFilteringStatus(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
return TrustHelper.GetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN, false);
}
public void SetSidFilteringStatus(string targetDomainName, bool enable)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.SetTrustedDomainInfoStatus(context, Name, targetDomainName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN, enable, false);
}
public void DeleteLocalSideOfTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
// delete local side of trust only
TrustHelper.DeleteTrust(context, Name, targetDomainName, false);
}
public void DeleteTrustRelationship(Domain targetDomain)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
// first delete the trust on the remote side
TrustHelper.DeleteTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false);
// then delete the local side trust
TrustHelper.DeleteTrust(context, Name, targetDomain.Name, false);
}
public void VerifyOutboundTrustRelationship(string targetDomainName)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
TrustHelper.VerifyTrust(context, Name, targetDomainName, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
public void VerifyTrustRelationship(Domain targetDomain, TrustDirection direction)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
try
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
try
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false/*not forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
public void CreateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection direction, string trustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
if (trustPassword == null)
throw new ArgumentNullException(nameof(trustPassword));
if (trustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(trustPassword));
// verify first that the target domain name is valid
Locator.GetDomainControllerInfo(null, targetDomainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired);
DirectoryContext targetContext = Utils.GetNewDirectoryContext(targetDomainName, DirectoryContextType.Domain, context);
TrustHelper.CreateTrust(context, Name, targetContext, targetDomainName, false, direction, trustPassword);
}
public void CreateTrustRelationship(Domain targetDomain, TrustDirection direction)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
string password = TrustHelper.CreateTrustPassword();
// first create trust on local side
TrustHelper.CreateTrust(context, Name, targetDomain.GetDirectoryContext(), targetDomain.Name, false, direction, password);
// then create trust on remote side
int reverseDirection = 0;
if ((direction & TrustDirection.Inbound) != 0)
reverseDirection |= (int)TrustDirection.Outbound;
if ((direction & TrustDirection.Outbound) != 0)
reverseDirection |= (int)TrustDirection.Inbound;
TrustHelper.CreateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, context, Name, false, (TrustDirection)reverseDirection, password);
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, string newTrustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrust(context, Name, targetDomainName, newTrustPassword, false);
}
public void UpdateLocalSideOfTrustRelationship(string targetDomainName, TrustDirection newTrustDirection, string newTrustPassword)
{
CheckIfDisposed();
if (targetDomainName == null)
throw new ArgumentNullException(nameof(targetDomainName));
if (targetDomainName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetDomainName));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrustDirection(context, Name, targetDomainName, newTrustPassword, false /*not a forest*/, newTrustDirection);
}
public void UpdateTrustRelationship(Domain targetDomain, TrustDirection newTrustDirection)
{
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
// no we generate trust password
string password = TrustHelper.CreateTrustPassword();
TrustHelper.UpdateTrustDirection(context, Name, targetDomain.Name, password, false /* not a forest */, newTrustDirection);
// then create trust on remote side
TrustDirection reverseDirection = 0;
if ((newTrustDirection & TrustDirection.Inbound) != 0)
reverseDirection |= TrustDirection.Outbound;
if ((newTrustDirection & TrustDirection.Outbound) != 0)
reverseDirection |= TrustDirection.Inbound;
TrustHelper.UpdateTrustDirection(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false /* not a forest */, reverseDirection);
}
public void RepairTrustRelationship(Domain targetDomain)
{
TrustDirection direction = TrustDirection.Bidirectional;
CheckIfDisposed();
if (targetDomain == null)
throw new ArgumentNullException(nameof(targetDomain));
// first try to reset the secure channel
try
{
direction = GetTrustRelationship(targetDomain.Name).TrustDirection;
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, null /* no need to go to specific server*/);
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, null /* no need to go to specific server*/);
}
}
catch (ActiveDirectoryOperationException)
{
// secure channel setup fails
RepairTrustHelper(targetDomain, direction);
}
catch (UnauthorizedAccessException)
{
// trust password does not match
RepairTrustHelper(targetDomain, direction);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
public static Domain GetCurrentDomain()
{
return Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain));
}
#endregion public methods
#region public properties
public Forest Forest
{
get
{
CheckIfDisposed();
if (_cachedForest == null)
{
// get the name of rootDomainNamingContext
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
string rootDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.RootDomainNamingContext);
string forestName = Utils.GetDnsNameFromDN(rootDomainNC);
DirectoryContext forestContext = Utils.GetNewDirectoryContext(forestName, DirectoryContextType.Forest, context);
_cachedForest = new Forest(forestContext, forestName);
}
return _cachedForest;
}
}
public DomainControllerCollection DomainControllers
{
get
{
CheckIfDisposed();
if (_cachedDomainControllers == null)
{
_cachedDomainControllers = FindAllDomainControllers();
}
return _cachedDomainControllers;
}
}
public DomainCollection Children
{
get
{
CheckIfDisposed();
if (_cachedChildren == null)
{
_cachedChildren = new DomainCollection(GetChildDomains());
}
return _cachedChildren;
}
}
public DomainMode DomainMode
{
get
{
CheckIfDisposed();
if ((int)_currentDomainMode == -1)
{
_currentDomainMode = GetDomainMode();
}
return _currentDomainMode;
}
}
public int DomainModeLevel
{
get
{
CheckIfDisposed();
if (_domainModeLevel == -1)
{
_domainModeLevel = GetDomainModeLevel();
}
return _domainModeLevel;
}
}
public Domain Parent
{
get
{
CheckIfDisposed();
if (!_isParentInitialized)
{
_cachedParent = GetParent();
_isParentInitialized = true;
}
return _cachedParent;
}
}
public DomainController PdcRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedPdcRoleOwner == null)
{
_cachedPdcRoleOwner = GetRoleOwner(ActiveDirectoryRole.PdcRole);
}
return _cachedPdcRoleOwner;
}
}
public DomainController RidRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedRidRoleOwner == null)
{
_cachedRidRoleOwner = GetRoleOwner(ActiveDirectoryRole.RidRole);
}
return _cachedRidRoleOwner;
}
}
public DomainController InfrastructureRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedInfrastructureRoleOwner == null)
{
_cachedInfrastructureRoleOwner = GetRoleOwner(ActiveDirectoryRole.InfrastructureRole);
}
return _cachedInfrastructureRoleOwner;
}
}
#endregion public properties
#region private methods
internal DirectoryContext GetDirectoryContext() => context;
private int GetDomainModeLevel()
{
DirectoryEntry domainEntry = null;
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
int domainFunctionality = 0;
try
{
if (rootDSE.Properties.Contains(PropertyManager.DomainFunctionality))
{
domainFunctionality = int.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DomainFunctionality), NumberFormatInfo.InvariantInfo);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE.Dispose();
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
return domainFunctionality;
}
private DomainMode GetDomainMode()
{
// logic to check the domain mode
// if domainFunctionality is 0,
// then check ntMixedDomain to differentiate between
// Windows2000Native and Windows2000Mixed
// if domainFunctionality is 1 ==> Windows2003Interim
// if domainFunctionality is 2 ==> Windows2003
// if domainFunctionality is 3 ==> Windows2008
// if domainFunctionality is 4 ==> Windows2008R2
// if domainFunctionality is 5 ==> Windows2012
// if domainFunctionality is 6 ==> Windows2012R2
DomainMode domainMode;
DirectoryEntry domainEntry = null;
int domainFunctionality = DomainModeLevel;
try
{
// If the "domainFunctionality" attribute is not set on the rootdse, then
// this is a W2K domain (with W2K schema) so just check for mixed or native
switch (domainFunctionality)
{
case 0:
{
domainEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
int ntMixedDomain = (int)PropertyManager.GetPropertyValue(context, domainEntry, PropertyManager.NTMixedDomain);
if (ntMixedDomain == 0)
{
domainMode = DomainMode.Windows2000NativeDomain;
}
else
{
domainMode = DomainMode.Windows2000MixedDomain;
}
break;
}
case 1:
domainMode = DomainMode.Windows2003InterimDomain;
break;
case 2:
domainMode = DomainMode.Windows2003Domain;
break;
case 3:
domainMode = DomainMode.Windows2008Domain;
break;
case 4:
domainMode = DomainMode.Windows2008R2Domain;
break;
case 5:
domainMode = DomainMode.Windows8Domain;
break;
case 6:
domainMode = DomainMode.Windows2012R2Domain;
break;
default:
// unrecognized domain mode
domainMode = DomainMode.Unknown;
break;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (domainEntry != null)
{
domainEntry.Dispose();
}
}
return domainMode;
}
/// <returns>Returns a DomainController object for the DC that holds the specified FSMO role</returns>
private DomainController GetRoleOwner(ActiveDirectoryRole role)
{
DirectoryEntry entry = null;
string dcName = null;
try
{
switch (role)
{
case ActiveDirectoryRole.PdcRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext));
break;
}
case ActiveDirectoryRole.RidRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RidManager));
break;
}
case ActiveDirectoryRole.InfrastructureRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.Infrastructure));
break;
}
default:
// should not happen since we are calling this only internally
Debug.Fail("Domain.GetRoleOwner: Invalid role type.");
break;
}
dcName = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, entry, PropertyManager.FsmoRoleOwner));
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (entry != null)
{
entry.Dispose();
}
}
// create a new context object for the domain controller passing on the
// credentials from the domain context
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
return new DomainController(dcContext, dcName);
}
private void LoadCrossRefAttributes()
{
DirectoryEntry partitionsEntry = null;
try
{
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// now within the partitions container search for the
// crossRef object that has it's "dnsRoot" attribute equal to the
// dns name of the current domain
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append(")(");
str.Append(PropertyManager.DnsRoot);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(partitionName));
str.Append("))");
string filter = str.ToString();
string[] propertiesToLoad = new string[2];
propertiesToLoad[0] = PropertyManager.DistinguishedName;
propertiesToLoad[1] = PropertyManager.TrustParent;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/);
SearchResult res = searcher.FindOne();
_crossRefDN = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DistinguishedName);
// "trustParent" attribute may not be set
if (res.Properties[PropertyManager.TrustParent].Count > 0)
{
_trustParent = (string)res.Properties[PropertyManager.TrustParent][0];
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (partitionsEntry != null)
{
partitionsEntry.Dispose();
}
}
}
private Domain GetParent()
{
if (_crossRefDN == null)
{
LoadCrossRefAttributes();
}
if (_trustParent != null)
{
DirectoryEntry parentCrossRef = DirectoryEntryManager.GetDirectoryEntry(context, _trustParent);
string parentDomainName = null;
DirectoryContext domainContext = null;
try
{
// create a new directory context for the parent domain
parentDomainName = (string)PropertyManager.GetPropertyValue(context, parentCrossRef, PropertyManager.DnsRoot);
domainContext = Utils.GetNewDirectoryContext(parentDomainName, DirectoryContextType.Domain, context);
}
finally
{
parentCrossRef.Dispose();
}
return new Domain(domainContext, parentDomainName);
}
// does not have a parent so just return null
return null;
}
private ArrayList GetChildDomains()
{
ArrayList childDomains = new ArrayList();
if (_crossRefDN == null)
{
LoadCrossRefAttributes();
}
DirectoryEntry partitionsEntry = null;
SearchResultCollection resCol = null;
try
{
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// search for all the "crossRef" objects that have the
// ADS_SYSTEMFLAG_CR_NTDS_NC and SYSTEMFLAG_CR_NTDS_DOMAIN flags set
// (one-level search is good enough)
// setup the directory searcher object
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append(")(");
str.Append(PropertyManager.TrustParent);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(_crossRefDN));
str.Append("))");
string filter = str.ToString();
string[] propertiesToLoad = new string[1];
propertiesToLoad[0] = PropertyManager.DnsRoot;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel);
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string childDomainName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DnsRoot);
DirectoryContext childContext = Utils.GetNewDirectoryContext(childDomainName, DirectoryContextType.Domain, context);
childDomains.Add(new Domain(childContext, childDomainName));
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (resCol != null)
{
resCol.Dispose();
}
if (partitionsEntry != null)
{
partitionsEntry.Dispose();
}
}
return childDomains;
}
private ArrayList GetTrustsHelper(string targetDomainName)
{
string serverName = null;
IntPtr domains = (IntPtr)0;
int count = 0;
ArrayList unmanagedTrustList = new ArrayList();
ArrayList tmpTrustList = new ArrayList();
TrustRelationshipInformationCollection collection = new TrustRelationshipInformationCollection();
int localDomainIndex = 0;
string localDomainParent = null;
int error = 0;
bool impersonated = false;
// first decide which server to go to
if (context.isServer())
{
serverName = context.Name;
}
else
{
serverName = DomainController.FindOne(context).Name;
}
// impersonate appropriately
impersonated = Utils.Impersonate(context);
// call the DS API to get trust domain information
try
{
try
{
error = UnsafeNativeMethods.DsEnumerateDomainTrustsW(serverName, (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_IN_FOREST | (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND | (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND, out domains, out count);
}
finally
{
if (impersonated)
Utils.Revert();
}
}
catch { throw; }
// check the result
if (error != 0)
throw ExceptionHelper.GetExceptionFromErrorCode(error, serverName);
try
{
// now enumerate through the collection
if (domains != (IntPtr)0 && count != 0)
{
IntPtr addr = (IntPtr)0;
int j = 0;
for (int i = 0; i < count; i++)
{
// get the unmanaged trust object
addr = IntPtr.Add(domains, +i * Marshal.SizeOf(typeof(DS_DOMAIN_TRUSTS)));
DS_DOMAIN_TRUSTS unmanagedTrust = new DS_DOMAIN_TRUSTS();
Marshal.PtrToStructure(addr, unmanagedTrust);
unmanagedTrustList.Add(unmanagedTrust);
}
for (int i = 0; i < unmanagedTrustList.Count; i++)
{
DS_DOMAIN_TRUSTS unmanagedTrust = (DS_DOMAIN_TRUSTS)unmanagedTrustList[i];
// make sure this is the trust object that we want
if ((unmanagedTrust.Flags & (int)(DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY | DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND | DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND)) == 0)
{
// Not interested in indirectly trusted domains.
continue;
}
// we don't want to have the NT4 trust to be returned
if (unmanagedTrust.TrustType == TrustHelper.TRUST_TYPE_DOWNLEVEL)
continue;
TrustObject obj = new TrustObject();
obj.TrustType = TrustType.Unknown;
if (unmanagedTrust.DnsDomainName != (IntPtr)0)
obj.DnsDomainName = Marshal.PtrToStringUni(unmanagedTrust.DnsDomainName);
if (unmanagedTrust.NetbiosDomainName != (IntPtr)0)
obj.NetbiosDomainName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName);
obj.Flags = unmanagedTrust.Flags;
obj.TrustAttributes = unmanagedTrust.TrustAttributes;
obj.OriginalIndex = i;
obj.ParentIndex = unmanagedTrust.ParentIndex;
// check whether it is the case that we are only interested in the trust with target as specified
if (targetDomainName != null)
{
bool sameTarget = false;
// check whether it is the same target
if (obj.DnsDomainName != null && Utils.Compare(targetDomainName, obj.DnsDomainName) == 0)
sameTarget = true;
else if (obj.NetbiosDomainName != null && Utils.Compare(targetDomainName, obj.NetbiosDomainName) == 0)
sameTarget = true;
// we only want to need local domain and specified target domain trusts
if (!sameTarget && (obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY) == 0)
continue;
}
// local domain case
if ((obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_PRIMARY) != 0)
{
localDomainIndex = j;
// verify whether this is already the root
if ((obj.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) == 0)
{
// get the parent domain name
DS_DOMAIN_TRUSTS parentTrust = (DS_DOMAIN_TRUSTS)unmanagedTrustList[obj.ParentIndex];
if (parentTrust.DnsDomainName != (IntPtr)0)
localDomainParent = Marshal.PtrToStringUni(parentTrust.DnsDomainName);
}
// this is the trust type SELF
obj.TrustType = (TrustType)7;
}
// this is the case of MIT kerberos trust
else if (unmanagedTrust.TrustType == 3)
{
obj.TrustType = TrustType.Kerberos;
}
j++;
tmpTrustList.Add(obj);
}
// now determine the trust type
for (int i = 0; i < tmpTrustList.Count; i++)
{
TrustObject tmpObject = (TrustObject)tmpTrustList[i];
// local domain case, trust type has been determined
if (i == localDomainIndex)
continue;
if (tmpObject.TrustType == TrustType.Kerberos)
continue;
// parent domain
if (localDomainParent != null && Utils.Compare(localDomainParent, tmpObject.DnsDomainName) == 0)
{
tmpObject.TrustType = TrustType.ParentChild;
continue;
}
if ((tmpObject.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_IN_FOREST) != 0)
{
// child domain
if (tmpObject.ParentIndex == ((TrustObject)tmpTrustList[localDomainIndex]).OriginalIndex)
{
tmpObject.TrustType = TrustType.ParentChild;
}
// tree root
else if ((tmpObject.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) != 0 &&
(((TrustObject)tmpTrustList[localDomainIndex]).Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_TREE_ROOT) != 0)
{
string tmpForestName = null;
string rootDomainNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDomainNamingContext);
tmpForestName = Utils.GetDnsNameFromDN(rootDomainNC);
// only if either the local domain or tmpObject is the tree root, will this trust relationship be a Root, otherwise it is cross link
DirectoryContext tmpContext = Utils.GetNewDirectoryContext(context.Name, DirectoryContextType.Forest, context);
if (tmpContext.isRootDomain() || Utils.Compare(tmpObject.DnsDomainName, tmpForestName) == 0)
{
tmpObject.TrustType = TrustType.TreeRoot;
}
else
{
tmpObject.TrustType = TrustType.CrossLink;
}
}
else
{
tmpObject.TrustType = TrustType.CrossLink;
}
continue;
}
// external trust or forest trust
if ((tmpObject.TrustAttributes & (int)TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) != 0)
{
// should not happen as we specify DS_DOMAIN_IN_FOREST when enumerating the trust, so forest trust will not be returned
tmpObject.TrustType = TrustType.Forest;
}
else
{
tmpObject.TrustType = TrustType.External;
}
}
}
return tmpTrustList;
}
finally
{
if (domains != (IntPtr)0)
UnsafeNativeMethods.NetApiBufferFree(domains);
}
}
private void RepairTrustHelper(Domain targetDomain, TrustDirection direction)
{
// now we try changing trust password on both sides
string password = TrustHelper.CreateTrustPassword();
// first reset trust password on remote side
string targetServerName = TrustHelper.UpdateTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, password, false);
// then reset trust password on local side
string sourceServerName = TrustHelper.UpdateTrust(context, Name, targetDomain.Name, password, false);
// last we reset the secure channel again to make sure info is replicated and trust is indeed ready now
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
try
{
TrustHelper.VerifyTrust(context, Name, targetDomain.Name, false /*not forest*/, TrustDirection.Outbound, true /*reset secure channel*/, targetServerName /* need to specify which target server */);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
try
{
TrustHelper.VerifyTrust(targetDomain.GetDirectoryContext(), targetDomain.Name, Name, false /*not forest*/, TrustDirection.Outbound, true/*reset secure channel*/, sourceServerName /* need to specify which target server */);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
#endregion private methods
}
}
| |
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Tests.TestSupport;
using ICSharpCode.SharpZipLib.Zip;
using NUnit.Framework;
using System;
using System.IO;
using System.Security;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tests.Zip
{
internal class RuntimeInfo
{
public RuntimeInfo(CompressionMethod method, int compressionLevel,
int size, string password, bool getCrc)
{
this.method = method;
this.compressionLevel = compressionLevel;
this.password = password;
this.size = size;
this.random = false;
original = new byte[Size];
if (random)
{
var rnd = new Random();
rnd.NextBytes(original);
}
else
{
for (int i = 0; i < size; ++i)
{
original[i] = (byte)'A';
}
}
if (getCrc)
{
var crc32 = new Crc32();
crc32.Update(new ArraySegment<byte>(original, 0, size));
crc = crc32.Value;
}
}
public RuntimeInfo(string password, bool isDirectory)
{
this.method = CompressionMethod.Stored;
this.compressionLevel = 1;
this.password = password;
this.size = 0;
this.random = false;
isDirectory_ = isDirectory;
original = new byte[0];
}
public byte[] Original
{
get { return original; }
}
public CompressionMethod Method
{
get { return method; }
}
public int CompressionLevel
{
get { return compressionLevel; }
}
public int Size
{
get { return size; }
}
public string Password
{
get { return password; }
}
private bool Random
{
get { return random; }
}
public long Crc
{
get { return crc; }
}
public bool IsDirectory
{
get { return isDirectory_; }
}
#region Instance Fields
private readonly byte[] original;
private readonly CompressionMethod method;
private int compressionLevel;
private int size;
private string password;
private bool random;
private bool isDirectory_;
private long crc = -1;
#endregion Instance Fields
}
internal class MemoryDataSource : IStaticDataSource
{
#region Constructors
/// <summary>
/// Initialise a new instance.
/// </summary>
/// <param name="data">The data to provide.</param>
public MemoryDataSource(byte[] data)
{
data_ = data;
}
#endregion Constructors
#region IDataSource Members
/// <summary>
/// Get a Stream for this <see cref="IStaticDataSource"/>
/// </summary>
/// <returns>Returns a <see cref="Stream"/></returns>
public Stream GetSource()
{
return new MemoryStream(data_);
}
#endregion IDataSource Members
#region Instance Fields
private readonly byte[] data_;
#endregion Instance Fields
}
internal class StringMemoryDataSource : MemoryDataSource
{
public StringMemoryDataSource(string data)
: base(Encoding.ASCII.GetBytes(data))
{
}
}
public class ZipBase
{
static protected string GetTempFilePath()
{
string result = null;
try
{
result = Path.GetTempPath();
}
catch (SecurityException)
{
}
return result;
}
protected byte[] MakeInMemoryZip(bool withSeek, params object[] createSpecs)
{
MemoryStream ms;
if (withSeek)
{
ms = new MemoryStream();
}
else
{
ms = new MemoryStreamWithoutSeek();
}
using (ZipOutputStream outStream = new ZipOutputStream(ms))
{
for (int counter = 0; counter < createSpecs.Length; ++counter)
{
var info = createSpecs[counter] as RuntimeInfo;
outStream.Password = info.Password;
if (info.Method != CompressionMethod.Stored)
{
outStream.SetLevel(info.CompressionLevel); // 0 - store only to 9 - means best compression
}
string entryName;
if (info.IsDirectory)
{
entryName = "dir" + counter + "/";
}
else
{
entryName = "entry" + counter + ".tst";
}
var entry = new ZipEntry(entryName);
entry.CompressionMethod = info.Method;
if (info.Crc >= 0)
{
entry.Crc = info.Crc;
}
outStream.PutNextEntry(entry);
if (info.Size > 0)
{
outStream.Write(info.Original, 0, info.Original.Length);
}
}
}
return ms.ToArray();
}
protected byte[] MakeInMemoryZip(ref byte[] original, CompressionMethod method,
int compressionLevel, int size, string password, bool withSeek)
{
MemoryStream ms;
if (withSeek)
{
ms = new MemoryStream();
}
else
{
ms = new MemoryStreamWithoutSeek();
}
using (ZipOutputStream outStream = new ZipOutputStream(ms))
{
outStream.Password = password;
if (method != CompressionMethod.Stored)
{
outStream.SetLevel(compressionLevel); // 0 - store only to 9 - means best compression
}
var entry = new ZipEntry("dummyfile.tst");
entry.CompressionMethod = method;
outStream.PutNextEntry(entry);
if (size > 0)
{
var rnd = new Random();
original = new byte[size];
rnd.NextBytes(original);
// Although this could be written in one chunk doing it in lumps
// throws up buffering problems including with encryption the original
// source for this change.
int index = 0;
while (size > 0)
{
int count = (size > 0x200) ? 0x200 : size;
outStream.Write(original, index, count);
size -= 0x200;
index += count;
}
}
}
return ms.ToArray();
}
protected static void MakeTempFile(string name, int size)
{
using (FileStream fs = File.Create(name))
{
byte[] buffer = new byte[4096];
while (size > 0)
{
fs.Write(buffer, 0, Math.Min(size, buffer.Length));
size -= buffer.Length;
}
}
}
protected static byte ScatterValue(byte rhs)
{
return (byte)((rhs * 253 + 7) & 0xff);
}
private static void AddKnownDataToEntry(ZipOutputStream zipStream, int size)
{
if (size > 0)
{
byte nextValue = 0;
int bufferSize = Math.Min(size, 65536);
byte[] data = new byte[bufferSize];
int currentIndex = 0;
for (int i = 0; i < size; ++i)
{
data[currentIndex] = nextValue;
nextValue = ScatterValue(nextValue);
currentIndex += 1;
if ((currentIndex >= data.Length) || (i + 1 == size))
{
zipStream.Write(data, 0, currentIndex);
currentIndex = 0;
}
}
}
}
public void WriteToFile(string fileName, byte[] data)
{
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
fs.Write(data, 0, data.Length);
}
}
#region MakeZipFile
protected void MakeZipFile(Stream storage, bool isOwner, string[] names, int size, string comment)
{
using (ZipOutputStream zOut = new ZipOutputStream(storage))
{
zOut.IsStreamOwner = isOwner;
zOut.SetComment(comment);
for (int i = 0; i < names.Length; ++i)
{
zOut.PutNextEntry(new ZipEntry(names[i]));
AddKnownDataToEntry(zOut, size);
}
zOut.Close();
}
}
protected void MakeZipFile(string name, string[] names, int size, string comment)
{
using (FileStream fs = File.Create(name))
{
using (ZipOutputStream zOut = new ZipOutputStream(fs))
{
zOut.SetComment(comment);
for (int i = 0; i < names.Length; ++i)
{
zOut.PutNextEntry(new ZipEntry(names[i]));
AddKnownDataToEntry(zOut, size);
}
zOut.Close();
}
fs.Close();
}
}
#endregion MakeZipFile
#region MakeZipFile Entries
protected void MakeZipFile(string name, string entryNamePrefix, int entries, int size, string comment)
{
using (FileStream fs = File.Create(name))
using (ZipOutputStream zOut = new ZipOutputStream(fs))
{
zOut.SetComment(comment);
for (int i = 0; i < entries; ++i)
{
zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1)));
AddKnownDataToEntry(zOut, size);
}
}
}
protected void MakeZipFile(Stream storage, bool isOwner,
string entryNamePrefix, int entries, int size, string comment)
{
using (ZipOutputStream zOut = new ZipOutputStream(storage))
{
zOut.IsStreamOwner = isOwner;
zOut.SetComment(comment);
for (int i = 0; i < entries; ++i)
{
zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1)));
AddKnownDataToEntry(zOut, size);
}
}
}
#endregion MakeZipFile Entries
protected static void CheckKnownEntry(Stream inStream, int expectedCount)
{
byte[] buffer = new byte[1024];
int bytesRead;
int total = 0;
byte nextValue = 0;
while ((bytesRead = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
total += bytesRead;
for (int i = 0; i < bytesRead; ++i)
{
Assert.AreEqual(nextValue, buffer[i], "Wrong value read from entry");
nextValue = ScatterValue(nextValue);
}
}
Assert.AreEqual(expectedCount, total, "Wrong number of bytes read from entry");
}
protected byte ReadByteChecked(Stream stream)
{
int rawValue = stream.ReadByte();
Assert.IsTrue(rawValue >= 0);
return (byte)rawValue;
}
protected int ReadInt(Stream stream)
{
return ReadByteChecked(stream) |
(ReadByteChecked(stream) << 8) |
(ReadByteChecked(stream) << 16) |
(ReadByteChecked(stream) << 24);
}
protected long ReadLong(Stream stream)
{
long result = ReadInt(stream) & 0xffffffff;
return result | (((long)ReadInt(stream)) << 32);
}
}
internal class TestHelper
{
static public void SaveMemoryStream(MemoryStream ms, string fileName)
{
byte[] data = ms.ToArray();
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
fs.Write(data, 0, data.Length);
}
}
static public int CompareDosDateTimes(DateTime l, DateTime r)
{
// Compare dates to dos accuracy...
// Ticks can be different yet all these values are still the same!
int result = l.Year - r.Year;
if (result == 0)
{
result = l.Month - r.Month;
if (result == 0)
{
result = l.Day - r.Day;
if (result == 0)
{
result = l.Hour - r.Hour;
if (result == 0)
{
result = l.Minute - r.Minute;
if (result == 0)
{
result = (l.Second / 2) - (r.Second / 2);
}
}
}
}
}
return result;
}
}
public class TransformBase : ZipBase
{
protected void TestFile(INameTransform t, string original, string expected)
{
string transformed = t.TransformFile(original);
Assert.AreEqual(expected, transformed, "Should be equal");
}
protected void TestDirectory(INameTransform t, string original, string expected)
{
string transformed = t.TransformDirectory(original);
Assert.AreEqual(expected, transformed, "Should be equal");
}
}
}
| |
// 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.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// HttpRedirects operations.
/// </summary>
public partial class HttpRedirects : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRedirects
{
/// <summary>
/// Initializes a new instance of the HttpRedirects class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpRedirects(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head300", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/300").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<string>>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get300", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/300").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<string>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<string>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head301", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get301", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put true Boolean value in request returns 301. This request should not be
/// automatically redirected, but should return the received 301 to the
/// caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put301", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head302", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get302", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch true Boolean value in request returns 302. This request should not
/// be automatically redirected, but should return the received 302 to the
/// caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch302", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post true Boolean value in request returns 303. This request should be
/// automatically redirected usign a get, ultimately returning a 200 status
/// code
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post303", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/303").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "SeeOther")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Redirect with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Redirect get with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete307", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace Valcon.Tests
{
/// <summary>
/// Provides a fluent interface for asserting the raising of exceptions.
/// </summary>
/// <typeparam name="TException">The type of exception to assert.</typeparam>
public static class Exception<TException>
where TException : Exception
{
/// <summary>
/// Asserts that the exception is thrown when the specified action is executed.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns></returns>
public static TException ShouldBeThrownBy(Action action)
{
return ShouldBeThrownBy(action, null);
}
/// <summary>
/// Asserts that the exception is thrown when the specified action is executed.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <param name="postCatchAction">The action to execute after the exception has been caught.</param>
/// <returns></returns>
public static TException ShouldBeThrownBy(Action action, Action<Exception> postCatchAction)
{
TException exception = null;
try
{
action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<TException>();
if(postCatchAction != null)
{
postCatchAction(e);
}
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
/// <summary>
/// Asserts that the exception was thrown when the specified action is executed by
/// scanning the exception chain.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns></returns>
public static TException ShouldExistInExceptionChainAfter(Action action)
{
TException exception = null;
try
{
action();
}
catch (Exception e)
{
exception = ScanExceptionChain(e);
}
return exception;
}
/// <summary>
/// Scans the specified exception chain and asserts the existence of the target exception.
/// </summary>
/// <param name="chainLink">Exception chain to scan.</param>
/// <returns></returns>
private static TException ScanExceptionChain(Exception chainLink)
{
TException exception;
if((exception = chainLink as TException) != null)
{
return exception;
}
if(chainLink.InnerException == null)
{
Assert.Fail("An exception was expected, but not thrown by the given action.");
}
return ScanExceptionChain(chainLink.InnerException);
}
}
public static class SpecificationExtensions
{
public static void ShouldHave<T>(this IEnumerable<T> values, Func<T, bool> func)
{
values.FirstOrDefault(func).ShouldNotBeNull();
}
public static void ShouldBeFalse(this bool condition)
{
Assert.IsFalse(condition);
}
public static void ShouldBeTrue(this bool condition)
{
Assert.IsTrue(condition);
}
public static void ShouldBeTrueBecause(this bool condition, string reason, params object[] args)
{
Assert.IsTrue(condition, reason, args);
}
public static object ShouldEqual(this object actual, object expected)
{
Assert.AreEqual(expected, actual);
return expected;
}
public static object ShouldEqual(this string actual, object expected)
{
Assert.AreEqual((expected != null) ? expected.ToString() : null, actual);
return expected;
}
public static void ShouldMatch(this string actual, string pattern)
{
#pragma warning disable 612,618
Assert.That(actual, Text.Matches(pattern));
#pragma warning restore 612,618
}
public static XmlElement AttributeShouldEqual(this XmlElement element, string attributeName, object expected)
{
Assert.IsNotNull(element, "The Element is null");
string actual = element.GetAttribute(attributeName);
Assert.AreEqual(expected, actual);
return element;
}
public static XmlElement AttributeShouldEqual(this XmlNode node, string attributeName, object expected)
{
var element = node as XmlElement;
Assert.IsNotNull(element, "The Element is null");
string actual = element.GetAttribute(attributeName);
Assert.AreEqual(expected, actual);
return element;
}
public static XmlElement ShouldHaveChild(this XmlElement element, string xpath)
{
var child = element.SelectSingleNode(xpath) as XmlElement;
Assert.IsNotNull(child, "Should have a child element matching " + xpath);
return child;
}
public static XmlElement DoesNotHaveAttribute(this XmlElement element, string attributeName)
{
Assert.IsNotNull(element, "The Element is null");
Assert.IsFalse(element.HasAttribute(attributeName),
"Element should not have an attribute named " + attributeName);
return element;
}
public static object ShouldNotEqual(this object actual, object expected)
{
Assert.AreNotEqual(expected, actual);
return expected;
}
public static void ShouldBeNull(this object anObject)
{
Assert.IsNull(anObject);
}
public static void ShouldNotBeNull(this object anObject)
{
Assert.IsNotNull(anObject);
}
public static void ShouldNotBeNull(this object anObject, string message)
{
Assert.IsNotNull(anObject, message);
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
Assert.AreSame(expected, actual);
return expected;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
Assert.AreNotSame(expected, actual);
return expected;
}
public static T ShouldBeOfType<T>(this object actual)
{
actual.ShouldNotBeNull();
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static T As<T>(this object actual)
{
actual.ShouldNotBeNull();
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static object ShouldBeOfType(this object actual, Type expected)
{
#pragma warning disable 612,618
Assert.IsInstanceOfType(expected, actual);
#pragma warning restore 612,618
return actual;
}
public static void ShouldNotBeOfType(this object actual, Type expected)
{
#pragma warning disable 612,618
Assert.IsNotInstanceOfType(expected, actual);
#pragma warning restore 612,618
}
public static void ShouldContain(this IList actual, object expected)
{
Assert.Contains(expected, actual);
}
public static void ShouldContain<T>(this IEnumerable<T> actual, T expected)
{
if (actual.Count(t => t.Equals(expected)) == 0)
{
Assert.Fail("The item '{0}' was not found in the sequence.", expected);
}
}
public static void ShouldBeEmpty<T>(this IEnumerable<T> actual)
{
actual.ShouldHaveCount(0);
}
public static void ShouldNotBeEmpty<T>(this IEnumerable<T> actual)
{
Assert.Greater(actual.Count(), 0, "The list should have at least one element");
}
public static void ShouldNotContain<T>(this IEnumerable<T> actual, T expected)
{
if (actual.Count(t => t.Equals(expected)) > 0)
{
Assert.Fail("The item was found in the sequence it should not be in.");
}
}
public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
actual.Count.ShouldEqual(expected.Count);
for (int i = 0; i < actual.Count; i++)
{
actual[i].ShouldEqual(expected[i]);
}
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected)
{
ShouldHaveTheSameElementsAs(actual, (IEnumerable<T>)expected);
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
IList actualList = (actual is IList) ? (IList)actual : actual.ToList();
IList expectedList = (expected is IList) ? (IList)expected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementKeysAs<ELEMENT, KEY>(this IEnumerable<ELEMENT> actual,
IEnumerable expected,
Func<ELEMENT, KEY> keySelector)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
ELEMENT[] actualArray = actual.ToArray();
object[] expectedArray = expected.Cast<object>().ToArray();
actualArray.Length.ShouldEqual(expectedArray.Length);
for (int i = 0; i < actual.Count(); i++)
{
keySelector(actualArray[i]).ShouldEqual(expectedArray[i]);
}
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2)
{
Assert.Greater(arg1, arg2);
return arg2;
}
public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2)
{
Assert.Less(arg1, arg2);
return arg2;
}
public static void ShouldBeEmpty(this ICollection collection)
{
Assert.IsEmpty(collection);
}
public static void ShouldBeEmpty(this string aString)
{
Assert.IsEmpty(aString);
}
public static void ShouldNotBeEmpty(this ICollection collection)
{
Assert.IsNotEmpty(collection);
}
public static void ShouldNotBeEmpty(this string aString)
{
Assert.IsNotEmpty(aString);
}
public static void ShouldContain(this string actual, string expected)
{
StringAssert.Contains(expected, actual);
}
public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected)
{
actual.Count().ShouldBeGreaterThan(0);
T result = actual.FirstOrDefault(expected);
Assert.That(result, Is.Not.EqualTo(default(T)), "Expected item was not found in the actual sequence");
}
public static void ShouldNotContain(this string actual, string expected)
{
Assert.That(actual, new NotConstraint(new SubstringConstraint(expected)));
}
public static string ShouldBeEqualIgnoringCase(this string actual, string expected)
{
StringAssert.AreEqualIgnoringCase(expected, actual);
return expected;
}
public static void ShouldEndWith(this string actual, string expected)
{
StringAssert.EndsWith(expected, actual);
}
public static void ShouldStartWith(this string actual, string expected)
{
StringAssert.StartsWith(expected, actual);
}
public static void ShouldContainErrorMessage(this Exception exception, string expected)
{
StringAssert.Contains(expected, exception.Message);
}
public static Exception ShouldBeThrownBy(this Type exceptionType, Action action)
{
Exception exception = null;
try
{
action();
}
catch (Exception e)
{
Assert.AreEqual(exceptionType, e.GetType());
exception = e;
}
if (exception == null)
{
Assert.Fail(String.Format("Expected {0} to be thrown.", exceptionType.FullName));
}
return exception;
}
public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected)
{
TimeSpan timeSpan = actual - expected;
Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3);
}
public static IEnumerable<T> ShouldHaveCount<T>(this IEnumerable<T> actual, int expected)
{
actual.Count().ShouldEqual(expected);
return actual;
}
}
}
| |
using System;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public static class Conversion
{
public static Gtk.IconSize ToGtkValue (Xwt.IconSize size)
{
switch (size) {
case IconSize.Small:
return Gtk.IconSize.Menu;
case IconSize.Medium:
return Gtk.IconSize.Button;
case IconSize.Large:
return Gtk.IconSize.Dialog;
}
return Gtk.IconSize.Dialog;
}
public static Gdk.Color ToGtkValue (this Xwt.Drawing.Color color)
{
return new Gdk.Color ((byte)(color.Red * 255), (byte)(color.Green * 255), (byte)(color.Blue * 255));
}
public static Color ToXwtValue (this Gdk.Color color)
{
return new Color ((double)color.Red / (double)ushort.MaxValue, (double)color.Green / (double)ushort.MaxValue, (double)color.Blue / (double)ushort.MaxValue);
}
#if XWT_GTK3
public static Gdk.RGBA ToGtkRgbaValue (this Xwt.Drawing.Color color)
{
var rgba = new Gdk.RGBA ();
rgba.Red = color.Red;
rgba.Green = color.Green;
rgba.Blue = color.Blue;
rgba.Alpha = color.Alpha;
return rgba;
}
public static Color ToXwtValue (this Gdk.RGBA color)
{
return new Color (color.Red, color.Green, color.Blue, color.Alpha);
}
#endif
public static Pango.EllipsizeMode ToGtkValue (this EllipsizeMode value)
{
switch (value) {
case Xwt.EllipsizeMode.None: return Pango.EllipsizeMode.None;
case Xwt.EllipsizeMode.Start: return Pango.EllipsizeMode.Start;
case Xwt.EllipsizeMode.Middle: return Pango.EllipsizeMode.Middle;
case Xwt.EllipsizeMode.End: return Pango.EllipsizeMode.End;
}
throw new NotSupportedException ();
}
public static EllipsizeMode ToXwtValue (this Pango.EllipsizeMode value)
{
switch (value) {
case Pango.EllipsizeMode.None: return Xwt.EllipsizeMode.None;
case Pango.EllipsizeMode.Start: return Xwt.EllipsizeMode.Start;
case Pango.EllipsizeMode.Middle: return Xwt.EllipsizeMode.Middle;
case Pango.EllipsizeMode.End: return Xwt.EllipsizeMode.End;
}
throw new NotSupportedException ();
}
public static ScrollPolicy ToXwtValue (this Gtk.PolicyType p)
{
switch (p) {
case Gtk.PolicyType.Always:
return ScrollPolicy.Always;
case Gtk.PolicyType.Automatic:
return ScrollPolicy.Automatic;
case Gtk.PolicyType.Never:
return ScrollPolicy.Never;
}
throw new InvalidOperationException ("Invalid policy value:" + p);
}
public static Gtk.PolicyType ToGtkValue (this ScrollPolicy p)
{
switch (p) {
case ScrollPolicy.Always:
return Gtk.PolicyType.Always;
case ScrollPolicy.Automatic:
return Gtk.PolicyType.Automatic;
case ScrollPolicy.Never:
return Gtk.PolicyType.Never;
}
throw new InvalidOperationException ("Invalid policy value:" + p);
}
public static ScrollDirection ToXwtValue(this Gdk.ScrollDirection d)
{
switch(d) {
case Gdk.ScrollDirection.Up:
return Xwt.ScrollDirection.Up;
case Gdk.ScrollDirection.Down:
return Xwt.ScrollDirection.Down;
case Gdk.ScrollDirection.Left:
return Xwt.ScrollDirection.Left;
case Gdk.ScrollDirection.Right:
return Xwt.ScrollDirection.Right;
}
throw new InvalidOperationException("Invalid mouse scroll direction value: " + d);
}
public static Gdk.ScrollDirection ToGtkValue(this ScrollDirection d)
{
switch (d) {
case ScrollDirection.Up:
return Gdk.ScrollDirection.Up;
case ScrollDirection.Down:
return Gdk.ScrollDirection.Down;
case ScrollDirection.Left:
return Gdk.ScrollDirection.Left;
case ScrollDirection.Right:
return Gdk.ScrollDirection.Right;
}
throw new InvalidOperationException("Invalid mouse scroll direction value: " + d);
}
public static ModifierKeys ToXwtValue (this Gdk.ModifierType s)
{
ModifierKeys m = ModifierKeys.None;
if ((s & Gdk.ModifierType.ShiftMask) != 0)
m |= ModifierKeys.Shift;
if ((s & Gdk.ModifierType.ControlMask) != 0)
m |= ModifierKeys.Control;
if ((s & Gdk.ModifierType.Mod1Mask) != 0)
m |= ModifierKeys.Alt;
if ((s & Gdk.ModifierType.Mod2Mask) != 0)
m |= ModifierKeys.Command;
return m;
}
public static Gtk.Requisition ToGtkRequisition (this Size size)
{
var req = new Gtk.Requisition ();
req.Height = (int)size.Height;
req.Width = (int)size.Width;
return req;
}
public static Gtk.TreeViewGridLines ToGtkValue (this GridLines value)
{
switch (value)
{
case GridLines.Both:
return Gtk.TreeViewGridLines.Both;
case GridLines.Horizontal:
return Gtk.TreeViewGridLines.Horizontal;
case GridLines.Vertical:
return Gtk.TreeViewGridLines.Vertical;
case GridLines.None:
return Gtk.TreeViewGridLines.None;
}
throw new InvalidOperationException("Invalid GridLines value: " + value);
}
public static GridLines ToXwtValue (this Gtk.TreeViewGridLines value)
{
switch (value)
{
case Gtk.TreeViewGridLines.Both:
return GridLines.Both;
case Gtk.TreeViewGridLines.Horizontal:
return GridLines.Horizontal;
case Gtk.TreeViewGridLines.Vertical:
return GridLines.Vertical;
case Gtk.TreeViewGridLines.None:
return GridLines.None;
}
throw new InvalidOperationException("Invalid TreeViewGridLines value: " + value);
}
public static float ToGtkAlignment(this Alignment alignment)
{
switch(alignment) {
case Alignment.Start: return 0.0f;
case Alignment.Center: return 0.5f;
case Alignment.End: return 1.0f;
}
throw new InvalidOperationException("Invalid alignment value: " + alignment);
}
public static Gtk.ResponseType ToResponseType (this Xwt.Command command)
{
if (command.Id == Command.Ok.Id)
return Gtk.ResponseType.Ok;
if (command.Id == Command.Cancel.Id)
return Gtk.ResponseType.Cancel;
if (command.Id == Command.Yes.Id)
return Gtk.ResponseType.Yes;
if (command.Id == Command.No.Id)
return Gtk.ResponseType.No;
if (command.Id == Command.Close.Id)
return Gtk.ResponseType.Close;
if (command.Id == Command.Delete.Id)
return Gtk.ResponseType.DeleteEvent;
if (command.Id == Command.Apply.Id)
return Gtk.ResponseType.Accept;
if (command.Id == Command.Stop.Id)
return Gtk.ResponseType.Reject;
return Gtk.ResponseType.None;
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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.
*/
#endregion
namespace RedBadger.Xpf
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Subjects;
using RedBadger.Xpf.Graphics;
using RedBadger.Xpf.Input;
using RedBadger.Xpf.Internal;
public abstract class UIElement : ReactiveObject, IElement
{
public static readonly ReactiveProperty<object> DataContextProperty =
ReactiveProperty<object>.Register("DataContext", typeof(UIElement), DataContextChanged);
public static readonly ReactiveProperty<double> HeightProperty = ReactiveProperty<double>.Register(
"Height", typeof(UIElement), double.NaN, ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<HorizontalAlignment> HorizontalAlignmentProperty =
ReactiveProperty<HorizontalAlignment>.Register(
"HorizontalAlignment",
typeof(UIElement),
HorizontalAlignment.Stretch,
ReactivePropertyChangedCallbacks.InvalidateArrange);
public static readonly ReactiveProperty<bool> IsMouseCapturedProperty =
ReactiveProperty<bool>.Register("IsMouseCaptured", typeof(UIElement));
public static readonly ReactiveProperty<Thickness> MarginProperty =
ReactiveProperty<Thickness>.Register(
"Margin", typeof(UIElement), new Thickness(), ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<double> MaxHeightProperty =
ReactiveProperty<double>.Register(
"MaxHeight",
typeof(UIElement),
double.PositiveInfinity,
ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<double> MaxWidthProperty = ReactiveProperty<double>.Register(
"MaxWidth", typeof(UIElement), double.PositiveInfinity, ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<double> MinHeightProperty =
ReactiveProperty<double>.Register(
"MinHeight", typeof(UIElement), ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<double> MinWidthProperty = ReactiveProperty<double>.Register(
"MinWidth", typeof(UIElement), ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<VerticalAlignment> VerticalAlignmentProperty =
ReactiveProperty<VerticalAlignment>.Register(
"VerticalAlignment",
typeof(UIElement),
VerticalAlignment.Stretch,
ReactivePropertyChangedCallbacks.InvalidateArrange);
public static readonly ReactiveProperty<double> WidthProperty = ReactiveProperty<double>.Register(
"Width", typeof(UIElement), double.NaN, ReactivePropertyChangedCallbacks.InvalidateMeasure);
private readonly Subject<Gesture> gestures = new Subject<Gesture>();
private Rect clippingRect = Rect.Empty;
private bool isClippingRequired;
private Size previousAvailableSize;
private Rect previousFinalRect;
private Size unclippedSize;
private Vector visualOffset;
protected UIElement()
{
this.Gestures.Subscribe(Observer.Create<Gesture>(this.OnNextGesture));
}
public double ActualHeight
{
get
{
return this.RenderSize.Height;
}
}
public double ActualWidth
{
get
{
return this.RenderSize.Width;
}
}
public Rect ClippingRect
{
get
{
return this.clippingRect;
}
}
public object DataContext
{
get
{
return this.GetValue(DataContextProperty);
}
set
{
this.SetValue(DataContextProperty, value);
}
}
public Size DesiredSize { get; private set; }
public Subject<Gesture> Gestures
{
get
{
return this.gestures;
}
}
public double Height
{
get
{
return this.GetValue(HeightProperty);
}
set
{
this.SetValue(HeightProperty, value);
}
}
public HorizontalAlignment HorizontalAlignment
{
get
{
return this.GetValue(HorizontalAlignmentProperty);
}
set
{
this.SetValue(HorizontalAlignmentProperty, value);
}
}
public bool IsArrangeValid { get; private set; }
public bool IsMeasureValid { get; private set; }
public bool IsMouseCaptured
{
get
{
return this.GetValue(IsMouseCapturedProperty);
}
private set
{
this.SetValue(IsMouseCapturedProperty, value);
}
}
public Thickness Margin
{
get
{
return this.GetValue(MarginProperty);
}
set
{
this.SetValue(MarginProperty, value);
}
}
public double MaxHeight
{
get
{
return this.GetValue(MaxHeightProperty);
}
set
{
this.SetValue(MaxHeightProperty, value);
}
}
public double MaxWidth
{
get
{
return this.GetValue(MaxWidthProperty);
}
set
{
this.SetValue(MaxWidthProperty, value);
}
}
public double MinHeight
{
get
{
return this.GetValue(MinHeightProperty);
}
set
{
this.SetValue(MinHeightProperty, value);
}
}
public double MinWidth
{
get
{
return this.GetValue(MinWidthProperty);
}
set
{
this.SetValue(MinWidthProperty, value);
}
}
public Size RenderSize { get; private set; }
public VerticalAlignment VerticalAlignment
{
get
{
return this.GetValue(VerticalAlignmentProperty);
}
set
{
this.SetValue(VerticalAlignmentProperty, value);
}
}
public Vector VisualOffset
{
get
{
return this.visualOffset;
}
}
public IElement VisualParent { get; set; }
public double Width
{
get
{
return this.GetValue(WidthProperty);
}
set
{
this.SetValue(WidthProperty, value);
}
}
public bool CaptureMouse()
{
IRootElement rootElement;
if (!this.IsMouseCaptured && this.TryGetRootElement(out rootElement))
{
this.IsMouseCaptured = rootElement.CaptureMouse(this);
}
return this.IsMouseCaptured;
}
public virtual void OnApplyTemplate()
{
}
public void ReleaseMouseCapture()
{
IRootElement rootElement;
if (this.IsMouseCaptured && this.TryGetRootElement(out rootElement))
{
rootElement.ReleaseMouseCapture(this);
this.IsMouseCaptured = false;
}
}
public void Arrange(Rect finalRect)
{
if (double.IsNaN(finalRect.Width) || double.IsNaN(finalRect.Height))
{
throw new InvalidOperationException("Width and Height must be numbers");
}
if (double.IsPositiveInfinity(finalRect.Width) || double.IsPositiveInfinity(finalRect.Height))
{
throw new InvalidOperationException("Width and Height must be less than infinity");
}
if (!this.IsArrangeValid || finalRect.IsDifferentFrom(this.previousFinalRect))
{
IRenderer renderer;
IDrawingContext drawingContext = null;
bool hasRenderer = this.TryGetRenderer(out renderer);
if (hasRenderer)
{
drawingContext = renderer.GetDrawingContext(this);
}
this.ArrangeCore(finalRect);
this.clippingRect = this.GetClippingRect(finalRect.Size);
if (hasRenderer && drawingContext != null)
{
this.OnRender(drawingContext);
}
this.previousFinalRect = finalRect;
this.IsArrangeValid = true;
}
}
public virtual IEnumerable<IElement> GetVisualChildren()
{
yield break;
}
public bool HitTest(Point point)
{
Vector absoluteOffset = Vector.Zero;
IElement currentElement = this;
while (currentElement != null)
{
absoluteOffset += currentElement.VisualOffset;
currentElement = currentElement.VisualParent;
}
var hitTestRect = new Rect(absoluteOffset.X, absoluteOffset.Y, this.ActualWidth, this.ActualHeight);
return hitTestRect.Contains(point);
}
public void InvalidateArrange()
{
this.IsArrangeValid = false;
IElement visualParent = this.VisualParent;
if (visualParent != null)
{
visualParent.InvalidateArrange();
}
}
public void InvalidateMeasure()
{
this.IsMeasureValid = false;
IElement visualParent = this.VisualParent;
if (visualParent != null)
{
visualParent.InvalidateMeasure();
}
this.InvalidateArrange();
}
public void Measure(Size availableSize)
{
if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height))
{
throw new InvalidOperationException("AvailableSize Width or Height cannot be NaN");
}
if (!this.IsMeasureValid || availableSize.IsDifferentFrom(this.previousAvailableSize))
{
Size size = this.MeasureCore(availableSize);
if (double.IsPositiveInfinity(size.Width) || double.IsPositiveInfinity(size.Height))
{
throw new InvalidOperationException("The implementing element returned a PositiveInfinity");
}
if (double.IsNaN(size.Width) || double.IsNaN(size.Height))
{
throw new InvalidOperationException("The implementing element returned NaN");
}
this.previousAvailableSize = availableSize;
this.IsMeasureValid = true;
this.DesiredSize = size;
}
}
public bool TryGetRenderer(out IRenderer renderer)
{
IRootElement rootElement;
if (this.TryGetRootElement(out rootElement))
{
renderer = rootElement.Renderer;
return true;
}
renderer = null;
return false;
}
public bool TryGetRootElement(out IRootElement rootElement)
{
var element = this as IRootElement;
if (element != null)
{
rootElement = element;
return true;
}
if (this.VisualParent != null)
{
return this.VisualParent.TryGetRootElement(out rootElement);
}
rootElement = null;
return false;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines a size for a UIElement derived class.
/// </summary>
/// <param name = "finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected virtual Size ArrangeOverride(Size finalSize)
{
return finalSize;
}
protected virtual Rect GetClippingRect(Size finalSize)
{
if (!this.isClippingRequired)
{
return Rect.Empty;
}
var max = new MinMax(this);
Size renderSize = this.RenderSize;
double maxWidth = double.IsPositiveInfinity(max.MaxWidth) ? renderSize.Width : max.MaxWidth;
double maxHeight = double.IsPositiveInfinity(max.MaxHeight) ? renderSize.Height : max.MaxHeight;
bool isClippingRequiredDueToMaxSize = maxWidth.IsLessThan(renderSize.Width) ||
maxHeight.IsLessThan(renderSize.Height);
renderSize.Width = Math.Min(renderSize.Width, max.MaxWidth);
renderSize.Height = Math.Min(renderSize.Height, max.MaxHeight);
Thickness margin = this.Margin;
double horizontalMargins = margin.Left + margin.Right;
double verticalMargins = margin.Top + margin.Bottom;
var clientSize = new Size(
(finalSize.Width - horizontalMargins).EnsurePositive(),
(finalSize.Height - verticalMargins).EnsurePositive());
bool isClippingRequiredDueToClientSize = clientSize.Width.IsLessThan(renderSize.Width) ||
clientSize.Height.IsLessThan(renderSize.Height);
if (isClippingRequiredDueToMaxSize && !isClippingRequiredDueToClientSize)
{
return new Rect(0d, 0d, maxWidth, maxHeight);
}
if (!isClippingRequiredDueToClientSize)
{
return Rect.Empty;
}
Vector offset = this.ComputeAlignmentOffset(clientSize, renderSize);
var clipRect = new Rect(-offset.X, -offset.Y, clientSize.Width, clientSize.Height);
if (isClippingRequiredDueToMaxSize)
{
clipRect.Intersect(new Rect(0d, 0d, maxWidth, maxHeight));
}
return clipRect;
}
/// <summary>
/// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the UIElement-derived class.
/// </summary>
/// <param name = "availableSize">
/// The available size that this element can give to child elements.
/// Infinity can be specified as a value to indicate that the element will size to whatever content is available.
/// </param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected virtual Size MeasureOverride(Size availableSize)
{
return Size.Empty;
}
protected virtual void OnNextGesture(Gesture gesture)
{
}
protected virtual void OnRender(IDrawingContext drawingContext)
{
}
private static void DataContextChanged(IReactiveObject source, ReactivePropertyChangeEventArgs<object> args)
{
((UIElement)source).InvalidateMeasureOnDataContextInheritors();
}
/// <summary>
/// Defines the template for core-level arrange layout definition.
/// </summary>
/// <remarks>
/// In WPF this method is defined on UIElement as protected virtual and has a base implementation.
/// FrameworkElement (which derrives from UIElement) creates a sealed implemention, similar to the below,
/// which discards UIElement's base implementation.
/// </remarks>
/// <param name = "finalRect">The final area within the parent that element should use to arrange itself and its child elements.</param>
private void ArrangeCore(Rect finalRect)
{
this.isClippingRequired = false;
Size finalSize = finalRect != Rect.Empty ? new Size(finalRect.Width, finalRect.Height) : new Size();
Thickness margin = this.Margin;
finalSize = finalSize.Deflate(margin);
Size unclippedDesiredSize = this.unclippedSize.IsEmpty
? this.DesiredSize.Deflate(margin)
: this.unclippedSize;
if (finalSize.Width.IsLessThan(unclippedDesiredSize.Width))
{
this.isClippingRequired = true;
finalSize.Width = unclippedDesiredSize.Width;
}
if (finalSize.Height.IsLessThan(unclippedDesiredSize.Height))
{
this.isClippingRequired = true;
finalSize.Height = unclippedDesiredSize.Height;
}
if (this.HorizontalAlignment != HorizontalAlignment.Stretch)
{
finalSize.Width = unclippedDesiredSize.Width;
}
if (this.VerticalAlignment != VerticalAlignment.Stretch)
{
finalSize.Height = unclippedDesiredSize.Height;
}
var minMax = new MinMax(this);
double largestWidth = Math.Max(unclippedDesiredSize.Width, minMax.MaxWidth);
if (largestWidth.IsLessThan(finalSize.Width))
{
finalSize.Width = largestWidth;
}
double largestHeight = Math.Max(unclippedDesiredSize.Height, minMax.MaxHeight);
if (largestHeight.IsLessThan(finalSize.Height))
{
finalSize.Height = largestHeight;
}
Size renderSize = this.ArrangeOverride(finalSize);
this.RenderSize = renderSize;
var inkSize = new Size(
Math.Min(renderSize.Width, minMax.MaxWidth), Math.Min(renderSize.Height, minMax.MaxHeight));
this.isClippingRequired |= inkSize.Width.IsLessThan(renderSize.Width) ||
inkSize.Height.IsLessThan(renderSize.Height);
Size clientSize = finalRect.Size.Deflate(margin);
this.isClippingRequired |= clientSize.Width.IsLessThan(inkSize.Width) ||
clientSize.Height.IsLessThan(inkSize.Height);
Vector offset = this.ComputeAlignmentOffset(clientSize, inkSize);
offset.X += finalRect.X + margin.Left;
offset.Y += finalRect.Y + margin.Top;
this.visualOffset = offset;
}
private Vector ComputeAlignmentOffset(Size clientSize, Size inkSize)
{
var vector = new Vector();
HorizontalAlignment horizontalAlignment = this.HorizontalAlignment;
VerticalAlignment verticalAlignment = this.VerticalAlignment;
if (horizontalAlignment == HorizontalAlignment.Stretch && inkSize.Width > clientSize.Width)
{
horizontalAlignment = HorizontalAlignment.Left;
}
if (verticalAlignment == VerticalAlignment.Stretch && inkSize.Height > clientSize.Height)
{
verticalAlignment = VerticalAlignment.Top;
}
switch (horizontalAlignment)
{
case HorizontalAlignment.Center:
case HorizontalAlignment.Stretch:
vector.X = (clientSize.Width - inkSize.Width) * 0.5;
break;
case HorizontalAlignment.Left:
vector.X = 0;
break;
case HorizontalAlignment.Right:
vector.X = clientSize.Width - inkSize.Width;
break;
}
switch (verticalAlignment)
{
case VerticalAlignment.Center:
case VerticalAlignment.Stretch:
vector.Y = (clientSize.Height - inkSize.Height) * 0.5;
return vector;
case VerticalAlignment.Bottom:
vector.Y = clientSize.Height - inkSize.Height;
return vector;
case VerticalAlignment.Top:
vector.Y = 0;
break;
}
return vector;
}
private object GetNearestDataContext()
{
IElement curentElement = this;
object dataContext;
do
{
dataContext = curentElement.DataContext;
curentElement = curentElement.VisualParent;
}
while (dataContext == null && curentElement != null);
return dataContext;
}
private void InvalidateMeasureOnDataContextInheritors()
{
IEnumerable<IElement> children = this.GetVisualChildren();
if (children.Count() == 0)
{
this.InvalidateMeasure();
}
else
{
IEnumerable<UIElement> childrenInheritingDataContext =
children.OfType<UIElement>().Where(element => element.DataContext == null);
foreach (UIElement element in childrenInheritingDataContext)
{
element.InvalidateMeasureOnDataContextInheritors();
}
}
}
/// <summary>
/// Implements basic measure-pass layout system behavior.
/// </summary>
/// <remarks>
/// In WPF this method is definded on UIElement as protected virtual and returns an empty Size.
/// FrameworkElement (which derrives from UIElement) then creates a sealed implementation similar to the below.
/// In XPF UIElement and FrameworkElement have been collapsed into a single class.
/// </remarks>
/// <param name = "availableSize">The available size that the parent element can give to the child elements.</param>
/// <returns>The desired size of this element in layout.</returns>
private Size MeasureCore(Size availableSize)
{
this.ResolveDeferredBindings(this.GetNearestDataContext());
this.OnApplyTemplate();
Thickness margin = this.Margin;
Size availableSizeWithoutMargins = availableSize.Deflate(margin);
var minMax = new MinMax(this);
availableSizeWithoutMargins.Width = availableSizeWithoutMargins.Width.Coerce(
minMax.MinWidth, minMax.MaxWidth);
availableSizeWithoutMargins.Height = availableSizeWithoutMargins.Height.Coerce(
minMax.MinHeight, minMax.MaxHeight);
Size size = this.MeasureOverride(availableSizeWithoutMargins);
size = new Size(Math.Max(size.Width, minMax.MinWidth), Math.Max(size.Height, minMax.MinHeight));
Size unclippedSize = size;
bool isClippingRequired = false;
if (size.Width > minMax.MaxWidth)
{
size.Width = minMax.MaxWidth;
isClippingRequired = true;
}
if (size.Height > minMax.MaxHeight)
{
size.Height = minMax.MaxHeight;
isClippingRequired = true;
}
Size desiredSizeWithMargins = size.Inflate(margin);
if (desiredSizeWithMargins.Width > availableSize.Width)
{
desiredSizeWithMargins.Width = availableSize.Width;
isClippingRequired = true;
}
if (desiredSizeWithMargins.Height > availableSize.Height)
{
desiredSizeWithMargins.Height = availableSize.Height;
isClippingRequired = true;
}
this.unclippedSize = isClippingRequired ? unclippedSize : Size.Empty;
return desiredSizeWithMargins;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Xml;
namespace tk2dEditor.Font
{
// Internal structures to fill and process
public class Char
{
public int id = 0, x = 0, y = 0, width = 0, height = 0, xoffset = 0, yoffset = 0, xadvance = 0;
public int texOffsetX, texOffsetY;
public int texX, texY, texW, texH;
public bool texFlipped;
public bool texOverride;
public int channel = 0;
};
public class Kerning
{
public int first = 0, second = 0, amount = 0;
};
public class Info
{
public string[] texturePaths = new string[0];
public int scaleW = 0, scaleH = 0;
public int lineHeight = 0;
public int numPages = 0;
public bool isPacked = false;
public List<Char> chars = new List<Char>();
public List<Kerning> kernings = new List<Kerning>();
};
class BMFontXmlImporter
{
static int ReadIntAttribute(XmlNode node, string attribute)
{
return int.Parse(node.Attributes[attribute].Value, System.Globalization.NumberFormatInfo.InvariantInfo);
}
static float ReadFloatAttribute(XmlNode node, string attribute)
{
return float.Parse(node.Attributes[attribute].Value, System.Globalization.NumberFormatInfo.InvariantInfo);
}
static string ReadStringAttribute(XmlNode node, string attribute)
{
return node.Attributes[attribute].Value;
}
static Vector2 ReadVector2Attributes(XmlNode node, string attributeX, string attributeY)
{
return new Vector2(ReadFloatAttribute(node, attributeX), ReadFloatAttribute(node, attributeY));
}
static bool HasAttribute(XmlNode node, string attribute)
{
return node.Attributes[attribute] != null;
}
public static Info Parse(string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
Info fontInfo = new Info();
XmlNode nodeCommon = doc.SelectSingleNode("/font/common");
fontInfo.scaleW = ReadIntAttribute(nodeCommon, "scaleW");
fontInfo.scaleH = ReadIntAttribute(nodeCommon, "scaleH");
fontInfo.lineHeight = ReadIntAttribute(nodeCommon, "lineHeight");
int pages = ReadIntAttribute(nodeCommon, "pages");
if (pages != 1)
{
EditorUtility.DisplayDialog("Fatal error", "Only one page supported in font. Please change the setting and re-export.", "Ok");
return null;
}
fontInfo.numPages = pages;
fontInfo.texturePaths = new string[pages];
for (int i = 0; i < pages; ++i) fontInfo.texturePaths[i] = string.Empty;
foreach (XmlNode node in doc.SelectNodes("/font/pages/page"))
{
int id = ReadIntAttribute(node, "id");
fontInfo.texturePaths[id] = ReadStringAttribute(node, "file");
}
foreach (XmlNode node in doc.SelectNodes(("/font/chars/char")))
{
Char thisChar = new Char();
thisChar.id = ReadIntAttribute(node, "id");
thisChar.x = ReadIntAttribute(node, "x");
thisChar.y = ReadIntAttribute(node, "y");
thisChar.width = ReadIntAttribute(node, "width");
thisChar.height = ReadIntAttribute(node, "height");
thisChar.xoffset = ReadIntAttribute(node, "xoffset");
thisChar.yoffset = ReadIntAttribute(node, "yoffset");
thisChar.xadvance = ReadIntAttribute(node, "xadvance");
thisChar.texOverride = false;
fontInfo.chars.Add(thisChar);
}
foreach (XmlNode node in doc.SelectNodes("/font/kernings/kerning"))
{
Kerning thisKerning = new Kerning();
thisKerning.first = ReadIntAttribute(node, "first");
thisKerning.second = ReadIntAttribute(node, "second");
thisKerning.amount = ReadIntAttribute(node, "amount");
fontInfo.kernings.Add(thisKerning);
}
return fontInfo;
}
}
class BMFontTextImporter
{
static string FindKeyValue(string[] tokens, string key)
{
string keyMatch = key + "=";
for (int i = 0; i < tokens.Length; ++i)
{
if (tokens[i].Length > keyMatch.Length && tokens[i].Substring(0, keyMatch.Length) == keyMatch)
return tokens[i].Substring(keyMatch.Length);
}
return "";
}
public static Info Parse(string path)
{
Info fontInfo = new Info();
System.IO.FileInfo finfo = new System.IO.FileInfo(path);
System.IO.StreamReader reader = finfo.OpenText();
string line;
while ((line = reader.ReadLine()) != null)
{
string[] tokens = line.Split( ' ' );
if (tokens[0] == "common")
{
fontInfo.lineHeight = int.Parse( FindKeyValue(tokens, "lineHeight") );
fontInfo.scaleW = int.Parse( FindKeyValue(tokens, "scaleW") );
fontInfo.scaleH = int.Parse( FindKeyValue(tokens, "scaleH") );
int pages = int.Parse( FindKeyValue(tokens, "pages") );
if (pages != 1)
{
EditorUtility.DisplayDialog("Fatal error", "Only one page supported in font. Please change the setting and re-export.", "Ok");
return null;
}
fontInfo.numPages = pages;
if (FindKeyValue(tokens, "packed") != "")
fontInfo.isPacked = int.Parse(FindKeyValue(tokens, "packed")) != 0;
fontInfo.texturePaths = new string[pages];
for (int i = 0 ; i < pages; ++i)
fontInfo.texturePaths[i] = string.Empty;
}
else if (tokens[0] == "page")
{
int id = int.Parse(FindKeyValue(tokens, "id"));
string file = FindKeyValue(tokens, "file");
if (file[0] == '"' && file[file.Length - 1] == '"')
file = file.Substring(1, file.Length - 2);
fontInfo.texturePaths[id] = file;
}
else if (tokens[0] == "char")
{
Char thisChar = new Char();
thisChar.id = int.Parse(FindKeyValue(tokens, "id"));
thisChar.x = int.Parse(FindKeyValue(tokens, "x"));
thisChar.y = int.Parse(FindKeyValue(tokens, "y"));
thisChar.width = int.Parse(FindKeyValue(tokens, "width"));
thisChar.height = int.Parse(FindKeyValue(tokens, "height"));
thisChar.xoffset = int.Parse(FindKeyValue(tokens, "xoffset"));
thisChar.yoffset = int.Parse(FindKeyValue(tokens, "yoffset"));
thisChar.xadvance = int.Parse(FindKeyValue(tokens, "xadvance"));
if (fontInfo.isPacked)
{
int chnl = int.Parse(FindKeyValue(tokens, "chnl"));
thisChar.channel = (int)Mathf.Round(Mathf.Log(chnl) / Mathf.Log(2));
}
fontInfo.chars.Add(thisChar);
}
else if (tokens[0] == "kerning")
{
Kerning thisKerning = new Kerning();
thisKerning.first = int.Parse(FindKeyValue(tokens, "first"));
thisKerning.second = int.Parse(FindKeyValue(tokens, "second"));
thisKerning.amount = int.Parse(FindKeyValue(tokens, "amount"));
fontInfo.kernings.Add(thisKerning);
}
}
reader.Close();
return fontInfo;
}
}
public static class Builder
{
public static Info ParseBMFont(string path)
{
Info fontInfo = null;
try
{
fontInfo = BMFontXmlImporter.Parse(path);
}
catch
{
fontInfo = BMFontTextImporter.Parse(path);
}
if (fontInfo == null || fontInfo.chars.Count == 0)
{
Debug.LogError("Font parsing returned 0 characters, check source bmfont file for errors");
return null;
}
return fontInfo;
}
public static bool BuildFont(Info fontInfo, tk2dFontData target, float scale, int charPadX, bool dupeCaps, bool flipTextureY, Texture2D gradientTexture, int gradientCount)
{
float texWidth = fontInfo.scaleW;
float texHeight = fontInfo.scaleH;
float lineHeight = fontInfo.lineHeight;
target.version = tk2dFontData.CURRENT_VERSION;
target.lineHeight = lineHeight * scale;
target.texelSize = new Vector2(scale, scale);
target.isPacked = fontInfo.isPacked;
// Get number of characters (lastindex + 1)
int maxCharId = 0;
int maxUnicodeChar = 100000;
foreach (var theChar in fontInfo.chars)
{
if (theChar.id > maxUnicodeChar)
{
// in most cases the font contains unwanted characters!
Debug.LogError("Unicode character id exceeds allowed limit: " + theChar.id.ToString() + ". Skipping.");
continue;
}
if (theChar.id > maxCharId) maxCharId = theChar.id;
}
// decide to use dictionary if necessary
// 2048 is a conservative lower floor
bool useDictionary = maxCharId > 2048;
Dictionary<int, tk2dFontChar> charDict = (useDictionary)?new Dictionary<int, tk2dFontChar>():null;
tk2dFontChar[] chars = (useDictionary)?null:new tk2dFontChar[maxCharId + 1];
int minChar = 0x7fffffff;
int maxCharWithinBounds = 0;
int numLocalChars = 0;
float largestWidth = 0.0f;
foreach (var theChar in fontInfo.chars)
{
tk2dFontChar thisChar = new tk2dFontChar();
int id = theChar.id;
int x = theChar.x;
int y = theChar.y;
int width = theChar.width;
int height = theChar.height;
int xoffset = theChar.xoffset;
int yoffset = theChar.yoffset;
int xadvance = theChar.xadvance + charPadX;
// special case, if the width and height are zero, the origin doesn't need to be offset
// handles problematic case highlighted here:
// http://2dtoolkit.com/forum/index.php/topic,89.msg220.html
if (width == 0 && height == 0)
{
xoffset = 0;
yoffset = 0;
}
// precompute required data
if (theChar.texOverride)
{
int w = theChar.texW;
int h = theChar.texH;
if (theChar.texFlipped)
{
h = theChar.texW;
w = theChar.texH;
}
float px = (xoffset + theChar.texOffsetX) * scale;
float py = (lineHeight - yoffset - theChar.texOffsetY) * scale;
thisChar.p0 = new Vector3(px, py , 0);
thisChar.p1 = new Vector3(px + w * scale, py - h * scale, 0);
thisChar.uv0 = new Vector2((theChar.texX) / texWidth, (theChar.texY + theChar.texH) / texHeight);
thisChar.uv1 = new Vector2((theChar.texX + theChar.texW) / texWidth, (theChar.texY) / texHeight);
if (flipTextureY)
{
float tmp = 0;
if (theChar.texFlipped)
{
tmp = thisChar.uv1.x;
thisChar.uv1.x = thisChar.uv0.x;
thisChar.uv0.x = tmp;
}
else
{
tmp = thisChar.uv1.y;
thisChar.uv1.y = thisChar.uv0.y;
thisChar.uv0.y = tmp;
}
}
thisChar.flipped = theChar.texFlipped;
}
else
{
float px = xoffset * scale;
float py = (lineHeight - yoffset) * scale;
thisChar.p0 = new Vector3(px, py, 0);
thisChar.p1 = new Vector3(px + width * scale, py - height * scale, 0);
if (flipTextureY)
{
thisChar.uv0 = new Vector2(x / texWidth, y / texHeight);
thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y + height / texHeight);
}
else
{
thisChar.uv0 = new Vector2(x / texWidth, 1.0f - y / texHeight);
thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y - height / texHeight);
}
thisChar.flipped = false;
}
thisChar.advance = xadvance * scale;
thisChar.channel = theChar.channel;
largestWidth = Mathf.Max(thisChar.advance, largestWidth);
// Needs gradient data
if (gradientTexture != null)
{
// build it up assuming the first gradient
float x0 = (float)(0.0f / gradientCount);
float x1 = (float)(1.0f / gradientCount);
float y0 = 1.0f;
float y1 = 0.0f;
// align to glyph if necessary
thisChar.gradientUv = new Vector2[4];
thisChar.gradientUv[0] = new Vector2(x0, y0);
thisChar.gradientUv[1] = new Vector2(x1, y0);
thisChar.gradientUv[2] = new Vector2(x0, y1);
thisChar.gradientUv[3] = new Vector2(x1, y1);
}
if (id <= maxCharId)
{
maxCharWithinBounds = (id > maxCharWithinBounds) ? id : maxCharWithinBounds;
minChar = (id < minChar) ? id : minChar;
if (useDictionary)
charDict[id] = thisChar;
else
chars[id] = thisChar;
++numLocalChars;
}
}
// duplicate capitals to lower case, or vice versa depending on which ones exist
if (dupeCaps)
{
for (int uc = 'A'; uc <= 'Z'; ++uc)
{
int lc = uc + ('a' - 'A');
if (useDictionary)
{
if (charDict.ContainsKey(uc))
charDict[lc] = charDict[uc];
else if (charDict.ContainsKey(lc))
charDict[uc] = charDict[lc];
}
else
{
if (chars[lc] == null) chars[lc] = chars[uc];
else if (chars[uc] == null) chars[uc] = chars[lc];
}
}
}
// share null char, same pointer
var nullChar = new tk2dFontChar();
nullChar.gradientUv = new Vector2[4]; // this would be null otherwise
nullChar.channel = 0;
target.largestWidth = largestWidth;
if (useDictionary)
{
// guarantee at least the first 256 characters
for (int i = 0; i < 256; ++i)
{
if (!charDict.ContainsKey(i))
charDict[i] = nullChar;
}
target.chars = null;
target.SetDictionary(charDict);
target.useDictionary = true;
}
else
{
target.chars = new tk2dFontChar[maxCharId + 1];
for (int i = 0; i <= maxCharId; ++i)
{
target.chars[i] = chars[i];
if (target.chars[i] == null)
{
target.chars[i] = nullChar; // zero everything, null char
}
}
target.charDict = null;
target.useDictionary = false;
}
// kerning
target.kerning = new tk2dFontKerning[fontInfo.kernings.Count];
for (int i = 0; i < target.kerning.Length; ++i)
{
tk2dFontKerning kerning = new tk2dFontKerning();
kerning.c0 = fontInfo.kernings[i].first;
kerning.c1 = fontInfo.kernings[i].second;
kerning.amount = fontInfo.kernings[i].amount * scale;
target.kerning[i] = kerning;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using DynamicMVC.Annotations;
using DynamicMVC.EntityMetadataLibrary.Interfaces;
using DynamicMVC.Shared;
using DynamicMVC.Shared.Interfaces;
using DynamicMVC.Shared.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DynamicMVC.EntityMetadataLibraryTest
{
#region UsedForTesting
[DynamicEntity]
public class Hello
{
public Hello()
{
Worlds = new HashSet<World>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public ICollection<World> Worlds { get; set; }
}
[Serializable]
[DynamicEntity]
public class World
{
[ScaffoldColumn(true)]
public int Id { get; set; }
public int HelloId { get; set; }
public Hello Hello { get; set; }
}
public class Test
{
public string TestProperty { get; set; }
public string TestProperty2 { get; set; }
public ICollection<World> Worlds { get; set; }
}
[DynamicEntity]
public class SimplePropertyTest
{
public int NormalInt { get; set; }
public long NormalLong { get; set; }
public Guid NormalGuid { get; set; }
public DateTime NormalDateTime { get; set; }
public bool NormalBool { get; set; }
public decimal NormalDecimal { get; set; }
public float NormalFloat { get; set; }
public double NormalDouble { get; set; }
public int? NullableInt { get; set; }
public long? NullableLong { get; set; }
public Guid? NullableGuid { get; set; }
public DateTime? NullableDateTime { get; set; }
public bool? NullableBool { get; set; }
public decimal? NullableDecimal { get; set; }
public float? NullableFloat { get; set; }
public double? NullableDouble { get; set; }
}
[DynamicEntity]
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int? FavoriteColorId { get; set; }
public int Age { get; set; }
public bool? Minor { get; set; }
public FavoriteColor FavoriteColor { get; set; }
}
[DynamicEntity]
public class FavoriteColor
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Person> People { get; set; }
}
#endregion
/// <summary>
/// Summary description for ApplicationMetadataProviderTest
/// </summary>
[TestClass]
public class ApplicationMetadataProviderTest
{
[TestInitialize]
public void TestInitialize()
{
var types = new List<Type>();
types.Add(typeof(Hello));
types.Add(typeof(World));
types.Add(typeof(Test));
types.Add(typeof(SimplePropertyTest));
Types = types;
Container.EagerLoad();
var container = Container.GetConfiguredContainer();
DynamicMVC.EntityMetadataLibrary.UnityConfig.RegisterTypes(container);
var applicationMetadataProvider = new ApplicationMetadataProvider(Types, Types, Types);
Container.RegisterInstance<IApplicationMetadataProvider>(applicationMetadataProvider);
}
public List<Type> Types { get; set; }
[TestMethod]
public void EntityMetadata_TwoDynamicEntites_ReturnsCorrectTypeNames()
{
//Arrange
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
//Assert
Assert.IsTrue(entityMetadatas.Any(x => x.TypeName == "Hello"));
Assert.IsTrue(entityMetadatas.Any(x => x.TypeName == "World"));
}
[TestMethod]
public void EntityMetadata_DynamicEntityWithNullableProperty_SetsNullToTrue()
{
//Arrange
Types.Clear();
Types.Add(typeof(Person));
Types.Add(typeof(FavoriteColor));
var applicationMetadataProvider = new ApplicationMetadataProvider(Types, Types, Types);
Container.RegisterInstance<IApplicationMetadataProvider>(applicationMetadataProvider);
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
//Assert
var person = entityMetadatas.Single(x => x.TypeName == "Person");
var favoriteColorId = person.EntityPropertyMetadata.Single(x => x.PropertyName == "FavoriteColorId");
var age = person.EntityPropertyMetadata.Single(x => x.PropertyName == "Age");
var minor = person.EntityPropertyMetadata.Single(x => x.PropertyName == "Minor");
Assert.IsTrue(favoriteColorId.IsNullableType);
Assert.IsTrue(age.IsNullableType == false);
Assert.IsTrue(minor.IsNullableType);
}
[TestMethod]
public void EntityMetadata_WithOneDynamicModelAttribute_SetsAttributeCorrectly()
{
//Arrange
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
//Assert
var helloEntityMetadata = entityMetadatas.Single(x => x.TypeName == "Hello");
var worldEntityMetadata = entityMetadatas.Single(x => x.TypeName == "World");
Assert.IsTrue(worldEntityMetadata.EntityAttributes.Any(x => x is SerializableAttribute));
Assert.IsTrue(helloEntityMetadata.EntityAttributes.Count == 1);
Assert.IsTrue(worldEntityMetadata.EntityAttributes.Count == 2);
}
[TestMethod]
public void EntityMetadata_PrimitivePropertis_ReturnsPrimitiveEntityPropertyMetadata()
{
//Arrange
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
//Assert
var helloEntityMetadata = entityMetadatas.Single(x => x.TypeName == "SimplePropertyTest");
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalInt").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalLong").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalFloat").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalGuid").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalDateTime").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalDecimal").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NormalDouble").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableInt").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableLong").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableFloat").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableGuid").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableDateTime").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableDecimal").IsSimple);
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "NullableDouble").IsSimple);
}
[TestMethod]
public void EntityMetadata_CollectionProperties_ReturnsCollectionEntityPropertyMetadata()
{
//Arrange
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
//Assert
var helloEntityMetadata = entityMetadatas.Single(x => x.TypeName == "Hello");
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "Worlds").IsCollection);
}
[TestMethod]
public void EntityMetadata_ComplextEntityProperties_ReturnsComplexEntityPropertyMetadata()
{
//Arrange
var entityMetadataManager = Container.Resolve<IEntityMetadataManager>();
//Act
var entityMetadatas = entityMetadataManager.GetEntityMetadatas().ToList();
var helloEntityMetadata = entityMetadatas.Single(x => x.TypeName == "World");
Assert.IsTrue(helloEntityMetadata.EntityPropertyMetadata.Single(x => x.PropertyName == "Hello").IsComplexEntity);
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct UInt64 : IComparable, IConvertible, IFormattable, IComparable<ulong>, IEquatable<ulong>, ISpanFormattable
{
private readonly ulong m_value; // Do not rename (binary serialization)
public const ulong MaxValue = (ulong)0xffffffffffffffffL;
public const ulong MinValue = 0x0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt64, this method throws an ArgumentException.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (value is ulong)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
ulong i = (ulong)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt64);
}
public int CompareTo(ulong value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(object obj)
{
if (!(obj is ulong))
{
return false;
}
return m_value == ((ulong)obj).m_value;
}
[NonVersionable]
public bool Equals(ulong obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return ((int)m_value) ^ (int)(m_value >> 32);
}
public override string ToString()
{
return Number.FormatUInt64(m_value, null, null);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatUInt64(m_value, null, provider);
}
public string ToString(string format)
{
return Number.FormatUInt64(m_value, format, null);
}
public string ToString(string format, IFormatProvider provider)
{
return Number.FormatUInt64(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatUInt64(m_value, format, provider, destination, out charsWritten);
}
[CLSCompliant(false)]
public static ulong Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(string s, out ulong result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, out ulong result)
{
return Number.TryParseUInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ulong result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out ulong result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt64;
}
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 Convert.ToInt32(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 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, "UInt64", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// devsolution 2003/6/17: Added items for calendar control
// must have Devsolution.Portal.dll in /bin for generating of the calendar
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using DevSolution.Portal;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Helpers;
using Rainbow.Framework.Web.UI.WebControls;
using History=Rainbow.Framework.History;
// devsolution 2003/6/17: Finish - Added items for calendar control
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Event list
/// </summary>
[History("Mario Hartmann", "mario@hartmann.net", "1.3", "2003/10/01", "moved to seperate folder")]
[History("devsolution", "devsolution@yahoo.com", "", "2003/06/17", "Added Calendar capability")]
[
History("devsolution", "devsolution@yahoo.com", "", "2003/06/23",
"Fixed when another control on page has postback, calendar would not show")]
public partial class Events : PortalModuleControl
{
/// <summary>
///
/// </summary>
private DataSet dsEventData;
// devsolution 2003/6/17: Finished - Added items for calendar control
/// <summary>
/// The Page_Load event handler on this User Control is used to
/// obtain a DataReader of event information from the Events
/// table, and then databind the results to a templated DataList
/// server control. It uses the Rainbow.EventDB()
/// data component to encapsulate all data functionality.
/// </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)
{
// Obtain the list of events from the Events table
// and bind to the DataList Control
// devsolution 2003/6/23: Fix for when another control is on
// page and a postback from that occurs calendar doesn't draw
// now it doesn't care if postback -- always draw it
// Test Case: To reproduce add picture module that has to page, page through
// picture module data and calendar will go away
int Month = (txtDisplayMonth.Text == string.Empty ? DateTime.Now.Month : int.Parse(txtDisplayMonth.Text));
int Year = (txtDisplayYear.Text == string.Empty ? DateTime.Now.Year : int.Parse(txtDisplayYear.Text));
RenderEvents(Month, Year);
// devsolution 2003/6/23: Fix
}
/// <summary>
/// Public constructor. Sets base settings for module.
/// </summary>
public Events()
{
// Set Editor Settings jviladiu@portalservices.net 2004/07/30 (added by Jakob Hansen)
// Modified by Hongwei Shen 2005/09/24
SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
int groupBase = (int) group;
HtmlEditorDataType.HtmlEditorSettings(_baseSettings, group);
//Indah Fuldner
SettingItem RepeatDirection = new SettingItem(new ListDataType("Vertical;Horizontal"));
RepeatDirection.Group = group; //SettingItemGroup.MODULE_SPECIAL_SETTINGS;
RepeatDirection.Required = true;
RepeatDirection.Value = "Vertical";
RepeatDirection.Order = groupBase + 20; //10;
_baseSettings.Add("RepeatDirectionSetting", RepeatDirection);
SettingItem RepeatColumn = new SettingItem(new IntegerDataType());
RepeatColumn.Group = group; // SettingItemGroup.MODULE_SPECIAL_SETTINGS;
RepeatColumn.Required = true;
RepeatColumn.Value = "1";
RepeatColumn.MinValue = 1;
RepeatColumn.MaxValue = 10;
RepeatColumn.Order = groupBase + 25; // 20;
_baseSettings.Add("RepeatColumns", RepeatColumn);
SettingItem showItemBorder = new SettingItem(new BooleanDataType());
showItemBorder.Group = group; //SettingItemGroup.MODULE_SPECIAL_SETTINGS;
showItemBorder.Order = groupBase + 30;
showItemBorder.Value = "false";
_baseSettings.Add("ShowBorder", showItemBorder);
//End Indah Fuldner
SettingItem DelayExpire = new SettingItem(new IntegerDataType());
DelayExpire.Group = group; //SettingItemGroup.MODULE_SPECIAL_SETTINGS;
DelayExpire.Order = groupBase + 35; // 40;
DelayExpire.Value = "365"; // 1 year
DelayExpire.MinValue = 0;
DelayExpire.MaxValue = 3650; //10 years
_baseSettings.Add("DelayExpire", DelayExpire);
// devsolution 2003/6/17: Added items for calendar control
// Show Calendar - Show a visual calendar with
// Default is false for backward compatibility
// Must edit collection properties and set to true
// to show calendar
SettingItem ShowCalendar = new SettingItem(new BooleanDataType());
ShowCalendar.Group = group; //SettingItemGroup.MODULE_SPECIAL_SETTINGS;
ShowCalendar.Order = groupBase + 40; // 50;
ShowCalendar.Value = "false";
_baseSettings.Add("ShowCalendar", ShowCalendar);
// devsolution 2003/6/17: Finished - Added items for calendar control
// Change by Geert.Audenaert@Syntegra.Com
// Date: 27/2/2003
SupportsWorkflow = true;
// End Change Geert.Audenaert@Syntegra.Com
}
/// <summary>
/// PreviousMonth_Click is fired when previous is clicked
/// this function goes back one month by passing in -1 (add -1 month)
/// to calendar
/// </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 PreviousMonth_Click(object sender, EventArgs e)
{
ChangeMonth(-1);
}
/// <summary>
/// Main routine to handle changing the month to display relative
/// to current display month and render it
/// </summary>
/// <param name="AddMonth">number of months to add (positive or negative allowed)</param>
private void ChangeMonth(int AddMonth)
{
int DisplayMonth = int.Parse(txtDisplayMonth.Text);
int DisplayYear = int.Parse(txtDisplayYear.Text);
DisplayMonth = DisplayMonth + AddMonth;
if (DisplayMonth < 1)
{
DisplayYear--;
DisplayMonth = 12;
}
else if (DisplayMonth > 12)
{
DisplayYear++;
DisplayMonth = 1;
}
txtDisplayMonth.Text = DisplayMonth.ToString();
txtDisplayYear.Text = DisplayYear.ToString();
RenderEvents(DisplayMonth, DisplayYear);
}
/// <summary>
/// NextMonth_Click fired when next month link is clicked
/// Addes 1 month to current month by calling ChangeMonth
/// </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 NextMonth_Click(object sender, EventArgs e)
{
ChangeMonth(1);
}
/// <summary>
/// Wrapper to call Devsolution.Portal dll
/// If all day should not return anything
/// if time passed and not allday should display in HH:MM AM or HH:MM PM format
/// </summary>
/// <param name="AllDay">if set to <c>true</c> [all day].</param>
/// <param name="StartTime">The start time.</param>
/// <returns></returns>
public string DisplayTime(bool AllDay, object StartTime)
{
EventCalendar eventcalendar = new EventCalendar();
return eventcalendar.DisplayTime(AllDay, StartTime);
}
// devsolution 2003/6/17: Finished - Added items for calendar control
/// <summary>
/// devsolution 2003/6/17:
/// Change to make a RenderEvents for modularity
/// Routine to add show calendar logic
/// And Clean up code as now the calendar next and previous
/// controls must re-render the display and get the data again
/// e.g. modularize the code
/// </summary>
/// <param name="DisplayMonth">Month to display 1=Jan, 2=Feb, etc</param>
/// <param name="DisplayYear">Year to display YYYY, 2003 for 2003</param>
private void RenderEvents(int DisplayMonth, int DisplayYear)
{
EventsDB events = new EventsDB();
myDataList.RepeatDirection = (Settings["RepeatDirectionSetting"].ToString() == "Horizontal"
? RepeatDirection.Horizontal
: RepeatDirection.Vertical);
myDataList.RepeatColumns = Int32.Parse(Settings["RepeatColumns"].ToString());
if (bool.Parse(Settings["ShowBorder"].ToString()))
{
//myDataList.BorderWidth=Unit.Pixel(1);
myDataList.ItemStyle.BorderWidth = Unit.Pixel(1);
}
dsEventData = events.GetEvents(ModuleID, Version);
myDataList.DataSource = dsEventData;
myDataList.DataBind();
// devsolution 2003/6/17: Added items for calendar control
if (bool.Parse(Settings["ShowCalendar"].ToString()))
{
CalendarPanel.Visible = true;
string DisplayDate = string.Empty;
// devsolution 2003/6/17: Must have Devsolution.Portal.dll in \bin for calendar display functionality
EventCalendar eventcalendar = new EventCalendar();
lblCalendar.Text =
eventcalendar.GenerateCalendar(ModuleID, DisplayMonth, DisplayYear, out DisplayDate, dsEventData);
lblDisplayDate.Text = DisplayDate;
}
// devsolution 2003/6/17: Finished - Added items for calendar control
myDataList.DataSource = dsEventData;
myDataList.DataBind();
}
#region General Implementation
/// <summary>
/// GUID of module (mandatory)
/// </summary>
/// <value></value>
/// <remarks>
/// </remarks>
public override Guid GuidID
{
get { return new Guid("{EF9B29C5-E481-49A6-9383-8ED3AB42DDA0}"); }
}
#region Search Implementation
/// <summary>
/// Searchable module
/// </summary>
/// <value></value>
public override bool Searchable
{
get { return true; }
}
/// <summary>
/// Searchable module implementation
/// </summary>
/// <param name="portalID">The portal ID</param>
/// <param name="userID">ID of the user is searching</param>
/// <param name="searchString">The text to search</param>
/// <param name="searchField">The fields where perfoming the search</param>
/// <returns>
/// The SELECT sql to perform a search on the current module
/// </returns>
public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField)
{
SearchDefinition s =
new SearchDefinition("rb_Events", "Title", "Description", "CreatedByUser", "CreatedDate", searchField);
//Add extra search fields here, this way
s.ArrSearchFields.Add("itm.WhereWhen");
return s.SearchSqlSelect(portalID, userID, searchString);
}
#endregion
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
# endregion
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
// devsolution 2003/6/17: Added items for calendar control
PreviousMonth.Click += new EventHandler(PreviousMonth_Click);
NextMonth.Click += new EventHandler(NextMonth_Click);
// devsolution 2003/6/17: Finish - Added items for calendar control
Load += new EventHandler(Page_Load);
// Create a new Title the control
// ModuleTitle = new DesktopModuleTitle();
// Set here title properties
// Add support for the edit page
AddText = "EVENTS_ADD";
AddUrl = "~/DesktopModules/CommunityModules/Events/EventsEdit.aspx";
// Add title ad the very beginning of
// the control's controls collection
// Controls.AddAt(0, ModuleTitle);
// Mark Brown: Added for Calendar
if (txtDisplayMonth.Text.Length == 0)
{
txtDisplayMonth.Text = DateTime.Now.Month.ToString();
txtDisplayYear.Text = DateTime.Now.Year.ToString();
}
// Mark Brown: End = Added for Calendar
base.OnInit(e);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Content.Server.Hands.Components;
using Content.Server.Weapon.Ranged.Ammunition.Components;
using Content.Server.Weapon.Ranged.Barrels.Components;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Item;
using Content.Shared.Verbs;
using Content.Shared.Weapons.Ranged;
using Content.Shared.Weapons.Ranged.Barrels.Components;
using Content.Shared.Weapons.Ranged.Components;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Player;
namespace Content.Server.Weapon.Ranged;
public sealed partial class GunSystem
{
private void AddEjectMagazineVerb(EntityUid uid, MagazineBarrelComponent component, GetVerbsEvent<AlternativeVerb> args)
{
if (args.Hands == null ||
!args.CanAccess ||
!args.CanInteract ||
!component.HasMagazine ||
!_blocker.CanPickup(args.User))
return;
if (component.MagNeedsOpenBolt && !component.BoltOpen)
return;
AlternativeVerb verb = new()
{
Text = MetaData(component.MagazineContainer.ContainedEntity!.Value).EntityName,
Category = VerbCategory.Eject,
Act = () => RemoveMagazine(args.User, component)
};
args.Verbs.Add(verb);
}
private void AddMagazineInteractionVerbs(EntityUid uid, MagazineBarrelComponent component, GetVerbsEvent<InteractionVerb> args)
{
if (args.Hands == null ||
!args.CanAccess ||
!args.CanInteract)
return;
// Toggle bolt verb
InteractionVerb toggleBolt = new()
{
Text = component.BoltOpen
? Loc.GetString("close-bolt-verb-get-data-text")
: Loc.GetString("open-bolt-verb-get-data-text"),
Act = () => component.BoltOpen = !component.BoltOpen
};
args.Verbs.Add(toggleBolt);
// Are we holding a mag that we can insert?
if (args.Using is not {Valid: true} @using ||
!CanInsertMagazine(args.User, @using, component) ||
!_blocker.CanDrop(args.User))
return;
// Insert mag verb
InteractionVerb insert = new()
{
Text = MetaData(@using).EntityName,
Category = VerbCategory.Insert,
Act = () => InsertMagazine(args.User, @using, component)
};
args.Verbs.Add(insert);
}
private void OnMagazineExamine(EntityUid uid, MagazineBarrelComponent component, ExaminedEvent args)
{
args.PushMarkup(Loc.GetString("server-magazine-barrel-component-on-examine", ("caliber", component.Caliber)));
foreach (var magazineType in GetMagazineTypes(component))
{
args.PushMarkup(Loc.GetString("server-magazine-barrel-component-on-examine-magazine-type", ("magazineType", magazineType)));
}
}
private void OnMagazineUse(EntityUid uid, MagazineBarrelComponent component, UseInHandEvent args)
{
if (args.Handled) return;
// Behavior:
// If bolt open just close it
// If bolt closed then cycle
// If we cycle then get next round
// If no more round then open bolt
args.Handled = true;
if (component.BoltOpen)
{
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundBoltClosed.GetSound(), component.Owner, AudioParams.Default.WithVolume(-5));
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-use-entity-bolt-closed"), component.Owner, Filter.Entities(args.User));
component.BoltOpen = false;
return;
}
// Could play a rack-slide specific sound here if you're so inclined (if the chamber is empty but rounds are available)
CycleMagazine(component, true);
return;
}
public void UpdateMagazineAppearance(MagazineBarrelComponent component)
{
if (!TryComp(component.Owner, out AppearanceComponent? appearanceComponent)) return;
appearanceComponent.SetData(BarrelBoltVisuals.BoltOpen, component.BoltOpen);
appearanceComponent.SetData(MagazineBarrelVisuals.MagLoaded, component.MagazineContainer.ContainedEntity != null);
appearanceComponent.SetData(AmmoVisuals.AmmoCount, component.ShotsLeft);
appearanceComponent.SetData(AmmoVisuals.AmmoMax, component.Capacity);
}
private void OnMagazineGetState(EntityUid uid, MagazineBarrelComponent component, ref ComponentGetState args)
{
(int, int)? count = null;
if (component.MagazineContainer.ContainedEntity is {Valid: true} magazine &&
TryComp(magazine, out RangedMagazineComponent? rangedMagazineComponent))
{
count = (rangedMagazineComponent.ShotsLeft, rangedMagazineComponent.Capacity);
}
args.State = new MagazineBarrelComponentState(
component.ChamberContainer.ContainedEntity != null,
component.FireRateSelector,
count,
component.SoundGunshot.GetSound());
}
private void OnMagazineInteractUsing(EntityUid uid, MagazineBarrelComponent component, InteractUsingEvent args)
{
if (args.Handled) return;
if (CanInsertMagazine(args.User, args.Used, component, false))
{
InsertMagazine(args.User, args.Used, component);
args.Handled = true;
return;
}
// Insert 1 ammo
if (TryComp(args.Used, out AmmoComponent? ammoComponent))
{
if (!component.BoltOpen)
{
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-ammo-bolt-closed"), component.Owner, Filter.Entities(args.User));
return;
}
if (ammoComponent.Caliber != component.Caliber)
{
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-wrong-caliber"), component.Owner, Filter.Entities(args.User));
return;
}
if (component.ChamberContainer.ContainedEntity == null)
{
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-ammo-success"), component.Owner, Filter.Entities(args.User));
component.ChamberContainer.Insert(args.Used);
component.Dirty(EntityManager);
UpdateMagazineAppearance(component);
args.Handled = true;
return;
}
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-ammo-full"), component.Owner, Filter.Entities(args.User));
}
}
private void OnMagazineInit(EntityUid uid, MagazineBarrelComponent component, ComponentInit args)
{
component.ChamberContainer = uid.EnsureContainer<ContainerSlot>($"{component.GetType()}-chamber");
component.MagazineContainer = uid.EnsureContainer<ContainerSlot>($"{component.GetType()}-magazine", out var existing);
if (!existing && component.MagFillPrototype != null)
{
var magEntity = EntityManager.SpawnEntity(component.MagFillPrototype, Transform(uid).Coordinates);
component.MagazineContainer.Insert(magEntity);
}
// Temporary coz client doesn't know about magfill.
component.Dirty(EntityManager);
}
private void OnMagazineMapInit(EntityUid uid, MagazineBarrelComponent component, MapInitEvent args)
{
UpdateMagazineAppearance(component);
}
public bool TryEjectChamber(MagazineBarrelComponent component)
{
if (component.ChamberContainer.ContainedEntity is {Valid: true} chamberEntity)
{
if (!component.ChamberContainer.Remove(chamberEntity))
{
return false;
}
var ammoComponent = EntityManager.GetComponent<AmmoComponent>(chamberEntity);
if (!ammoComponent.Caseless)
{
EjectCasing(chamberEntity);
}
return true;
}
return false;
}
public bool TryFeedChamber(MagazineBarrelComponent component)
{
if (component.ChamberContainer.ContainedEntity != null)
{
return false;
}
// Try and pull a round from the magazine to replace the chamber if possible
var magazine = component.MagazineContainer.ContainedEntity;
var magComp = EntityManager.GetComponentOrNull<RangedMagazineComponent>(magazine);
if (magComp == null || TakeAmmo(magComp) is not {Valid: true} nextRound)
{
return false;
}
component.ChamberContainer.Insert(nextRound);
if (component.AutoEjectMag && magazine != null && EntityManager.GetComponent<RangedMagazineComponent>(magazine.Value).ShotsLeft == 0)
{
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundAutoEject.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2));
component.MagazineContainer.Remove(magazine.Value);
// TODO: Should be a state or something, waste of bandwidth
RaiseNetworkEvent(new MagazineAutoEjectEvent {Uid = component.Owner});
}
return true;
}
private void CycleMagazine(MagazineBarrelComponent component, bool manual = false)
{
if (component.BoltOpen)
return;
TryEjectChamber(component);
TryFeedChamber(component);
if (component.ChamberContainer.ContainedEntity == null && !component.BoltOpen)
{
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundBoltOpen.GetSound(), component.Owner, AudioParams.Default.WithVolume(-5));
if (_container.TryGetContainingContainer(component.Owner, out var container))
{
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-cycle-bolt-open"), component.Owner, Filter.Entities(container.Owner));
}
component.BoltOpen = true;
return;
}
if (manual)
{
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundRack.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2));
}
component.Dirty(EntityManager);
UpdateMagazineAppearance(component);
}
public EntityUid? PeekAmmo(MagazineBarrelComponent component)
{
return component.BoltOpen ? null : component.ChamberContainer.ContainedEntity;
}
public EntityUid? TakeProjectile(MagazineBarrelComponent component, EntityCoordinates spawnAt)
{
if (component.BoltOpen)
return null;
var entity = component.ChamberContainer.ContainedEntity;
CycleMagazine(component);
return entity != null ? TakeBullet(EntityManager.GetComponent<AmmoComponent>(entity.Value), spawnAt) : null;
}
public List<MagazineType> GetMagazineTypes(MagazineBarrelComponent component)
{
var types = new List<MagazineType>();
foreach (MagazineType mag in Enum.GetValues(typeof(MagazineType)))
{
if ((component.MagazineTypes & mag) != 0)
{
types.Add(mag);
}
}
return types;
}
public void RemoveMagazine(EntityUid user, MagazineBarrelComponent component)
{
var mag = component.MagazineContainer.ContainedEntity;
if (mag == null)
return;
if (component.MagNeedsOpenBolt && !component.BoltOpen)
{
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-remove-magazine-bolt-closed"), component.Owner, Filter.Entities(user));
return;
}
component.MagazineContainer.Remove(mag.Value);
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundMagEject.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2));
if (TryComp(user, out HandsComponent? handsComponent))
{
handsComponent.PutInHandOrDrop(EntityManager.GetComponent<SharedItemComponent>(mag.Value));
}
component.Dirty(EntityManager);
UpdateMagazineAppearance(component);
}
public bool CanInsertMagazine(EntityUid user, EntityUid magazine, MagazineBarrelComponent component, bool quiet = true)
{
if (!TryComp(magazine, out RangedMagazineComponent? magazineComponent))
{
return false;
}
if ((component.MagazineTypes & magazineComponent.MagazineType) == 0)
{
if (!quiet)
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-wrong-magazine-type"), component.Owner, Filter.Entities(user));
return false;
}
if (magazineComponent.Caliber != component.Caliber)
{
if (!quiet)
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-wrong-caliber"), component.Owner, Filter.Entities(user));
return false;
}
if (component.MagNeedsOpenBolt && !component.BoltOpen)
{
if (!quiet)
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-bolt-closed"), component.Owner, Filter.Entities(user));
return false;
}
if (component.MagazineContainer.ContainedEntity == null)
return true;
if (!quiet)
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-already-holding-magazine"), component.Owner, Filter.Entities(user));
return false;
}
public void InsertMagazine(EntityUid user, EntityUid magazine, MagazineBarrelComponent component)
{
SoundSystem.Play(Filter.Pvs(component.Owner), component.SoundMagInsert.GetSound(), component.Owner, AudioParams.Default.WithVolume(-2));
_popup.PopupEntity(Loc.GetString("server-magazine-barrel-component-interact-using-success"), component.Owner, Filter.Entities(user));
component.MagazineContainer.Insert(magazine);
component.Dirty(EntityManager);
UpdateMagazineAppearance(component);
}
}
| |
/*
* LinkLabel.cs - Implementation of the
* "System.Windows.Forms.LinkLabel" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* With contributions from Ian Fung <if26@cornell.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.Drawing;
using System.Drawing.Text;
using System.Collections;
[TODO]
public class LinkLabel : Label, IButtonControl
{
// Internal state.
private Color activeLinkColor;
private Color disabledLinkColor;
private LinkArea linkArea;
private LinkBehavior linkBehavior;
private Color linkColor;
private LinkCollection links;
private bool linkVisited;
private Color visitedLinkColor;
[TODO]
public LinkLabel()
{
}
// Implement IButtonControl
public DialogResult DialogResult
{
get
{
return DialogResult.Abort;
}
set
{
}
}
// Get or set this LinkLabel's properties.
[TODO]
public Color ActiveLinkColor
{
get
{
return activeLinkColor;
}
set
{
activeLinkColor = value;
}
}
[TODO]
public Color DisabledLinkColor
{
get
{
return disabledLinkColor;
}
set
{
disabledLinkColor = value;
}
}
[TODO]
public LinkArea LinkArea
{
get
{
return linkArea;
}
set
{
linkArea = value;
}
}
[TODO]
public LinkBehavior LinkBehavior
{
get
{
return linkBehavior;
}
set
{
linkBehavior = value;
}
}
[TODO]
public Color LinkColor
{
get
{
return linkColor;
}
set
{
linkColor = value;
}
}
[TODO]
public LinkCollection Links
{
get
{
return links;
}
set
{
links = value;
}
}
[TODO]
public override string Text
{
get
{
return text;
}
set
{
text = value;
}
}
[TODO]
public Color VisitedLinkColor
{
get
{
return visitedLinkColor;
}
set
{
visitedLinkColor = value;
}
}
[TODO]
public bool LinkVisited
{
get
{
return linkVisited;
}
set
{
linkVisited = value;
}
}
[TODO]
public event LinkLabelLinkClickedEventHandler LinkClicked
{
add
{
}
remove
{
}
}
[TODO]
protected override AccessibleObject CreateAccessibilityInstance()
{
return null;
}
[TODO]
protected override void CreateHandle()
{
}
[TODO]
protected override void OnEnabledChanged(EventArgs e)
{
}
[TODO]
protected override void OnFontChanged(EventArgs e)
{
}
[TODO]
protected override void OnGotFocus(EventArgs e)
{
}
[TODO]
protected override void OnKeyDown(KeyEventArgs e)
{
}
[TODO]
protected virtual void OnLinkClicked(LinkLabelLinkClickedEventArgs e)
{
}
[TODO]
protected override void OnLostFocus(EventArgs e)
{
}
[TODO]
protected override void OnMouseDown(MouseEventArgs e)
{
}
[TODO]
protected override void OnMouseLeave(EventArgs e)
{
}
[TODO]
protected override void OnMouseMove(MouseEventArgs e)
{
}
[TODO]
protected override void OnMouseUp(MouseEventArgs e)
{
}
[TODO]
protected override void OnPaint(PaintEventArgs e)
{
}
[TODO]
protected override void OnPaintBackground(PaintEventArgs e)
{
}
[TODO]
protected override void OnTextAlignChanged(EventArgs e)
{
}
[TODO]
protected override void OnTextChanged(EventArgs e)
{
}
[TODO]
protected Link PointInLink(int x, int y)
{
return null;
}
[TODO]
protected override bool ProcessDialogKey(Keys keyData)
{
return false;
}
[TODO]
protected override void Select(bool directed, bool forward)
{
}
[TODO]
protected override void SetBoundsCore(int x, int y, int width, int height,
BoundsSpecified specified)
{
}
// IButtonControl public methods
[TODO]
public virtual void NotifyDefault(bool value)
{
}
[TODO]
public virtual void PerformClick()
{
}
[TODO]
public class Link
{
private bool enabled;
private int length;
private object linkData;
private int start;
private bool visited;
[TODO]
public bool Enabled
{
get
{
return enabled;
}
set
{
enabled = value;
}
}
[TODO]
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
[TODO]
public object LinkData
{
get
{
return linkData;
}
set
{
linkData = value;
}
}
[TODO]
public int Start
{
get
{
return start;
}
set
{
start = value;
}
}
[TODO]
public bool Visited
{
get
{
return visited;
}
set
{
visited = value;
}
}
}
[TODO]
public class LinkCollection : IList
{
private int count;
private bool isReadOnly;
[TODO]
public LinkCollection(LinkLabel owner)
{
}
[TODO]
public virtual int Count
{
get
{
return count;
}
}
[TODO]
public virtual bool IsReadOnly
{
get
{
return isReadOnly;
}
}
[TODO]
public virtual LinkLabel.Link this[int index]
{
get
{
return null;
}
set
{
}
}
[TODO]
public Link Add(int start, int length)
{
return null;
}
[TODO]
public Link Add(int start, int length, object linkData)
{
return null;
}
[TODO]
public virtual void Clear()
{
}
[TODO]
public bool Contains(LinkLabel.Link link)
{
return false;
}
// Implement from IEnumerable
[TODO]
public virtual IEnumerator GetEnumerator()
{
return null;
}
// Implement from ICollection
[TODO]
public virtual void CopyTo(Array array, int index)
{
}
[TODO]
public bool IsSynchronized
{
get
{
return false;
}
}
[TODO]
public object SyncRoot
{
get
{
return null;
}
}
// Implement from IList
[TODO]
public int Add(object value)
{
return 0;
}
[TODO]
public bool Contains(object value)
{
return false;
}
[TODO]
public int IndexOf(object value)
{
return 0;
}
[TODO]
public void Insert(int index, object value)
{
}
[TODO]
public void Remove(object value)
{
}
[TODO]
public void RemoveAt(int index)
{
}
[TODO]
public bool IsFixedSize
{
get
{
return false;
}
}
[TODO]
object IList.this[int index]
{
get
{
return null;
}
set
{
}
}
}
#if !CONFIG_COMPACT_FORMS
// Process a message.
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
#endif // !CONFIG_COMPACT_FORMS
}; // class LinkLabel
}; // namespace System.Windows.Forms
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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.
//
// * Neither the name of Jim Heising 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.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.lblLoadStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.lblConnectionStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.lblPoweredBy = new System.Windows.Forms.ToolStripStatusLabel();
this.mnuMain = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuLogin = new System.Windows.Forms.ToolStripMenuItem();
this.mnuConnect = new System.Windows.Forms.ToolStripMenuItem();
this.mnuConnectOtherComputer = new System.Windows.Forms.ToolStripMenuItem();
this.mnuConnectThisComputer = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.mnuImport = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.mnuClose = new System.Windows.Forms.ToolStripMenuItem();
this.mnuEdit = new System.Windows.Forms.ToolStripMenuItem();
this.mnuSettings = new System.Windows.Forms.ToolStripMenuItem();
this.mnuExpertModeDiv = new System.Windows.Forms.ToolStripSeparator();
this.mnuExpertMode = new System.Windows.Forms.ToolStripMenuItem();
this.mnuView = new System.Windows.Forms.ToolStripMenuItem();
this.mnuQuickStart = new System.Windows.Forms.ToolStripMenuItem();
this.mnuTour = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.mnuExtensions = new System.Windows.Forms.ToolStripMenuItem();
this.mnuReceptionist = new System.Windows.Forms.ToolStripMenuItem();
this.mnuScriptSchedule = new System.Windows.Forms.ToolStripMenuItem();
this.mnuCallFlow = new System.Windows.Forms.ToolStripMenuItem();
this.mnuCallPersonalization = new System.Windows.Forms.ToolStripMenuItem();
this.mnuTestDrive = new System.Windows.Forms.ToolStripMenuItem();
this.mnuPBX = new System.Windows.Forms.ToolStripMenuItem();
this.mnuVoIPProviders = new System.Windows.Forms.ToolStripMenuItem();
this.mnuCallHistory = new System.Windows.Forms.ToolStripMenuItem();
this.mnuPlugins = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuShowCommonTasks = new System.Windows.Forms.ToolStripMenuItem();
this.mnuLanguage = new System.Windows.Forms.ToolStripMenuItem();
this.mnuEnglish = new System.Windows.Forms.ToolStripMenuItem();
this.mnuGerman = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHelp = new System.Windows.Forms.ToolStripMenuItem();
this.mnuUserManual = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.mnuPurchase = new System.Windows.Forms.ToolStripMenuItem();
this.mnuRegister = new System.Windows.Forms.ToolStripMenuItem();
this.mnuChangeEdition = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuSupport = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuGetModules = new System.Windows.Forms.ToolStripMenuItem();
this.checkForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAbout = new System.Windows.Forms.ToolStripMenuItem();
this.pnlMainContent = new System.Windows.Forms.Panel();
this.pnlRightOuter = new System.Windows.Forms.Panel();
this.pnlContent = new global::Controls.RoundedCornerPanel();
this.pnlExpired = new System.Windows.Forms.Panel();
this.roundedCornerPanel1 = new global::Controls.RoundedCornerPanel();
this.btnRegister = new global::Controls.LinkButton();
this.label2 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pnlLeftOuter = new System.Windows.Forms.Panel();
this.pnlCommonTasks = new global::Controls.RoundedCornerPanel();
this.btnCloseCommonTasks = new System.Windows.Forms.PictureBox();
this.grpCallHistory = new global::Controls.GroupBoxEx();
this.btnManageGeneralSettings = new global::Controls.LinkButton();
this.btnAddonModules = new global::Controls.LinkButton();
this.btnAddCallPersonalization = new global::Controls.LinkButton();
this.btnAddNewDepartment = new global::Controls.LinkButton();
this.btnNewExtension = new global::Controls.LinkButton();
this.btnGetPhoneNumber = new global::Controls.LinkButton();
this.pnlNewVersion = new System.Windows.Forms.Panel();
this.pnlDownloadNewVersion = new global::Controls.RoundedCornerPanel();
this.btnDownloadNewVersion = new global::Controls.LinkButton();
this.label1 = new System.Windows.Forms.Label();
this.pictureBox6 = new System.Windows.Forms.PictureBox();
this.btnHideUpdateNotification = new global::Controls.LinkButton();
this.pnlHeaderButtonContainer = new global::Controls.GradientPanel();
this.divExtensions = new System.Windows.Forms.PictureBox();
this.btnExtensions = new global::Controls.LinkButton();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.btnReceptionist = new global::Controls.LinkButton();
this.divCallFlow = new System.Windows.Forms.PictureBox();
this.btnScriptSchedule = new global::Controls.LinkButton();
this.btnCallFlow = new global::Controls.LinkButton();
this.divCallPersonalization = new System.Windows.Forms.PictureBox();
this.btnCallPersonalization = new global::Controls.LinkButton();
this.divTestDrive = new System.Windows.Forms.PictureBox();
this.btnTestDrive = new global::Controls.LinkButton();
this.divPBX = new System.Windows.Forms.PictureBox();
this.btnPBX = new global::Controls.LinkButton();
this.divProviders = new System.Windows.Forms.PictureBox();
this.btnProviders = new global::Controls.LinkButton();
this.divPlugins = new System.Windows.Forms.PictureBox();
this.btnPlugins = new global::Controls.LinkButton();
this.pnlHeader = new System.Windows.Forms.Panel();
this.btnBackToSummary = new global::Controls.LinkButton();
this.picHeaderIcon = new System.Windows.Forms.PictureBox();
this.picCallButlerLogo = new System.Windows.Forms.PictureBox();
this.lblHeaderCaption = new global::Controls.SmoothLabel();
this.lblViewTitle = new global::Controls.SmoothLabel();
this.openSettingsFileDialog = new System.Windows.Forms.OpenFileDialog();
this.statusStrip.SuspendLayout();
this.mnuMain.SuspendLayout();
this.pnlMainContent.SuspendLayout();
this.pnlRightOuter.SuspendLayout();
this.pnlExpired.SuspendLayout();
this.roundedCornerPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.pnlLeftOuter.SuspendLayout();
this.pnlCommonTasks.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.btnCloseCommonTasks)).BeginInit();
this.grpCallHistory.SuspendLayout();
this.pnlNewVersion.SuspendLayout();
this.pnlDownloadNewVersion.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).BeginInit();
this.pnlHeaderButtonContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.divExtensions)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divCallFlow)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divCallPersonalization)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divTestDrive)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divPBX)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divProviders)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.divPlugins)).BeginInit();
this.pnlHeader.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picHeaderIcon)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picCallButlerLogo)).BeginInit();
this.SuspendLayout();
//
// statusStrip
//
this.statusStrip.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.statusStrip, "statusStrip");
this.statusStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblLoadStatus,
this.lblConnectionStatus,
this.lblPoweredBy});
this.statusStrip.Name = "statusStrip";
this.statusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
//
// lblLoadStatus
//
this.lblLoadStatus.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lblLoadStatus.Name = "lblLoadStatus";
resources.ApplyResources(this.lblLoadStatus, "lblLoadStatus");
this.lblLoadStatus.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal;
//
// lblConnectionStatus
//
this.lblConnectionStatus.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lblConnectionStatus.Name = "lblConnectionStatus";
this.lblConnectionStatus.Padding = new System.Windows.Forms.Padding(18, 0, 0, 0);
resources.ApplyResources(this.lblConnectionStatus, "lblConnectionStatus");
//
// lblPoweredBy
//
this.lblPoweredBy.ActiveLinkColor = System.Drawing.Color.CornflowerBlue;
resources.ApplyResources(this.lblPoweredBy, "lblPoweredBy");
this.lblPoweredBy.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lblPoweredBy.IsLink = true;
this.lblPoweredBy.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.lblPoweredBy.LinkColor = System.Drawing.Color.RoyalBlue;
this.lblPoweredBy.Name = "lblPoweredBy";
this.lblPoweredBy.Spring = true;
this.lblPoweredBy.VisitedLinkColor = System.Drawing.Color.RoyalBlue;
this.lblPoweredBy.Click += new System.EventHandler(this.lblPoweredBy_Click);
//
// mnuMain
//
this.mnuMain.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(111)))), ((int)(((byte)(187)))), ((int)(((byte)(255)))));
resources.ApplyResources(this.mnuMain, "mnuMain");
this.mnuMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.mnuEdit,
this.mnuView,
this.mnuHelp});
this.mnuMain.Name = "mnuMain";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuLogin,
this.mnuConnect,
this.toolStripSeparator5,
this.mnuImport,
this.toolStripSeparator4,
this.mnuClose});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// mnuLogin
//
this.mnuLogin.Name = "mnuLogin";
resources.ApplyResources(this.mnuLogin, "mnuLogin");
this.mnuLogin.Click += new System.EventHandler(this.mnuLogin_Click);
//
// mnuConnect
//
this.mnuConnect.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuConnectOtherComputer,
this.mnuConnectThisComputer});
this.mnuConnect.Image = global::CallButler.Manager.Properties.Resources.connection_16;
this.mnuConnect.Name = "mnuConnect";
resources.ApplyResources(this.mnuConnect, "mnuConnect");
//
// mnuConnectOtherComputer
//
this.mnuConnectOtherComputer.Name = "mnuConnectOtherComputer";
resources.ApplyResources(this.mnuConnectOtherComputer, "mnuConnectOtherComputer");
this.mnuConnectOtherComputer.Click += new System.EventHandler(this.mnuConnectOtherComputer_Click);
//
// mnuConnectThisComputer
//
this.mnuConnectThisComputer.Name = "mnuConnectThisComputer";
resources.ApplyResources(this.mnuConnectThisComputer, "mnuConnectThisComputer");
this.mnuConnectThisComputer.Click += new System.EventHandler(this.mnuConnectThisComputer_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// mnuImport
//
this.mnuImport.Image = global::CallButler.Manager.Properties.Resources.import_16;
this.mnuImport.Name = "mnuImport";
resources.ApplyResources(this.mnuImport, "mnuImport");
this.mnuImport.Click += new System.EventHandler(this.mnuImport_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// mnuClose
//
this.mnuClose.Name = "mnuClose";
resources.ApplyResources(this.mnuClose, "mnuClose");
this.mnuClose.Click += new System.EventHandler(this.mnuClose_Click);
//
// mnuEdit
//
this.mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuSettings,
this.mnuExpertModeDiv,
this.mnuExpertMode});
this.mnuEdit.Name = "mnuEdit";
resources.ApplyResources(this.mnuEdit, "mnuEdit");
//
// mnuSettings
//
this.mnuSettings.Image = global::CallButler.Manager.Properties.Resources.nut_and_bolt_16;
this.mnuSettings.Name = "mnuSettings";
resources.ApplyResources(this.mnuSettings, "mnuSettings");
this.mnuSettings.Click += new System.EventHandler(this.mnuSettings_Click);
//
// mnuExpertModeDiv
//
this.mnuExpertModeDiv.Name = "mnuExpertModeDiv";
resources.ApplyResources(this.mnuExpertModeDiv, "mnuExpertModeDiv");
//
// mnuExpertMode
//
this.mnuExpertMode.CheckOnClick = true;
this.mnuExpertMode.Name = "mnuExpertMode";
resources.ApplyResources(this.mnuExpertMode, "mnuExpertMode");
this.mnuExpertMode.CheckedChanged += new System.EventHandler(this.mnuExpertMode_CheckedChanged);
this.mnuExpertMode.Click += new System.EventHandler(this.mnuExpertMode_Click);
//
// mnuView
//
this.mnuView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuQuickStart,
this.mnuTour,
this.toolStripSeparator3,
this.mnuExtensions,
this.mnuReceptionist,
this.mnuScriptSchedule,
this.mnuCallFlow,
this.mnuCallPersonalization,
this.mnuTestDrive,
this.mnuPBX,
this.mnuVoIPProviders,
this.mnuCallHistory,
this.mnuPlugins,
this.toolStripSeparator2,
this.mnuShowCommonTasks,
this.mnuLanguage});
this.mnuView.Name = "mnuView";
resources.ApplyResources(this.mnuView, "mnuView");
//
// mnuQuickStart
//
this.mnuQuickStart.Name = "mnuQuickStart";
resources.ApplyResources(this.mnuQuickStart, "mnuQuickStart");
this.mnuQuickStart.Click += new System.EventHandler(this.mnuQuickStart_Click);
//
// mnuTour
//
this.mnuTour.Name = "mnuTour";
resources.ApplyResources(this.mnuTour, "mnuTour");
this.mnuTour.Click += new System.EventHandler(this.mnuTour_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// mnuExtensions
//
this.mnuExtensions.Name = "mnuExtensions";
resources.ApplyResources(this.mnuExtensions, "mnuExtensions");
this.mnuExtensions.Click += new System.EventHandler(this.btnExtensions_Click);
//
// mnuReceptionist
//
this.mnuReceptionist.Name = "mnuReceptionist";
resources.ApplyResources(this.mnuReceptionist, "mnuReceptionist");
this.mnuReceptionist.Click += new System.EventHandler(this.btnReceptionist_Click);
//
// mnuScriptSchedule
//
this.mnuScriptSchedule.Name = "mnuScriptSchedule";
resources.ApplyResources(this.mnuScriptSchedule, "mnuScriptSchedule");
this.mnuScriptSchedule.Click += new System.EventHandler(this.btnScriptSchedule_Click);
//
// mnuCallFlow
//
this.mnuCallFlow.Name = "mnuCallFlow";
resources.ApplyResources(this.mnuCallFlow, "mnuCallFlow");
this.mnuCallFlow.Click += new System.EventHandler(this.btnCallFlow_Click);
//
// mnuCallPersonalization
//
this.mnuCallPersonalization.Name = "mnuCallPersonalization";
resources.ApplyResources(this.mnuCallPersonalization, "mnuCallPersonalization");
this.mnuCallPersonalization.Click += new System.EventHandler(this.btnPersonalGreetings_Click);
//
// mnuTestDrive
//
this.mnuTestDrive.Name = "mnuTestDrive";
resources.ApplyResources(this.mnuTestDrive, "mnuTestDrive");
this.mnuTestDrive.Click += new System.EventHandler(this.btnTestDrive_Click);
//
// mnuPBX
//
this.mnuPBX.Name = "mnuPBX";
resources.ApplyResources(this.mnuPBX, "mnuPBX");
this.mnuPBX.Click += new System.EventHandler(this.btnPBX_Click);
//
// mnuVoIPProviders
//
this.mnuVoIPProviders.Name = "mnuVoIPProviders";
resources.ApplyResources(this.mnuVoIPProviders, "mnuVoIPProviders");
this.mnuVoIPProviders.Click += new System.EventHandler(this.btnProviders_Click);
//
// mnuCallHistory
//
this.mnuCallHistory.Name = "mnuCallHistory";
resources.ApplyResources(this.mnuCallHistory, "mnuCallHistory");
this.mnuCallHistory.Click += new System.EventHandler(this.mnuCallHistory_Click);
//
// mnuPlugins
//
this.mnuPlugins.Name = "mnuPlugins";
resources.ApplyResources(this.mnuPlugins, "mnuPlugins");
this.mnuPlugins.Click += new System.EventHandler(this.btnPlugins_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// mnuShowCommonTasks
//
this.mnuShowCommonTasks.CheckOnClick = true;
this.mnuShowCommonTasks.Name = "mnuShowCommonTasks";
resources.ApplyResources(this.mnuShowCommonTasks, "mnuShowCommonTasks");
this.mnuShowCommonTasks.Click += new System.EventHandler(this.mnuShowCommonTasks_Click);
//
// mnuLanguage
//
this.mnuLanguage.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuEnglish,
this.mnuGerman});
this.mnuLanguage.Name = "mnuLanguage";
resources.ApplyResources(this.mnuLanguage, "mnuLanguage");
//
// mnuEnglish
//
this.mnuEnglish.Name = "mnuEnglish";
resources.ApplyResources(this.mnuEnglish, "mnuEnglish");
this.mnuEnglish.Tag = "en";
this.mnuEnglish.Click += new System.EventHandler(this.mnuLanguage_Click);
//
// mnuGerman
//
this.mnuGerman.Name = "mnuGerman";
resources.ApplyResources(this.mnuGerman, "mnuGerman");
this.mnuGerman.Tag = "de";
this.mnuGerman.Click += new System.EventHandler(this.mnuLanguage_Click);
//
// mnuHelp
//
this.mnuHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuUserManual,
this.toolStripSeparator6,
this.mnuPurchase,
this.mnuRegister,
this.mnuChangeEdition,
this.toolStripSeparator1,
this.mnuSupport,
this.toolStripMenuItem1,
this.mnuGetModules,
this.checkForUpdatesToolStripMenuItem,
this.mnuAbout});
this.mnuHelp.Name = "mnuHelp";
resources.ApplyResources(this.mnuHelp, "mnuHelp");
//
// mnuUserManual
//
this.mnuUserManual.Image = global::CallButler.Manager.Properties.Resources.help_16;
this.mnuUserManual.Name = "mnuUserManual";
resources.ApplyResources(this.mnuUserManual, "mnuUserManual");
this.mnuUserManual.Click += new System.EventHandler(this.mnuUserManual_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// mnuPurchase
//
this.mnuPurchase.Image = global::CallButler.Manager.Properties.Resources.shoppingcart_full_16;
this.mnuPurchase.Name = "mnuPurchase";
resources.ApplyResources(this.mnuPurchase, "mnuPurchase");
this.mnuPurchase.Click += new System.EventHandler(this.mnuPurchase_Click);
//
// mnuRegister
//
this.mnuRegister.Image = global::CallButler.Manager.Properties.Resources.keys_16;
this.mnuRegister.Name = "mnuRegister";
resources.ApplyResources(this.mnuRegister, "mnuRegister");
this.mnuRegister.Click += new System.EventHandler(this.mnuRegister_Click);
//
// mnuChangeEdition
//
this.mnuChangeEdition.Name = "mnuChangeEdition";
resources.ApplyResources(this.mnuChangeEdition, "mnuChangeEdition");
this.mnuChangeEdition.Click += new System.EventHandler(this.mnuChangeEdition_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// mnuSupport
//
this.mnuSupport.Name = "mnuSupport";
resources.ApplyResources(this.mnuSupport, "mnuSupport");
this.mnuSupport.Click += new System.EventHandler(this.mnuSupport_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// mnuGetModules
//
this.mnuGetModules.Name = "mnuGetModules";
resources.ApplyResources(this.mnuGetModules, "mnuGetModules");
this.mnuGetModules.Click += new System.EventHandler(this.btnAddonModules_Click);
//
// checkForUpdatesToolStripMenuItem
//
this.checkForUpdatesToolStripMenuItem.Image = global::CallButler.Manager.Properties.Resources.download_16;
this.checkForUpdatesToolStripMenuItem.Name = "checkForUpdatesToolStripMenuItem";
resources.ApplyResources(this.checkForUpdatesToolStripMenuItem, "checkForUpdatesToolStripMenuItem");
this.checkForUpdatesToolStripMenuItem.Click += new System.EventHandler(this.checkForUpdatesToolStripMenuItem_Click);
//
// mnuAbout
//
this.mnuAbout.Image = global::CallButler.Manager.Properties.Resources.about_16;
this.mnuAbout.Name = "mnuAbout";
resources.ApplyResources(this.mnuAbout, "mnuAbout");
this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
//
// pnlMainContent
//
this.pnlMainContent.BackColor = System.Drawing.Color.Transparent;
this.pnlMainContent.Controls.Add(this.pnlRightOuter);
this.pnlMainContent.Controls.Add(this.pnlLeftOuter);
this.pnlMainContent.Controls.Add(this.pnlHeaderButtonContainer);
this.pnlMainContent.Controls.Add(this.pnlExpired);
this.pnlMainContent.Controls.Add(this.pnlNewVersion);
resources.ApplyResources(this.pnlMainContent, "pnlMainContent");
this.pnlMainContent.Name = "pnlMainContent";
//
// pnlRightOuter
//
this.pnlRightOuter.Controls.Add(this.pnlContent);
resources.ApplyResources(this.pnlRightOuter, "pnlRightOuter");
this.pnlRightOuter.Name = "pnlRightOuter";
//
// pnlContent
//
this.pnlContent.BorderSize = 1F;
this.pnlContent.CornerRadius = 10;
this.pnlContent.DisplayShadow = false;
resources.ApplyResources(this.pnlContent, "pnlContent");
this.pnlContent.ForeColor = System.Drawing.Color.Silver;
this.pnlContent.Name = "pnlContent";
this.pnlContent.PanelColor = System.Drawing.Color.WhiteSmoke;
this.pnlContent.ShadowColor = System.Drawing.Color.Gray;
this.pnlContent.ShadowOffset = 5;
//
// pnlExpired
//
this.pnlExpired.Controls.Add(this.roundedCornerPanel1);
resources.ApplyResources(this.pnlExpired, "pnlExpired");
this.pnlExpired.Name = "pnlExpired";
//
// roundedCornerPanel1
//
this.roundedCornerPanel1.BackColor = System.Drawing.Color.White;
this.roundedCornerPanel1.BorderSize = 1F;
this.roundedCornerPanel1.Controls.Add(this.btnRegister);
this.roundedCornerPanel1.Controls.Add(this.label2);
this.roundedCornerPanel1.Controls.Add(this.pictureBox1);
this.roundedCornerPanel1.CornerRadius = 5;
this.roundedCornerPanel1.DisplayShadow = false;
resources.ApplyResources(this.roundedCornerPanel1, "roundedCornerPanel1");
this.roundedCornerPanel1.ForeColor = System.Drawing.Color.Silver;
this.roundedCornerPanel1.Name = "roundedCornerPanel1";
this.roundedCornerPanel1.PanelColor = System.Drawing.Color.LightGoldenrodYellow;
this.roundedCornerPanel1.ShadowColor = System.Drawing.Color.Gray;
this.roundedCornerPanel1.ShadowOffset = 5;
//
// btnRegister
//
this.btnRegister.AntiAliasText = false;
resources.ApplyResources(this.btnRegister, "btnRegister");
this.btnRegister.BackColor = System.Drawing.Color.Transparent;
this.btnRegister.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnRegister.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnRegister.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnRegister.Name = "btnRegister";
this.btnRegister.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnRegister.UnderlineOnHover = true;
this.btnRegister.Click += new System.EventHandler(this.mnuRegister_Click);
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.label2, "label2");
this.label2.ForeColor = System.Drawing.Color.Firebrick;
this.label2.Name = "label2";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::CallButler.Manager.Properties.Resources.information;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// pnlLeftOuter
//
this.pnlLeftOuter.Controls.Add(this.pnlCommonTasks);
resources.ApplyResources(this.pnlLeftOuter, "pnlLeftOuter");
this.pnlLeftOuter.Name = "pnlLeftOuter";
//
// pnlCommonTasks
//
this.pnlCommonTasks.BorderSize = 1F;
this.pnlCommonTasks.Controls.Add(this.btnCloseCommonTasks);
this.pnlCommonTasks.Controls.Add(this.grpCallHistory);
this.pnlCommonTasks.CornerRadius = 10;
this.pnlCommonTasks.DisplayShadow = false;
resources.ApplyResources(this.pnlCommonTasks, "pnlCommonTasks");
this.pnlCommonTasks.ForeColor = System.Drawing.Color.Silver;
this.pnlCommonTasks.Name = "pnlCommonTasks";
this.pnlCommonTasks.PanelColor = System.Drawing.Color.WhiteSmoke;
this.pnlCommonTasks.ShadowColor = System.Drawing.Color.Gray;
this.pnlCommonTasks.ShadowOffset = 5;
//
// btnCloseCommonTasks
//
resources.ApplyResources(this.btnCloseCommonTasks, "btnCloseCommonTasks");
this.btnCloseCommonTasks.BackColor = System.Drawing.Color.WhiteSmoke;
this.btnCloseCommonTasks.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnCloseCommonTasks.Image = global::CallButler.Manager.Properties.Resources.view_previous_16;
this.btnCloseCommonTasks.Name = "btnCloseCommonTasks";
this.btnCloseCommonTasks.TabStop = false;
this.btnCloseCommonTasks.Click += new System.EventHandler(this.btnCloseCommonTasks_Click);
//
// grpCallHistory
//
this.grpCallHistory.AntiAliasText = false;
this.grpCallHistory.BackColor = System.Drawing.Color.WhiteSmoke;
this.grpCallHistory.Controls.Add(this.btnManageGeneralSettings);
this.grpCallHistory.Controls.Add(this.btnAddonModules);
this.grpCallHistory.Controls.Add(this.btnAddCallPersonalization);
this.grpCallHistory.Controls.Add(this.btnAddNewDepartment);
this.grpCallHistory.Controls.Add(this.btnNewExtension);
this.grpCallHistory.Controls.Add(this.btnGetPhoneNumber);
this.grpCallHistory.CornerRadius = 10;
this.grpCallHistory.DividerAbove = false;
resources.ApplyResources(this.grpCallHistory, "grpCallHistory");
this.grpCallHistory.DrawLeftDivider = false;
this.grpCallHistory.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.grpCallHistory.HeaderColor = System.Drawing.Color.Silver;
this.grpCallHistory.Name = "grpCallHistory";
//
// btnManageGeneralSettings
//
this.btnManageGeneralSettings.AntiAliasText = false;
resources.ApplyResources(this.btnManageGeneralSettings, "btnManageGeneralSettings");
this.btnManageGeneralSettings.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnManageGeneralSettings.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnManageGeneralSettings.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnManageGeneralSettings.LinkImage = global::CallButler.Manager.Properties.Resources.nut_and_bolt_24;
this.btnManageGeneralSettings.Name = "btnManageGeneralSettings";
this.btnManageGeneralSettings.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnManageGeneralSettings.UnderlineOnHover = true;
this.btnManageGeneralSettings.Click += new System.EventHandler(this.mnuSettings_Click);
//
// btnAddonModules
//
this.btnAddonModules.AntiAliasText = false;
resources.ApplyResources(this.btnAddonModules, "btnAddonModules");
this.btnAddonModules.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnAddonModules.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnAddonModules.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddonModules.LinkImage = global::CallButler.Manager.Properties.Resources.gear_connection_24;
this.btnAddonModules.Name = "btnAddonModules";
this.btnAddonModules.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddonModules.UnderlineOnHover = true;
this.btnAddonModules.Click += new System.EventHandler(this.btnAddonModules_Click);
//
// btnAddCallPersonalization
//
this.btnAddCallPersonalization.AntiAliasText = false;
resources.ApplyResources(this.btnAddCallPersonalization, "btnAddCallPersonalization");
this.btnAddCallPersonalization.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnAddCallPersonalization.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnAddCallPersonalization.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddCallPersonalization.LinkImage = global::CallButler.Manager.Properties.Resources.toolbox_24;
this.btnAddCallPersonalization.Name = "btnAddCallPersonalization";
this.btnAddCallPersonalization.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddCallPersonalization.UnderlineOnHover = true;
this.btnAddCallPersonalization.Click += new System.EventHandler(this.btnAddPersonalExtension_Click);
//
// btnAddNewDepartment
//
this.btnAddNewDepartment.AntiAliasText = false;
resources.ApplyResources(this.btnAddNewDepartment, "btnAddNewDepartment");
this.btnAddNewDepartment.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnAddNewDepartment.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnAddNewDepartment.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddNewDepartment.LinkImage = global::CallButler.Manager.Properties.Resources.office_24;
this.btnAddNewDepartment.Name = "btnAddNewDepartment";
this.btnAddNewDepartment.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAddNewDepartment.UnderlineOnHover = true;
this.btnAddNewDepartment.Click += new System.EventHandler(this.btnAddNewDepartment_Click);
//
// btnNewExtension
//
this.btnNewExtension.AntiAliasText = false;
resources.ApplyResources(this.btnNewExtension, "btnNewExtension");
this.btnNewExtension.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnNewExtension.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnNewExtension.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnNewExtension.LinkImage = global::CallButler.Manager.Properties.Resources.user1_telephone_24;
this.btnNewExtension.Name = "btnNewExtension";
this.btnNewExtension.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnNewExtension.UnderlineOnHover = true;
this.btnNewExtension.Click += new System.EventHandler(this.btnNewExtension_Click);
//
// btnGetPhoneNumber
//
this.btnGetPhoneNumber.AntiAliasText = false;
resources.ApplyResources(this.btnGetPhoneNumber, "btnGetPhoneNumber");
this.btnGetPhoneNumber.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnGetPhoneNumber.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnGetPhoneNumber.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnGetPhoneNumber.LinkImage = global::CallButler.Manager.Properties.Resources.telephone_24;
this.btnGetPhoneNumber.Name = "btnGetPhoneNumber";
this.btnGetPhoneNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnGetPhoneNumber.UnderlineOnHover = true;
this.btnGetPhoneNumber.Click += new System.EventHandler(this.btnGetPhoneNumber_Click);
//
// pnlNewVersion
//
this.pnlNewVersion.Controls.Add(this.pnlDownloadNewVersion);
resources.ApplyResources(this.pnlNewVersion, "pnlNewVersion");
this.pnlNewVersion.Name = "pnlNewVersion";
//
// pnlDownloadNewVersion
//
this.pnlDownloadNewVersion.BackColor = System.Drawing.Color.White;
this.pnlDownloadNewVersion.BorderSize = 1F;
this.pnlDownloadNewVersion.Controls.Add(this.btnDownloadNewVersion);
this.pnlDownloadNewVersion.Controls.Add(this.label1);
this.pnlDownloadNewVersion.Controls.Add(this.pictureBox6);
this.pnlDownloadNewVersion.Controls.Add(this.btnHideUpdateNotification);
this.pnlDownloadNewVersion.CornerRadius = 5;
this.pnlDownloadNewVersion.DisplayShadow = false;
resources.ApplyResources(this.pnlDownloadNewVersion, "pnlDownloadNewVersion");
this.pnlDownloadNewVersion.ForeColor = System.Drawing.Color.Silver;
this.pnlDownloadNewVersion.Name = "pnlDownloadNewVersion";
this.pnlDownloadNewVersion.PanelColor = System.Drawing.Color.LightGoldenrodYellow;
this.pnlDownloadNewVersion.ShadowColor = System.Drawing.Color.Gray;
this.pnlDownloadNewVersion.ShadowOffset = 5;
//
// btnDownloadNewVersion
//
this.btnDownloadNewVersion.AntiAliasText = false;
resources.ApplyResources(this.btnDownloadNewVersion, "btnDownloadNewVersion");
this.btnDownloadNewVersion.BackColor = System.Drawing.Color.Transparent;
this.btnDownloadNewVersion.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDownloadNewVersion.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnDownloadNewVersion.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnDownloadNewVersion.Name = "btnDownloadNewVersion";
this.btnDownloadNewVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnDownloadNewVersion.UnderlineOnHover = true;
this.btnDownloadNewVersion.Click += new System.EventHandler(this.btnDownloadNewVersion_Click);
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.label1, "label1");
this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.label1.Name = "label1";
//
// pictureBox6
//
this.pictureBox6.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.pictureBox6, "pictureBox6");
this.pictureBox6.Image = global::CallButler.Manager.Properties.Resources.information;
this.pictureBox6.Name = "pictureBox6";
this.pictureBox6.TabStop = false;
//
// btnHideUpdateNotification
//
this.btnHideUpdateNotification.AntiAliasText = false;
resources.ApplyResources(this.btnHideUpdateNotification, "btnHideUpdateNotification");
this.btnHideUpdateNotification.BackColor = System.Drawing.Color.Transparent;
this.btnHideUpdateNotification.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnHideUpdateNotification.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnHideUpdateNotification.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnHideUpdateNotification.Name = "btnHideUpdateNotification";
this.btnHideUpdateNotification.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnHideUpdateNotification.UnderlineOnHover = true;
this.btnHideUpdateNotification.Click += new System.EventHandler(this.btnHideUpdateNotification_Click);
//
// pnlHeaderButtonContainer
//
this.pnlHeaderButtonContainer.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(206)))), ((int)(((byte)(206)))), ((int)(((byte)(206)))));
this.pnlHeaderButtonContainer.BorderWidth = 1F;
this.pnlHeaderButtonContainer.Controls.Add(this.divExtensions);
this.pnlHeaderButtonContainer.Controls.Add(this.btnExtensions);
this.pnlHeaderButtonContainer.Controls.Add(this.pictureBox2);
this.pnlHeaderButtonContainer.Controls.Add(this.btnReceptionist);
this.pnlHeaderButtonContainer.Controls.Add(this.divCallFlow);
this.pnlHeaderButtonContainer.Controls.Add(this.btnScriptSchedule);
this.pnlHeaderButtonContainer.Controls.Add(this.btnCallFlow);
this.pnlHeaderButtonContainer.Controls.Add(this.divCallPersonalization);
this.pnlHeaderButtonContainer.Controls.Add(this.btnCallPersonalization);
this.pnlHeaderButtonContainer.Controls.Add(this.divTestDrive);
this.pnlHeaderButtonContainer.Controls.Add(this.btnTestDrive);
this.pnlHeaderButtonContainer.Controls.Add(this.divPBX);
this.pnlHeaderButtonContainer.Controls.Add(this.btnPBX);
this.pnlHeaderButtonContainer.Controls.Add(this.divProviders);
this.pnlHeaderButtonContainer.Controls.Add(this.btnProviders);
this.pnlHeaderButtonContainer.Controls.Add(this.divPlugins);
this.pnlHeaderButtonContainer.Controls.Add(this.btnPlugins);
resources.ApplyResources(this.pnlHeaderButtonContainer, "pnlHeaderButtonContainer");
this.pnlHeaderButtonContainer.DrawBorder = true;
this.pnlHeaderButtonContainer.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(229)))), ((int)(((byte)(229)))));
this.pnlHeaderButtonContainer.GradientAngle = 90F;
this.pnlHeaderButtonContainer.Name = "pnlHeaderButtonContainer";
//
// divExtensions
//
this.divExtensions.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divExtensions, "divExtensions");
this.divExtensions.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divExtensions.Name = "divExtensions";
this.divExtensions.TabStop = false;
//
// btnExtensions
//
this.btnExtensions.AntiAliasText = false;
resources.ApplyResources(this.btnExtensions, "btnExtensions");
this.btnExtensions.BackColor = System.Drawing.Color.Transparent;
this.btnExtensions.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnExtensions.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnExtensions.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnExtensions.LinkImage = global::CallButler.Manager.Properties.Resources.user1_telephone_24;
this.btnExtensions.Name = "btnExtensions";
this.btnExtensions.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnExtensions.UnderlineOnHover = true;
this.btnExtensions.Click += new System.EventHandler(this.btnExtensions_Click);
//
// pictureBox2
//
this.pictureBox2.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.pictureBox2, "pictureBox2");
this.pictureBox2.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.TabStop = false;
//
// btnReceptionist
//
this.btnReceptionist.AntiAliasText = false;
resources.ApplyResources(this.btnReceptionist, "btnReceptionist");
this.btnReceptionist.BackColor = System.Drawing.Color.Transparent;
this.btnReceptionist.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnReceptionist.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnReceptionist.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnReceptionist.LinkImage = ((System.Drawing.Image)(resources.GetObject("btnReceptionist.LinkImage")));
this.btnReceptionist.Name = "btnReceptionist";
this.btnReceptionist.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnReceptionist.UnderlineOnHover = true;
this.btnReceptionist.Click += new System.EventHandler(this.btnReceptionist_Click);
//
// divCallFlow
//
this.divCallFlow.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divCallFlow, "divCallFlow");
this.divCallFlow.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divCallFlow.Name = "divCallFlow";
this.divCallFlow.TabStop = false;
//
// btnScriptSchedule
//
this.btnScriptSchedule.AntiAliasText = false;
resources.ApplyResources(this.btnScriptSchedule, "btnScriptSchedule");
this.btnScriptSchedule.BackColor = System.Drawing.Color.Transparent;
this.btnScriptSchedule.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnScriptSchedule.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnScriptSchedule.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnScriptSchedule.LinkImage = global::CallButler.Manager.Properties.Resources.date_time_24;
this.btnScriptSchedule.Name = "btnScriptSchedule";
this.btnScriptSchedule.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnScriptSchedule.UnderlineOnHover = true;
this.btnScriptSchedule.Click += new System.EventHandler(this.btnScriptSchedule_Click);
//
// btnCallFlow
//
this.btnCallFlow.AntiAliasText = false;
resources.ApplyResources(this.btnCallFlow, "btnCallFlow");
this.btnCallFlow.BackColor = System.Drawing.Color.Transparent;
this.btnCallFlow.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnCallFlow.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnCallFlow.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCallFlow.LinkImage = global::CallButler.Manager.Properties.Resources.branch_24;
this.btnCallFlow.Name = "btnCallFlow";
this.btnCallFlow.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCallFlow.UnderlineOnHover = true;
this.btnCallFlow.Click += new System.EventHandler(this.btnCallFlow_Click);
//
// divCallPersonalization
//
this.divCallPersonalization.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divCallPersonalization, "divCallPersonalization");
this.divCallPersonalization.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divCallPersonalization.Name = "divCallPersonalization";
this.divCallPersonalization.TabStop = false;
//
// btnCallPersonalization
//
this.btnCallPersonalization.AntiAliasText = false;
resources.ApplyResources(this.btnCallPersonalization, "btnCallPersonalization");
this.btnCallPersonalization.BackColor = System.Drawing.Color.Transparent;
this.btnCallPersonalization.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnCallPersonalization.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnCallPersonalization.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCallPersonalization.LinkImage = global::CallButler.Manager.Properties.Resources.toolbox_24;
this.btnCallPersonalization.Name = "btnCallPersonalization";
this.btnCallPersonalization.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCallPersonalization.UnderlineOnHover = true;
this.btnCallPersonalization.Click += new System.EventHandler(this.btnPersonalGreetings_Click);
//
// divTestDrive
//
this.divTestDrive.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divTestDrive, "divTestDrive");
this.divTestDrive.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divTestDrive.Name = "divTestDrive";
this.divTestDrive.TabStop = false;
//
// btnTestDrive
//
this.btnTestDrive.AntiAliasText = false;
resources.ApplyResources(this.btnTestDrive, "btnTestDrive");
this.btnTestDrive.BackColor = System.Drawing.Color.Transparent;
this.btnTestDrive.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnTestDrive.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnTestDrive.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnTestDrive.LinkImage = global::CallButler.Manager.Properties.Resources.gauge_24;
this.btnTestDrive.Name = "btnTestDrive";
this.btnTestDrive.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnTestDrive.UnderlineOnHover = true;
this.btnTestDrive.Click += new System.EventHandler(this.btnTestDrive_Click);
//
// divPBX
//
this.divPBX.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divPBX, "divPBX");
this.divPBX.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divPBX.Name = "divPBX";
this.divPBX.TabStop = false;
//
// btnPBX
//
this.btnPBX.AntiAliasText = false;
resources.ApplyResources(this.btnPBX, "btnPBX");
this.btnPBX.BackColor = System.Drawing.Color.Transparent;
this.btnPBX.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnPBX.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnPBX.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnPBX.LinkImage = global::CallButler.Manager.Properties.Resources.node_24;
this.btnPBX.Name = "btnPBX";
this.btnPBX.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnPBX.UnderlineOnHover = true;
this.btnPBX.Click += new System.EventHandler(this.btnPBX_Click);
//
// divProviders
//
this.divProviders.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divProviders, "divProviders");
this.divProviders.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divProviders.Name = "divProviders";
this.divProviders.TabStop = false;
//
// btnProviders
//
this.btnProviders.AntiAliasText = false;
resources.ApplyResources(this.btnProviders, "btnProviders");
this.btnProviders.BackColor = System.Drawing.Color.Transparent;
this.btnProviders.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnProviders.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnProviders.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnProviders.LinkImage = global::CallButler.Manager.Properties.Resources.provider_connection_24;
this.btnProviders.Name = "btnProviders";
this.btnProviders.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnProviders.UnderlineOnHover = true;
this.btnProviders.Click += new System.EventHandler(this.btnProviders_Click);
//
// divPlugins
//
this.divPlugins.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.divPlugins, "divPlugins");
this.divPlugins.Image = global::CallButler.Manager.Properties.Resources.divider_line;
this.divPlugins.Name = "divPlugins";
this.divPlugins.TabStop = false;
//
// btnPlugins
//
this.btnPlugins.AntiAliasText = false;
resources.ApplyResources(this.btnPlugins, "btnPlugins");
this.btnPlugins.BackColor = System.Drawing.Color.Transparent;
this.btnPlugins.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnPlugins.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnPlugins.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnPlugins.LinkImage = global::CallButler.Manager.Properties.Resources.gear_connection_24;
this.btnPlugins.Name = "btnPlugins";
this.btnPlugins.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnPlugins.UnderlineOnHover = true;
this.btnPlugins.Click += new System.EventHandler(this.btnPlugins_Click);
//
// pnlHeader
//
resources.ApplyResources(this.pnlHeader, "pnlHeader");
this.pnlHeader.Controls.Add(this.btnBackToSummary);
this.pnlHeader.Controls.Add(this.picHeaderIcon);
this.pnlHeader.Controls.Add(this.picCallButlerLogo);
this.pnlHeader.Controls.Add(this.lblHeaderCaption);
this.pnlHeader.Controls.Add(this.lblViewTitle);
this.pnlHeader.Name = "pnlHeader";
//
// btnBackToSummary
//
resources.ApplyResources(this.btnBackToSummary, "btnBackToSummary");
this.btnBackToSummary.AntiAliasText = false;
this.btnBackToSummary.BackColor = System.Drawing.Color.Transparent;
this.btnBackToSummary.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnBackToSummary.ForeColor = System.Drawing.Color.White;
this.btnBackToSummary.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnBackToSummary.LinkImage = global::CallButler.Manager.Properties.Resources.back_up;
this.btnBackToSummary.MouseDownImage = global::CallButler.Manager.Properties.Resources.back_down;
this.btnBackToSummary.Name = "btnBackToSummary";
this.btnBackToSummary.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnBackToSummary.UnderlineOnHover = true;
this.btnBackToSummary.Click += new System.EventHandler(this.btnBackToSummary_Click);
//
// picHeaderIcon
//
resources.ApplyResources(this.picHeaderIcon, "picHeaderIcon");
this.picHeaderIcon.BackColor = System.Drawing.Color.Transparent;
this.picHeaderIcon.Name = "picHeaderIcon";
this.picHeaderIcon.TabStop = false;
//
// picCallButlerLogo
//
this.picCallButlerLogo.BackColor = System.Drawing.Color.Transparent;
this.picCallButlerLogo.Cursor = System.Windows.Forms.Cursors.Hand;
this.picCallButlerLogo.Image = global::CallButler.Manager.Properties.Resources.logo;
resources.ApplyResources(this.picCallButlerLogo, "picCallButlerLogo");
this.picCallButlerLogo.Name = "picCallButlerLogo";
this.picCallButlerLogo.TabStop = false;
this.picCallButlerLogo.Click += new System.EventHandler(this.picCallButlerLogo_Click);
//
// lblHeaderCaption
//
resources.ApplyResources(this.lblHeaderCaption, "lblHeaderCaption");
this.lblHeaderCaption.BackColor = System.Drawing.Color.Transparent;
this.lblHeaderCaption.ForeColor = System.Drawing.Color.White;
this.lblHeaderCaption.Name = "lblHeaderCaption";
//
// lblViewTitle
//
resources.ApplyResources(this.lblViewTitle, "lblViewTitle");
this.lblViewTitle.BackColor = System.Drawing.Color.Transparent;
this.lblViewTitle.ForeColor = System.Drawing.Color.White;
this.lblViewTitle.Name = "lblViewTitle";
//
// openSettingsFileDialog
//
resources.ApplyResources(this.openSettingsFileDialog, "openSettingsFileDialog");
//
// MainForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.pnlMainContent);
this.Controls.Add(this.pnlHeader);
this.Controls.Add(this.mnuMain);
this.Controls.Add(this.statusStrip);
this.DoubleBuffered = true;
this.Name = "MainForm";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.mnuMain.ResumeLayout(false);
this.mnuMain.PerformLayout();
this.pnlMainContent.ResumeLayout(false);
this.pnlRightOuter.ResumeLayout(false);
this.pnlExpired.ResumeLayout(false);
this.roundedCornerPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.pnlLeftOuter.ResumeLayout(false);
this.pnlCommonTasks.ResumeLayout(false);
this.pnlCommonTasks.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.btnCloseCommonTasks)).EndInit();
this.grpCallHistory.ResumeLayout(false);
this.pnlNewVersion.ResumeLayout(false);
this.pnlDownloadNewVersion.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).EndInit();
this.pnlHeaderButtonContainer.ResumeLayout(false);
this.pnlHeaderButtonContainer.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.divExtensions)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divCallFlow)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divCallPersonalization)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divTestDrive)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divPBX)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divProviders)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.divPlugins)).EndInit();
this.pnlHeader.ResumeLayout(false);
this.pnlHeader.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picHeaderIcon)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picCallButlerLogo)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.MenuStrip mnuMain;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.Panel pnlMainContent;
private System.Windows.Forms.Panel pnlRightOuter;
private System.Windows.Forms.Panel pnlLeftOuter;
private global::Controls.RoundedCornerPanel pnlCommonTasks;
private global::Controls.GradientPanel pnlHeaderButtonContainer;
private System.Windows.Forms.PictureBox picCallButlerLogo;
private global::Controls.SmoothLabel lblViewTitle;
private System.Windows.Forms.Panel pnlHeader;
private global::Controls.SmoothLabel lblHeaderCaption;
private System.Windows.Forms.PictureBox picHeaderIcon;
private System.Windows.Forms.ToolStripStatusLabel lblLoadStatus;
private global::Controls.LinkButton btnProviders;
private System.Windows.Forms.PictureBox divProviders;
private System.Windows.Forms.PictureBox divTestDrive;
private global::Controls.LinkButton btnTestDrive;
private System.Windows.Forms.PictureBox divCallFlow;
private global::Controls.LinkButton btnCallFlow;
private System.Windows.Forms.PictureBox divExtensions;
private global::Controls.LinkButton btnExtensions;
private global::Controls.LinkButton btnBackToSummary;
private System.Windows.Forms.ToolStripMenuItem mnuConnect;
private System.Windows.Forms.ToolStripMenuItem mnuConnectOtherComputer;
private System.Windows.Forms.ToolStripMenuItem mnuConnectThisComputer;
private System.Windows.Forms.ToolStripMenuItem mnuClose;
private System.Windows.Forms.ToolStripStatusLabel lblConnectionStatus;
private System.Windows.Forms.ToolStripMenuItem mnuEdit;
private System.Windows.Forms.ToolStripMenuItem mnuSettings;
private System.Windows.Forms.PictureBox divCallPersonalization;
private global::Controls.LinkButton btnCallPersonalization;
private global::Controls.GroupBoxEx grpCallHistory;
private global::Controls.LinkButton btnNewExtension;
private System.Windows.Forms.PictureBox btnCloseCommonTasks;
private System.Windows.Forms.ToolStripMenuItem mnuView;
private System.Windows.Forms.ToolStripMenuItem mnuShowCommonTasks;
private global::Controls.LinkButton btnAddCallPersonalization;
private global::Controls.LinkButton btnAddNewDepartment;
private global::Controls.LinkButton btnManageGeneralSettings;
private System.Windows.Forms.ToolStripMenuItem mnuHelp;
private System.Windows.Forms.ToolStripMenuItem mnuRegister;
private System.Windows.Forms.ToolStripMenuItem mnuAbout;
private System.Windows.Forms.ToolStripSeparator mnuExpertModeDiv;
private System.Windows.Forms.ToolStripMenuItem mnuExpertMode;
private global::Controls.LinkButton btnScriptSchedule;
private System.Windows.Forms.ToolStripMenuItem mnuExtensions;
private System.Windows.Forms.ToolStripMenuItem mnuScriptSchedule;
private System.Windows.Forms.ToolStripMenuItem mnuCallFlow;
private System.Windows.Forms.ToolStripMenuItem mnuCallPersonalization;
private System.Windows.Forms.ToolStripMenuItem mnuTestDrive;
private System.Windows.Forms.ToolStripMenuItem mnuVoIPProviders;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem mnuCallHistory;
private System.Windows.Forms.ToolStripMenuItem mnuQuickStart;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private global::Controls.RoundedCornerPanel pnlContent;
private global::Controls.RoundedCornerPanel pnlDownloadNewVersion;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ToolStripMenuItem checkForUpdatesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private global::Controls.LinkButton btnDownloadNewVersion;
private global::Controls.LinkButton btnHideUpdateNotification;
private System.Windows.Forms.Panel pnlNewVersion;
private System.Windows.Forms.PictureBox pictureBox6;
private System.Windows.Forms.ToolStripMenuItem mnuSupport;
private System.Windows.Forms.PictureBox divPlugins;
private global::Controls.LinkButton btnPlugins;
private System.Windows.Forms.ToolStripMenuItem mnuPlugins;
private System.Windows.Forms.ToolStripMenuItem mnuPurchase;
private System.Windows.Forms.ToolStripMenuItem mnuLogin;
private System.Windows.Forms.ToolStripStatusLabel lblPoweredBy;
private global::Controls.LinkButton btnGetPhoneNumber;
private System.Windows.Forms.ToolStripMenuItem mnuTour;
private System.Windows.Forms.Panel pnlExpired;
private global::Controls.RoundedCornerPanel roundedCornerPanel1;
private global::Controls.LinkButton btnRegister;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ToolStripMenuItem mnuChangeEdition;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem mnuImport;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.OpenFileDialog openSettingsFileDialog;
private global::Controls.LinkButton btnPBX;
private System.Windows.Forms.PictureBox divPBX;
private global::Controls.LinkButton btnReceptionist;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.ToolStripMenuItem mnuUserManual;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem mnuReceptionist;
private System.Windows.Forms.ToolStripMenuItem mnuPBX;
private System.Windows.Forms.ToolStripMenuItem mnuLanguage;
private System.Windows.Forms.ToolStripMenuItem mnuEnglish;
private System.Windows.Forms.ToolStripMenuItem mnuGerman;
private global::Controls.LinkButton btnAddonModules;
private System.Windows.Forms.ToolStripMenuItem mnuGetModules;
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.EnvironmentsList {
class PipPackageCache : IDisposable {
private static readonly Dictionary<string, PipPackageCache> _knownCaches =
new Dictionary<string, PipPackageCache>();
private static readonly object _knownCachesLock = new object();
private readonly Uri _index;
private readonly string _indexName;
private readonly string _cachePath;
protected readonly SemaphoreSlim _cacheLock = new SemaphoreSlim(1);
protected readonly Dictionary<string, PipPackageView> _cache;
protected DateTime _cacheAge;
protected int _userCount; // protected by _knownCachesLock
private long _writeVersion;
protected bool _isDisposed;
private readonly static Regex IndexNameSanitizerRegex = new Regex(@"\W");
private static readonly Regex SimpleListRegex = new Regex(@"a href=['""](?<package>[^'""]+)");
// These constants are substituted where necessary, but are not stored
// in instance variables so we can differentiate between set and unset.
private static readonly Uri DefaultIndex = new Uri("https://pypi.python.org/pypi/");
private const string DefaultIndexName = "PyPI";
protected PipPackageCache(
Uri index,
string indexName,
string cachePath
) {
_index = index;
_indexName = indexName;
_cachePath = cachePath;
_cache = new Dictionary<string, PipPackageView>();
}
public static PipPackageCache GetCache(Uri index = null, string indexName = null) {
PipPackageCache cache;
var key = (index ?? DefaultIndex).AbsoluteUri;
lock (_knownCachesLock) {
if (!_knownCaches.TryGetValue(key, out cache)) {
_knownCaches[key] = cache = new PipPackageCache(
index,
indexName,
GetCachePath(index ?? DefaultIndex, indexName ?? DefaultIndexName)
);
}
cache._userCount += 1;
}
return cache;
}
~PipPackageCache() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (_isDisposed) {
return;
}
_isDisposed = true;
if (disposing) {
lock (_knownCachesLock) {
if (--_userCount <= 0) {
Debug.Assert(_userCount == 0);
_cacheLock.Dispose();
_knownCaches.Remove((_index ?? DefaultIndex).AbsoluteUri);
}
}
}
}
public Uri Index {
get { return _index ?? DefaultIndex; }
}
public string IndexName {
get { return _indexName ?? DefaultIndexName; }
}
public bool HasExplicitIndex {
get { return _index != null; }
}
public async Task<IList<PipPackageView>> GetAllPackagesAsync(CancellationToken cancel) {
await _cacheLock.WaitAsync(cancel).ConfigureAwait(false);
try {
if (!_cache.Any()) {
try {
await ReadCacheFromDiskAsync(cancel).ConfigureAwait(false);
} catch (IOException) {
_cacheAge = DateTime.MinValue;
}
}
if (_cacheAge.AddHours(6) < DateTime.Now) {
await RefreshCacheAsync(cancel).ConfigureAwait(false);
}
return _cache.Values.ToList();
} finally {
_cacheLock.Release();
}
}
/// <summary>
/// Use some rough heuristicts to try and only show the first section of
/// a package description.
///
/// Most descriptions start with a summary line or title, followed by a
/// blank line or "====..." style separator.
/// </summary>
private static bool IsSeparatorLine(string s) {
if (string.IsNullOrWhiteSpace(s)) {
return true;
}
if (s.Length > 2) {
var first = s.FirstOrDefault(c => !char.IsWhiteSpace(c));
if (first != default(char)) {
if (s.All(c => char.IsWhiteSpace(c) || c == first)) {
return true;
}
}
}
return false;
}
public async Task UpdatePackageInfoAsync(PipPackageView package, CancellationToken cancel) {
string description = null;
List<string> versions = null;
using (var client = new WebClient()) {
Stream data;
try {
data = await client.OpenReadTaskAsync(new Uri(_index ?? DefaultIndex, package.Name + "/json"));
} catch (WebException) {
// No net access
return;
}
try {
using (var reader = JsonReaderWriterFactory.CreateJsonReader(data, new XmlDictionaryReaderQuotas())) {
var doc = XDocument.Load(reader);
// TODO: Get package URL
//url = (string)doc.Document
// .Elements("root")
// .Elements("info")
// .Elements("package_url")
// .FirstOrDefault();
description = (string)doc.Document
.Elements("root")
.Elements("info")
.Elements("description")
.FirstOrDefault();
versions = doc.Document
.Elements("root")
.Elements("releases")
.Elements()
.Attributes("item")
.Select(a => a.Value)
.ToList();
}
} catch (InvalidOperationException) {
}
}
cancel.ThrowIfCancellationRequested();
bool changed = false;
await _cacheLock.WaitAsync();
try {
PipPackageView inCache;
if (!_cache.TryGetValue(package.Name, out inCache)) {
inCache = _cache[package.Name] = new PipPackageView(this, package.Name, null, null);
}
if (!string.IsNullOrEmpty(description)) {
var lines = description.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var firstLine = string.Join(
" ",
lines.TakeWhile(s => !IsSeparatorLine(s)).Select(s => s.Trim())
);
if (firstLine.Length > 500) {
firstLine = firstLine.Substring(0, 497) + "...";
}
if (firstLine == "UNKNOWN") {
firstLine = string.Empty;
}
inCache.Description = firstLine;
package.Description = firstLine;
changed = true;
}
if (versions != null) {
var updateVersion = Pep440Version.TryParseAll(versions)
.Where(v => v.IsFinalRelease)
.OrderByDescending(v => v)
.FirstOrDefault();
inCache.UpgradeVersion = updateVersion;
package.UpgradeVersion = updateVersion;
changed = true;
}
} finally {
_cacheLock.Release();
}
if (changed) {
TriggerWriteCacheToDisk();
}
}
#region Cache File Management
private static async Task<IDisposable> LockFile(string filename, CancellationToken cancel) {
FileStream stream = null;
while (stream == null) {
cancel.ThrowIfCancellationRequested();
if (!File.Exists(filename)) {
try {
stream = new FileStream(
filename,
FileMode.CreateNew,
FileAccess.ReadWrite,
FileShare.None,
8,
FileOptions.DeleteOnClose
);
} catch (DirectoryNotFoundException) {
var dir = CommonUtils.GetParent(filename);
if (!Directory.Exists(dir)) {
Directory.CreateDirectory(dir);
} else {
throw;
}
} catch (IOException) {
}
}
await Task.Delay(100);
}
return stream;
}
private async Task RefreshCacheAsync(CancellationToken cancel) {
Debug.Assert(_cacheLock.CurrentCount == 0, "Cache must be locked before calling RefreshCacheAsync");
string htmlList;
using (var client = new WebClient()) {
// ../simple is a list of <a href="package">package</a>
try {
htmlList = await client.DownloadStringTaskAsync(
new Uri(_index ?? DefaultIndex, "../simple")
).ConfigureAwait(false);
} catch (WebException) {
// No net access, so can't refresh
return;
}
}
bool changed = false;
var toRemove = new HashSet<string>(_cache.Keys);
// We only want to add new packages so we don't blow away
// existing package specs in the cache.
foreach (Match match in SimpleListRegex.Matches(htmlList)) {
var package = match.Groups["package"].Value;
if (string.IsNullOrEmpty(package)) {
continue;
}
if (!toRemove.Remove(package)) {
try {
_cache[package] = new PipPackageView(this, package);
changed = true;
} catch (FormatException) {
}
}
}
foreach (var package in toRemove) {
_cache.Remove(package);
changed = true;
}
if (changed) {
TriggerWriteCacheToDisk();
}
_cacheAge = DateTime.Now;
}
private async void TriggerWriteCacheToDisk() {
var version = Interlocked.Increment(ref _writeVersion);
await Task.Delay(1000).ConfigureAwait(false);
if (Volatile.Read(ref _writeVersion) != version) {
return;
}
try {
await _cacheLock.WaitAsync();
try {
await WriteCacheToDiskAsync(CancellationToken.None);
} finally {
_cacheLock.Release();
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Debug.Fail("Unhandled exception: " + ex.ToString());
// Nowhere else to report the exception, so just swallow it to
// avoid bringing down the whole process.
}
}
protected async Task WriteCacheToDiskAsync(CancellationToken cancel) {
Debug.Assert(_cacheLock.CurrentCount == 0, "Cache must be locked before calling WriteCacheToDiskAsync");
try {
using (await LockFile(_cachePath + ".lock", cancel))
using (var file = new StreamWriter(_cachePath, false, Encoding.UTF8)) {
foreach (var keyValue in _cache) {
cancel.ThrowIfCancellationRequested();
await file.WriteLineAsync(keyValue.Value.GetPackageSpec(false, true));
}
}
} catch (IOException ex) {
Debug.Fail("Failed to write cache file: " + ex.ToString());
// Otherwise, just keep the cache in memory.
}
}
protected async Task ReadCacheFromDiskAsync(CancellationToken cancel) {
Debug.Assert(_cacheLock.CurrentCount == 0, "Cache must be locked before calling ReadCacheFromDiskAsync");
var newCacheAge = DateTime.Now;
var newCache = new Dictionary<string, PipPackageView>();
using (await LockFile(_cachePath + ".lock", cancel).ConfigureAwait(false))
using (var file = new StreamReader(_cachePath, Encoding.UTF8)) {
try {
newCacheAge = File.GetLastWriteTime(_cachePath);
} catch (IOException) {
}
string spec;
while ((spec = await file.ReadLineAsync()) != null) {
cancel.ThrowIfCancellationRequested();
try {
var pv = new PipPackageView(this, spec, versionIsInstalled: false);
newCache[pv.Name] = pv;
} catch (FormatException) {
}
}
}
_cache.Clear();
foreach (var kv in newCache) {
_cache[kv.Key] = kv.Value;
}
_cacheAge = newCacheAge;
}
#endregion
private static string BasePackageCachePath {
get {
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"PipCache",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.VSVersion
);
}
}
private static string GetCachePath(Uri index, string indexName) {
return Path.Combine(
BasePackageCachePath,
IndexNameSanitizerRegex.Replace(indexName, "_") + "_simple.cache"
);
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static readonly Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
private static readonly unsafe Ssl.SslCtxSetAlpnCallback s_alpnServerCallback = AlpnServerSelectCallback;
private static readonly IdnMapping s_idnMapping = new IdnMapping();
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
Debug.Assert(
bindingType != ChannelBindingKind.Endpoint,
"Endpoint binding should be handled by EndpointChannelBindingToken");
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions)
{
SafeSslHandle context = null;
// Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest
// mutually supported version and can thus handle any of the set protocols, and we then use
// SetProtocolOptions to ensure we only allow the ones requested.
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
if (!Interop.Ssl.Tls13Supported)
{
if (protocols != SslProtocols.None &&
CipherSuitesPolicyPal.WantsTls13(protocols))
{
protocols = protocols & (~SslProtocols.Tls13);
}
}
else if (CipherSuitesPolicyPal.WantsTls13(protocols) &&
CipherSuitesPolicyPal.ShouldOptOutOfTls13(sslAuthenticationOptions.CipherSuitesPolicy, policy))
{
if (protocols == SslProtocols.None)
{
// we are using default settings but cipher suites policy says that TLS 1.3
// is not compatible with our settings (i.e. we requested no encryption or disabled
// all TLS 1.3 cipher suites)
protocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
}
else
{
// user explicitly asks for TLS 1.3 but their policy is not compatible with TLS 1.3
throw new SslException(
SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
}
if (CipherSuitesPolicyPal.ShouldOptOutOfLowerThanTls13(sslAuthenticationOptions.CipherSuitesPolicy, policy))
{
if (!CipherSuitesPolicyPal.WantsTls13(protocols))
{
// We cannot provide neither TLS 1.3 or non TLS 1.3, user disabled all cipher suites
throw new SslException(
SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
protocols = SslProtocols.Tls13;
}
// Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just
// create the handle, it's rooted by the using, no one else has a reference to it, etc.
Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols);
// Sets policy and security level
if (!Ssl.SetEncryptionPolicy(innerContext, policy))
{
throw new SslException(
SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
// The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
// shutdown (we aren't negotiating for session close to enable later session
// restoration).
//
// If you find yourself wanting to remove this line to enable bidirectional
// close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
Ssl.SslCtxSetQuietShutdown(innerContext);
byte[] cipherList =
CipherSuitesPolicyPal.GetOpenSslCipherList(sslAuthenticationOptions.CipherSuitesPolicy, protocols, policy);
Debug.Assert(cipherList == null || (cipherList.Length >= 1 && cipherList[cipherList.Length - 1] == 0));
byte[] cipherSuites =
CipherSuitesPolicyPal.GetOpenSslCipherSuites(sslAuthenticationOptions.CipherSuitesPolicy, protocols, policy);
Debug.Assert(cipherSuites == null || (cipherSuites.Length >= 1 && cipherSuites[cipherSuites.Length - 1] == 0));
unsafe
{
fixed (byte* cipherListStr = cipherList)
fixed (byte* cipherSuitesStr = cipherSuites)
{
if (!Ssl.SetCiphers(innerContext, cipherListStr, cipherSuitesStr))
{
Crypto.ErrClearError();
throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
}
}
bool hasCertificateAndKey =
certHandle != null && !certHandle.IsInvalid
&& certKeyHandle != null && !certKeyHandle.IsInvalid;
if (hasCertificateAndKey)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired)
{
Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate);
}
GCHandle alpnHandle = default;
try
{
if (sslAuthenticationOptions.ApplicationProtocols != null)
{
if (sslAuthenticationOptions.IsServer)
{
alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols);
Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle));
}
else
{
if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0)
{
throw CreateSslException(SR.net_alpn_config_failed);
}
}
}
context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
if (!sslAuthenticationOptions.IsServer)
{
// The IdnMapping converts unicode input into the IDNA punycode sequence.
string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost);
// Similar to windows behavior, set SNI on openssl by default for client context, ignore errors.
if (!Ssl.SslSetTlsExtHostName(context, punyCode))
{
Crypto.ErrClearError();
}
}
if (hasCertificateAndKey)
{
bool hasCertReference = false;
try
{
certHandle.DangerousAddRef(ref hasCertReference);
using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle()))
{
X509Chain chain = null;
try
{
chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false);
if (chain != null && !Ssl.AddExtraChainCertificates(context, chain))
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
}
finally
{
if (chain != null)
{
int elementsCount = chain.ChainElements.Count;
for (int i = 0; i < elementsCount; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
chain.Dispose();
}
}
}
}
finally
{
if (hasCertReference)
certHandle.DangerousRelease();
}
}
context.AlpnHandle = alpnHandle;
}
catch
{
if (alpnHandle.IsAllocated)
{
alpnHandle.Free();
}
throw;
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
if (BioWrite(context.InputBio, recvBuf, recvOffset, recvCount) <= 0)
{
// Make sure we clear out the error that is stored in the queue
throw Crypto.CreateOpenSslCryptographicException();
}
}
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
Exception innerError;
Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
// Make sure we clear out the error that is stored in the queue
Crypto.ErrClearError();
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory<byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode)
{
#if DEBUG
ulong assertNoError = Crypto.ErrPeekError();
Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
Exception innerError = null;
lock (context)
{
unsafe
{
using (MemoryHandle handle = input.Pin())
{
retVal = Ssl.SslWrite(context, (byte*)handle.Pointer, input.Length);
}
}
if (retVal != input.Length)
{
errorCode = GetSslError(context, retVal, out innerError);
}
}
if (retVal != input.Length)
{
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
if (output == null || output.Length < capacityNeeded)
{
output = new byte[capacityNeeded];
}
retVal = BioRead(context.OutputBio, output, capacityNeeded);
if (retVal <= 0)
{
// Make sure we clear out the error that is stored in the queue
Crypto.ErrClearError();
}
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
#if DEBUG
ulong assertNoError = Crypto.ErrPeekError();
Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, offset, count);
Exception innerError = null;
lock (context)
{
if (retVal == count)
{
unsafe
{
fixed (byte* fixedBuffer = outBuffer)
{
retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length);
}
}
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
errorCode = GetSslError(context, retVal, out innerError);
}
}
if (retVal != count)
{
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
// user callback. It's also up to those handlers to decide if a null certificate
// is appropriate. So just return success to tell OpenSSL that the cert is acceptable,
// we'll process it after the handshake finishes.
const int OpenSslSuccess = 1;
return OpenSslSuccess;
}
private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out byte* outp, out byte outlen, byte* inp, uint inlen, IntPtr arg)
{
outp = null;
outlen = 0;
GCHandle protocolHandle = GCHandle.FromIntPtr(arg);
if (!(protocolHandle.Target is List<SslApplicationProtocol> protocolList))
{
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
try
{
for (int i = 0; i < protocolList.Count; i++)
{
var clientList = new Span<byte>(inp, (int)inlen);
while (clientList.Length > 0)
{
byte length = clientList[0];
Span<byte> clientProto = clientList.Slice(1, length);
if (clientProto.SequenceEqual(protocolList[i].Protocol.Span))
{
fixed (byte* p = &MemoryMarshal.GetReference(clientProto)) outp = p;
outlen = length;
return Ssl.SSL_TLSEXT_ERR_OK;
}
clientList = clientList.Slice(1 + length);
}
}
}
catch
{
// No common application protocol was negotiated, set the target on the alpnHandle to null.
// It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
protocolHandle.Target = null;
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
// No common application protocol was negotiated, set the target on the alpnHandle to null.
// It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
protocolHandle.Target = null;
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError)
{
ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
switch (retVal)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
// Some I/O error occurred
innerError =
Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty
result == 0 ? new EndOfStreamException() : // end of file that violates protocol
result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error
null; // no additional info available
break;
case Ssl.SslErrorCode.SSL_ERROR_SSL:
// OpenSSL failure occurred. The error queue contains more details, when building the exception the queue will be cleared.
innerError = Interop.Crypto.CreateOpenSslCryptographicException();
break;
default:
// No additional info available.
innerError = null;
break;
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
// Capture last error to be consistent with CreateOpenSslCryptographicException
ulong errorVal = Crypto.ErrPeekLastError();
Crypto.ErrClearError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#endregion
}
}
| |
// 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.MachineLearning.WebServices
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// These APIs allow end users to operate on Azure Machine Learning Web
/// Services resources. They support the following
/// operations:<ul><li>Create or update a web
/// service</li><li>Get a web
/// service</li><li>Patch a web
/// service</li><li>Delete a web
/// service</li><li>Get All Web Services in a Resource Group
/// </li><li>Get All Web Services in a
/// Subscription</li><li>Get Web Services
/// Keys</li></ul>
/// </summary>
public partial class AzureMLWebServicesManagementClient : ServiceClient<AzureMLWebServicesManagementClient>, IAzureMLWebServicesManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Azure subscription id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The versiong of the Microsoft.MachineLearning resource provider API to be
/// used.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IWebServicesOperations.
/// </summary>
public virtual IWebServicesOperations WebServices { get; private set; }
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AzureMLWebServicesManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AzureMLWebServicesManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AzureMLWebServicesManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AzureMLWebServicesManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.WebServices = new WebServicesOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-05-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WebServiceProperties>("packageType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<WebServiceProperties>("packageType"));
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Portable;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Grid proxy with fake serialization.
/// </summary>
[Serializable]
internal class IgniteProxy : IIgnite, IClusterGroupEx, IPortableWriteAware, ICluster
{
/** */
[NonSerialized]
private readonly IIgnite _ignite;
/// <summary>
/// Default ctor for marshalling.
/// </summary>
public IgniteProxy()
{
// No-op.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
public IgniteProxy(IIgnite ignite)
{
_ignite = ignite;
}
/** <inheritdoc /> */
public string Name
{
get { return _ignite.Name; }
}
/** <inheritdoc /> */
public ICluster Cluster
{
get { return this; }
}
/** <inheritdoc /> */
public IIgnite Ignite
{
get { return this; }
}
/** <inheritdoc /> */
public IClusterGroup ForLocal()
{
return _ignite.Cluster.ForLocal();
}
/** <inheritdoc /> */
public ICompute Compute()
{
return _ignite.Compute();
}
/** <inheritdoc /> */
public ICompute Compute(IClusterGroup clusterGroup)
{
return clusterGroup.Compute();
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
return _ignite.Cluster.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
return _ignite.Cluster.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
return _ignite.Cluster.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(ICollection<Guid> ids)
{
return _ignite.Cluster.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
return _ignite.Cluster.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
return _ignite.Cluster.ForPredicate(p);
}
/** <inheritdoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
return _ignite.Cluster.ForAttribute(name, val);
}
/** <inheritdoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return _ignite.Cluster.ForCacheNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForDataNodes(string name)
{
return _ignite.Cluster.ForDataNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForClientNodes(string name)
{
return _ignite.Cluster.ForClientNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForRemotes()
{
return _ignite.Cluster.ForRemotes();
}
/** <inheritdoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
return _ignite.Cluster.ForHost(node);
}
/** <inheritdoc /> */
public IClusterGroup ForRandom()
{
return _ignite.Cluster.ForRandom();
}
/** <inheritdoc /> */
public IClusterGroup ForOldest()
{
return _ignite.Cluster.ForOldest();
}
/** <inheritdoc /> */
public IClusterGroup ForYoungest()
{
return _ignite.Cluster.ForYoungest();
}
/** <inheritdoc /> */
public IClusterGroup ForDotNet()
{
return _ignite.Cluster.ForDotNet();
}
/** <inheritdoc /> */
public ICollection<IClusterNode> Nodes()
{
return _ignite.Cluster.Nodes();
}
/** <inheritdoc /> */
public IClusterNode Node(Guid id)
{
return _ignite.Cluster.Node(id);
}
/** <inheritdoc /> */
public IClusterNode Node()
{
return _ignite.Cluster.Node();
}
/** <inheritdoc /> */
public IClusterMetrics Metrics()
{
return _ignite.Cluster.Metrics();
}
/** <inheritdoc /> */
public void Dispose()
{
_ignite.Dispose();
}
/** <inheritdoc /> */
public ICache<TK, TV> Cache<TK, TV>(string name)
{
return _ignite.Cache<TK, TV>(name);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name)
{
return _ignite.GetOrCreateCache<TK, TV>(name);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(string name)
{
return _ignite.CreateCache<TK, TV>(name);
}
/** <inheritdoc /> */
public IClusterNode LocalNode
{
get
{
return _ignite.Cluster.LocalNode;
}
}
/** <inheritdoc /> */
public bool PingNode(Guid nodeId)
{
return _ignite.Cluster.PingNode(nodeId);
}
/** <inheritdoc /> */
public long TopologyVersion
{
get { return _ignite.Cluster.TopologyVersion; }
}
/** <inheritdoc /> */
public ICollection<IClusterNode> Topology(long ver)
{
return _ignite.Cluster.Topology(ver);
}
/** <inheritdoc /> */
public void ResetMetrics()
{
_ignite.Cluster.ResetMetrics();
}
/** <inheritdoc /> */
public IDataStreamer<TK, TV> DataStreamer<TK, TV>(string cacheName)
{
return _ignite.DataStreamer<TK, TV>(cacheName);
}
/** <inheritdoc /> */
public IPortables Portables()
{
return _ignite.Portables();
}
/** <inheritdoc /> */
public ICacheAffinity Affinity(string name)
{
return _ignite.Affinity(name);
}
/** <inheritdoc /> */
public ITransactions Transactions
{
get { return _ignite.Transactions; }
}
/** <inheritdoc /> */
public IMessaging Message()
{
return _ignite.Message();
}
/** <inheritdoc /> */
public IMessaging Message(IClusterGroup clusterGroup)
{
return _ignite.Message(clusterGroup);
}
/** <inheritdoc /> */
public IEvents Events()
{
return _ignite.Events();
}
/** <inheritdoc /> */
public IEvents Events(IClusterGroup clusterGroup)
{
return _ignite.Events(clusterGroup);
}
/** <inheritdoc /> */
public IServices Services()
{
return _ignite.Services();
}
/** <inheritdoc /> */
public void WritePortable(IPortableWriter writer)
{
// No-op.
}
/// <summary>
/// Target grid.
/// </summary>
internal IIgnite Target
{
get
{
return _ignite;
}
}
/** <inheritdoc /> */
public IPortableMetadata Metadata(int typeId)
{
return ((IClusterGroupEx)_ignite).Metadata(typeId);
}
}
}
| |
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 ReportWebSite.Areas.HelpPage.ModelDescriptions;
using ReportWebSite.Areas.HelpPage.Models;
namespace ReportWebSite.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 (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// 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.
//
// * Neither the name of Jaroslaw Kowalski 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.
//
namespace NLog.Internal
{
using System;
using System.Text;
/// <summary>
/// URL Encoding helper.
/// </summary>
internal static class UrlHelper
{
[Flags]
public enum EscapeEncodingOptions
{
None = 0,
/// <summary>Allow UnreservedMarks instead of ReservedMarks, as specified by chosen RFC</summary>
UriString = 1,
/// <summary>Use RFC2396 standard (instead of RFC3986)</summary>
LegacyRfc2396 = 2,
/// <summary>Should use lowercase when doing HEX escaping of special characters</summary>
LowerCaseHex = 4,
/// <summary>Replace space ' ' with '+' instead of '%20'</summary>
SpaceAsPlus = 8,
/// <summary>Skip UTF8 encoding, and prefix special characters with '%u'</summary>
NLogLegacy = 16 | LegacyRfc2396 | LowerCaseHex | UriString,
};
/// <summary>
/// Escape unicode string data for use in http-requests
/// </summary>
/// <param name="source">unicode string-data to be encoded</param>
/// <param name="target">target for the encoded result</param>
/// <param name="options"><see cref="EscapeEncodingOptions"/>s for how to perform the encoding</param>
public static void EscapeDataEncode(string source, StringBuilder target, EscapeEncodingOptions options)
{
if (string.IsNullOrEmpty(source))
return;
bool isLowerCaseHex = Contains(options, EscapeEncodingOptions.LowerCaseHex);
bool isSpaceAsPlus = Contains(options, EscapeEncodingOptions.SpaceAsPlus);
bool isNLogLegacy = Contains(options, EscapeEncodingOptions.NLogLegacy);
char[] charArray = null;
byte[] byteArray = null;
char[] hexChars = isLowerCaseHex ? hexLowerChars : hexUpperChars;
for (int i = 0; i < source.Length; ++i)
{
char ch = source[i];
target.Append(ch);
if (IsSimpleCharOrNumber(ch))
continue;
if (isSpaceAsPlus && ch == ' ')
{
target[target.Length - 1] = '+';
continue;
}
if (IsAllowedChar(options, ch))
{
continue;
}
if (isNLogLegacy)
{
HandleLegacyEncoding(target, ch, hexChars);
continue;
}
if (charArray == null)
charArray = new char[1];
charArray[0] = ch;
if (byteArray == null)
byteArray = new byte[8];
WriteWideChars(target, charArray, byteArray, hexChars);
}
}
private static bool Contains(EscapeEncodingOptions options, EscapeEncodingOptions option)
{
return (options & option) == option;
}
/// <summary>
/// Convert the wide-char into utf8-bytes, and then escape
/// </summary>
/// <param name="target"></param>
/// <param name="charArray"></param>
/// <param name="byteArray"></param>
/// <param name="hexChars"></param>
private static void WriteWideChars(StringBuilder target, char[] charArray, byte[] byteArray, char[] hexChars)
{
int byteCount = Encoding.UTF8.GetBytes(charArray, 0, 1, byteArray, 0);
for (int j = 0; j < byteCount; ++j)
{
byte byteCh = byteArray[j];
if (j == 0)
target[target.Length - 1] = '%';
else
target.Append('%');
target.Append(hexChars[(byteCh & 0xf0) >> 4]);
target.Append(hexChars[byteCh & 0xf]);
}
}
private static void HandleLegacyEncoding(StringBuilder target, char ch, char[] hexChars)
{
if (ch < 256)
{
target[target.Length - 1] = '%';
target.Append(hexChars[(ch >> 4) & 0xF]);
target.Append(hexChars[(ch >> 0) & 0xF]);
}
else
{
target[target.Length - 1] = '%';
target.Append('u');
target.Append(hexChars[(ch >> 12) & 0xF]);
target.Append(hexChars[(ch >> 8) & 0xF]);
target.Append(hexChars[(ch >> 4) & 0xF]);
target.Append(hexChars[(ch >> 0) & 0xF]);
}
}
/// <summary>
/// Is allowed?
/// </summary>
/// <param name="options"></param>
/// <param name="ch"></param>
/// <returns></returns>
private static bool IsAllowedChar(EscapeEncodingOptions options, char ch)
{
bool isUriString = (options & EscapeEncodingOptions.UriString) == EscapeEncodingOptions.UriString;
bool isLegacyRfc2396 = (options & EscapeEncodingOptions.LegacyRfc2396) == EscapeEncodingOptions.LegacyRfc2396;
if (isUriString)
{
if (!isLegacyRfc2396 && RFC3986UnreservedMarks.IndexOf(ch) >= 0)
return true;
if (isLegacyRfc2396 && RFC2396UnreservedMarks.IndexOf(ch) >= 0)
return true;
}
else
{
if (!isLegacyRfc2396 && RFC3986ReservedMarks.IndexOf(ch) >= 0)
return true;
if (isLegacyRfc2396 && RFC2396ReservedMarks.IndexOf(ch) >= 0)
return true;
}
return false;
}
/// <summary>
/// Is a-z / A-Z / 0-9
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
private static bool IsSimpleCharOrNumber(char ch)
{
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9';
}
private const string RFC2396ReservedMarks = @";/?:@&=+$,";
private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;=";
private const string RFC2396UnreservedMarks = @"-_.!~*'()";
private const string RFC3986UnreservedMarks = @"-._~";
private static readonly char[] hexUpperChars =
{ '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static readonly char[] hexLowerChars =
{ '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static EscapeEncodingOptions GetUriStringEncodingFlags(bool escapeDataNLogLegacy, bool spaceAsPlus, bool escapeDataRfc3986)
{
EscapeEncodingOptions encodingOptions = EscapeEncodingOptions.UriString;
if (escapeDataNLogLegacy)
encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.NLogLegacy;
else if (!escapeDataRfc3986)
encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.LegacyRfc2396;
if (spaceAsPlus)
encodingOptions |= EscapeEncodingOptions.SpaceAsPlus;
return encodingOptions;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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 System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.Attachments;
using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for OSSL attachment functions
/// </summary>
/// <remarks>
/// TODO: Add tests for all functions
/// </remarks>
[TestFixture]
public class OSSL_ApiAttachmentTests : OpenSimTestCase
{
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource initConfigSource = new IniConfigSource();
IConfig xengineConfig = initConfigSource.AddConfig("XEngine");
xengineConfig.Set("Enabled", "true");
xengineConfig.Set("AllowOSFunctions", "true");
xengineConfig.Set("OSFunctionThreatLevel", "Severe");
IConfig modulesConfig = initConfigSource.AddConfig("Modules");
modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(
m_scene, initConfigSource, new AttachmentsModule(), new BasicInventoryAccessModule());
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
[Test]
public void TestOsForceAttachToAvatarFromInventory()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
string taskInvObjItemName = "sphere";
UUID taskInvObjItemId = UUID.Parse("00000000-0000-0000-0000-100000000000");
AttachmentPoint attachPoint = AttachmentPoint.Chin;
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(m_scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, ua1.PrincipalID);
SceneObjectGroup inWorldObj = SceneHelpers.AddSceneObject(m_scene, "inWorldObj", ua1.PrincipalID);
TaskInventoryItem scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, inWorldObj.RootPart);
new LSL_Api().Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
// SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(1, ua1.PrincipalID);
// Create an object embedded inside the first
TaskInventoryHelpers.AddSceneObject(m_scene.AssetService, inWorldObj.RootPart, taskInvObjItemName, taskInvObjItemId, ua1.PrincipalID);
osslApi.osForceAttachToAvatarFromInventory(taskInvObjItemName, (int)attachPoint);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(taskInvObjItemName));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((uint)attachPoint));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check appearance status
List<AvatarAttachment> attachmentsInAppearance = sp.Appearance.GetAttachments();
Assert.That(attachmentsInAppearance.Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attachmentsInAppearance[0].ItemID), Is.EqualTo((uint)attachPoint));
}
/// <summary>
/// Make sure we can't force attach anything other than objects.
/// </summary>
[Test]
public void TestOsForceAttachToAvatarFromInventoryNotObject()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
string taskInvObjItemName = "sphere";
UUID taskInvObjItemId = UUID.Parse("00000000-0000-0000-0000-100000000000");
AttachmentPoint attachPoint = AttachmentPoint.Chin;
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(m_scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, ua1.PrincipalID);
SceneObjectGroup inWorldObj = SceneHelpers.AddSceneObject(m_scene, "inWorldObj", ua1.PrincipalID);
TaskInventoryItem scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, inWorldObj.RootPart);
new LSL_Api().Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
// Create an object embedded inside the first
TaskInventoryHelpers.AddNotecard(
m_scene.AssetService, inWorldObj.RootPart, taskInvObjItemName, taskInvObjItemId, TestHelpers.ParseTail(0x900), "Hello World!");
bool exceptionCaught = false;
try
{
osslApi.osForceAttachToAvatarFromInventory(taskInvObjItemName, (int)attachPoint);
}
catch (Exception)
{
exceptionCaught = true;
}
Assert.That(exceptionCaught, Is.True);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.False);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(0));
// Check appearance status
List<AvatarAttachment> attachmentsInAppearance = sp.Appearance.GetAttachments();
Assert.That(attachmentsInAppearance.Count, Is.EqualTo(0));
}
[Test]
public void TestOsForceAttachToOtherAvatarFromInventory()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
string taskInvObjItemName = "sphere";
UUID taskInvObjItemId = UUID.Parse("00000000-0000-0000-0000-100000000000");
AttachmentPoint attachPoint = AttachmentPoint.Chin;
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(m_scene, "user", "one", 0x1, "pass");
UserAccount ua2 = UserAccountHelpers.CreateUserWithInventory(m_scene, "user", "two", 0x2, "pass");
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, ua1);
SceneObjectGroup inWorldObj = SceneHelpers.AddSceneObject(m_scene, "inWorldObj", ua1.PrincipalID);
TaskInventoryItem scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, inWorldObj.RootPart);
new LSL_Api().Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, inWorldObj.RootPart, scriptItem, null);
// Create an object embedded inside the first
TaskInventoryHelpers.AddSceneObject(
m_scene.AssetService, inWorldObj.RootPart, taskInvObjItemName, taskInvObjItemId, ua1.PrincipalID);
ScenePresence sp2 = SceneHelpers.AddScenePresence(m_scene, ua2);
osslApi.osForceAttachToOtherAvatarFromInventory(sp2.UUID.ToString(), taskInvObjItemName, (int)attachPoint);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.False);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(0));
Assert.That(sp2.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments2 = sp2.GetAttachments();
Assert.That(attachments2.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments2[0];
Assert.That(attSo.Name, Is.EqualTo(taskInvObjItemName));
Assert.That(attSo.OwnerID, Is.EqualTo(ua2.PrincipalID));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((uint)attachPoint));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check appearance status
List<AvatarAttachment> attachmentsInAppearance = sp.Appearance.GetAttachments();
Assert.That(attachmentsInAppearance.Count, Is.EqualTo(0));
List<AvatarAttachment> attachmentsInAppearance2 = sp2.Appearance.GetAttachments();
Assert.That(attachmentsInAppearance2.Count, Is.EqualTo(1));
Assert.That(sp2.Appearance.GetAttachpoint(attachmentsInAppearance2[0].ItemID), Is.EqualTo((uint)attachPoint));
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2015 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 --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace MsgPack.Serialization
{
/// <summary>
/// Defines basic features for enum object serializers.
/// </summary>
/// <typeparam name="TEnum">The type of enum type itself.</typeparam>
/// <remarks>
/// This class supports auto-detect on deserialization. So the constructor parameter only affects serialization behavior.
/// </remarks>
public abstract class EnumMessagePackSerializer<TEnum> : MessagePackSerializer<TEnum>, ICustomizableEnumSerializer
where TEnum : struct
{
private readonly Type _underlyingType;
private EnumSerializationMethod _serializationMethod; // not readonly -- changed in cloned instance in GetCopyAs()
/// <summary>
/// Initializes a new instance of the <see cref="EnumMessagePackSerializer{TEnum}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="serializationMethod">The <see cref="EnumSerializationMethod"/> which determines serialization form of the enums.</param>
/// <exception cref="InvalidOperationException"><c>TEnum</c> is not enum type.</exception>
protected EnumMessagePackSerializer( SerializationContext ownerContext, EnumSerializationMethod serializationMethod )
: base( ownerContext )
{
if ( !typeof( TEnum ).GetIsEnum() )
{
throw new InvalidOperationException(
String.Format( CultureInfo.CurrentCulture, "Type '{0}' is not enum.", typeof( TEnum ) )
);
}
this._serializationMethod = serializationMethod;
this._underlyingType = Enum.GetUnderlyingType( typeof( TEnum ) );
}
/// <summary>
/// Serializes specified object with specified <see cref="Packer"/>.
/// </summary>
/// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param>
/// <param name="objectTree">Object to be serialized.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )]
protected internal sealed override void PackToCore( Packer packer, TEnum objectTree )
{
if ( this._serializationMethod == EnumSerializationMethod.ByUnderlyingValue )
{
this.PackUnderlyingValueTo( packer, objectTree );
}
else
{
packer.PackString( objectTree.ToString() );
}
}
/// <summary>
/// Packs enum value as its underlying value.
/// </summary>
/// <param name="packer">The packer.</param>
/// <param name="enumValue">The enum value to be packed.</param>
protected internal abstract void PackUnderlyingValueTo( Packer packer, TEnum enumValue );
/// <summary>
/// Deserializes object with specified <see cref="Unpacker"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <returns>Deserialized object.</returns>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )]
protected internal sealed override TEnum UnpackFromCore( Unpacker unpacker )
{
if ( unpacker.LastReadData.IsRaw )
{
var asString = unpacker.LastReadData.AsString();
TEnum result;
#if NETFX_35 || UNITY
try
{
result = ( TEnum ) Enum.Parse( typeof( TEnum ), asString, false );
}
catch ( ArgumentException ex )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Name '{0}' is not member of enum type '{1}'.",
asString,
typeof( TEnum )
),
ex
);
}
#else
if ( !Enum.TryParse( asString, false, out result ) )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Name '{0}' is not member of enum type '{1}'.",
asString,
typeof( TEnum )
)
);
}
#endif // NETFX_35 || UNITY
return result;
}
else if ( unpacker.LastReadData.IsTypeOf( this._underlyingType ).GetValueOrDefault() )
{
return this.UnpackFromUnderlyingValue( unpacker.LastReadData );
}
else
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Type '{0}' is not underlying type of enum type '{1}'.",
unpacker.LastReadData.UnderlyingType,
typeof( TEnum )
)
);
}
}
/// <summary>
/// Unpacks enum value from underlying integral value.
/// </summary>
/// <param name="messagePackObject">The message pack object which represents some integral value.</param>
/// <returns>
/// An enum value.
/// </returns>
/// <exception cref="SerializationException">The type of integral value is not compatible with underlying type of the enum.</exception>
protected internal abstract TEnum UnpackFromUnderlyingValue( MessagePackObject messagePackObject );
ICustomizableEnumSerializer ICustomizableEnumSerializer.GetCopyAs( EnumSerializationMethod method )
{
if ( method == this._serializationMethod )
{
return this;
}
var clone = this.MemberwiseClone() as EnumMessagePackSerializer<TEnum>;
// ReSharper disable once PossibleNullReferenceException
clone._serializationMethod = method;
return clone;
}
}
#if UNITY
internal abstract class UnityEnumMessagePackSerializer : NonGenericMessagePackSerializer, ICustomizableEnumSerializer
{
private readonly Type _underlyingType;
private EnumSerializationMethod _serializationMethod; // not readonly -- changed in cloned instance in GetCopyAs()
protected UnityEnumMessagePackSerializer( SerializationContext ownerContext, Type targetType, EnumSerializationMethod serializationMethod )
: base( ownerContext, targetType )
{
if ( !targetType.GetIsEnum() )
{
throw new InvalidOperationException(
String.Format( CultureInfo.CurrentCulture, "Type '{0}' is not enum.", targetType )
);
}
this._serializationMethod = serializationMethod;
this._underlyingType = Enum.GetUnderlyingType( targetType );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )]
protected internal sealed override void PackToCore( Packer packer, object objectTree )
{
if ( this._serializationMethod == EnumSerializationMethod.ByUnderlyingValue )
{
this.PackUnderlyingValueTo( packer, objectTree );
}
else
{
packer.PackString( objectTree.ToString() );
}
}
protected internal abstract void PackUnderlyingValueTo( Packer packer, object enumValue );
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )]
protected internal sealed override object UnpackFromCore( Unpacker unpacker )
{
if ( unpacker.LastReadData.IsRaw )
{
var asString = unpacker.LastReadData.AsString();
try
{
return Enum.Parse( this.TargetType, asString, false );
}
catch ( ArgumentException ex )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Name '{0}' is not member of enum type '{1}'.",
asString,
this.TargetType
),
ex
);
}
}
else if ( unpacker.LastReadData.IsTypeOf( this._underlyingType ).GetValueOrDefault() )
{
return this.UnpackFromUnderlyingValue( unpacker.LastReadData );
}
else
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Type '{0}' is not underlying type of enum type '{1}'.",
unpacker.LastReadData.UnderlyingType,
this.TargetType
)
);
}
}
protected internal abstract object UnpackFromUnderlyingValue( MessagePackObject messagePackObject );
ICustomizableEnumSerializer ICustomizableEnumSerializer.GetCopyAs( EnumSerializationMethod method )
{
if ( method == this._serializationMethod )
{
return this;
}
var clone = this.MemberwiseClone() as UnityEnumMessagePackSerializer;
// ReSharper disable once PossibleNullReferenceException
clone._serializationMethod = method;
return clone;
}
}
#endif // UNITY
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Security.Cryptography.Asn1
{
internal partial class AsnReader
{
/// <summary>
/// Reads the next value as a BIT STRING with tag UNIVERSAL 3, returning the contents
/// as a <see cref="ReadOnlyMemory{T}"/> over the original data.
/// </summary>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="value">
/// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data
/// corresponding to the value of the BIT STRING.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if the BIT STRING value had a primitive encoding,
/// <c>false</c> and does not advance the reader if it had a constructed encoding.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryCopyBitStringBytes(Span{byte},out int,out int)"/>
public bool TryReadPrimitiveBitStringValue(out int unusedBitCount, out ReadOnlyMemory<byte> value)
=> TryReadPrimitiveBitStringValue(Asn1Tag.PrimitiveBitString, out unusedBitCount, out value);
/// <summary>
/// Reads the next value as a BIT STRING with a specified tag, returning the contents
/// as a <see cref="ReadOnlyMemory{T}"/> over the original data.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="value">
/// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data
/// corresponding to the value of the BIT STRING.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if the BIT STRING value had a primitive encoding,
/// <c>false</c> and does not advance the reader if it had a constructed encoding.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <seealso cref="TryCopyBitStringBytes(Asn1Tag,Span{byte},out int,out int)"/>
public bool TryReadPrimitiveBitStringValue(
Asn1Tag expectedTag,
out int unusedBitCount,
out ReadOnlyMemory<byte> value)
{
bool isPrimitive = TryReadPrimitiveBitStringValue(
expectedTag,
out Asn1Tag actualTag,
out int? contentsLength,
out int headerLength,
out unusedBitCount,
out value,
out byte normalizedLastByte);
if (isPrimitive)
{
// A BER reader which encountered a situation where an "unused" bit was not
// set to 0.
if (value.Length != 0 && normalizedLastByte != value.Span[value.Length - 1])
{
unusedBitCount = 0;
value = default(ReadOnlyMemory<byte>);
return false;
}
// Skip the tag+length (header) and the unused bit count byte (1) and the contents.
_data = _data.Slice(headerLength + value.Length + 1);
}
return isPrimitive;
}
/// <summary>
/// Reads the next value as a BIT STRING with tag UNIVERSAL 3, copying the value
/// into a provided destination buffer.
/// </summary>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadBitString(out int)"/>
public bool TryCopyBitStringBytes(
Span<byte> destination,
out int unusedBitCount,
out int bytesWritten)
{
return TryCopyBitStringBytes(
Asn1Tag.PrimitiveBitString,
destination,
out unusedBitCount,
out bytesWritten);
}
/// <summary>
/// Reads the next value as a BIT STRING with a specified tag, copying the value
/// into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(Asn1Tag,out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadBitString(Asn1Tag,out int)"/>
public bool TryCopyBitStringBytes(
Asn1Tag expectedTag,
Span<byte> destination,
out int unusedBitCount,
out int bytesWritten)
{
if (TryReadPrimitiveBitStringValue(
expectedTag,
out Asn1Tag actualTag,
out int? contentsLength,
out int headerLength,
out unusedBitCount,
out ReadOnlyMemory<byte> value,
out byte normalizedLastByte))
{
if (value.Length > destination.Length)
{
bytesWritten = 0;
unusedBitCount = 0;
return false;
}
CopyBitStringValue(value, normalizedLastByte, destination);
bytesWritten = value.Length;
// contents doesn't include the unusedBitCount value, so add one byte for that.
_data = _data.Slice(headerLength + value.Length + 1);
return true;
}
Debug.Assert(actualTag.IsConstructed);
bool read = TryCopyConstructedBitStringValue(
Slice(_data, headerLength, contentsLength),
destination,
contentsLength == null,
out unusedBitCount,
out int bytesRead,
out bytesWritten);
if (read)
{
_data = _data.Slice(headerLength + bytesRead);
}
return read;
}
/// <summary>
/// Reads the next value as a BIT STRING with tag UNIVERSAL 3, copying the value
/// into a provided destination buffer.
/// </summary>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadBitString(out int)"/>
public bool TryCopyBitStringBytes(
ArraySegment<byte> destination,
out int unusedBitCount,
out int bytesWritten)
{
return TryCopyBitStringBytes(
Asn1Tag.PrimitiveBitString,
destination.AsSpan(),
out unusedBitCount,
out bytesWritten);
}
/// <summary>
/// Reads the next value as a BIT STRING with a specified tag, copying the value
/// into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(Asn1Tag,out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadBitString(Asn1Tag,out int)"/>
public bool TryCopyBitStringBytes(
Asn1Tag expectedTag,
ArraySegment<byte> destination,
out int unusedBitCount,
out int bytesWritten)
{
return TryCopyBitStringBytes(
expectedTag,
destination.AsSpan(),
out unusedBitCount,
out bytesWritten);
}
/// <summary>
/// Reads the next value as a BIT STRING with tag UNIVERSAL 3, returning the value
/// in a byte array.
/// </summary>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <returns>
/// a copy of the value in a newly allocated, precisely sized, array.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyBitStringBytes(Span{byte},out int,out int)"/>
public byte[] ReadBitString(out int unusedBitCount)
{
return ReadBitString(Asn1Tag.PrimitiveBitString, out unusedBitCount);
}
/// <summary>
/// Reads the next value as a BIT STRING with tag UNIVERSAL 3, returning the value
/// in a byte array.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="unusedBitCount">
/// On success, receives the number of bits in the last byte which were reported as
/// "unused" by the writer.
/// </param>
/// <returns>
/// a copy of the value in a newly allocated, precisely sized, array.
/// </returns>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <seealso cref="TryReadPrimitiveBitStringValue(Asn1Tag,out int,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyBitStringBytes(Asn1Tag,Span{byte},out int,out int)"/>
public byte[] ReadBitString(Asn1Tag expectedTag, out int unusedBitCount)
{
ReadOnlyMemory<byte> memory;
if (TryReadPrimitiveBitStringValue(expectedTag, out unusedBitCount, out memory))
{
return memory.ToArray();
}
memory = PeekEncodedValue();
// Guaranteed long enough
byte[] rented = ArrayPool<byte>.Shared.Rent(memory.Length);
int dataLength = 0;
try
{
if (!TryCopyBitStringBytes(expectedTag, rented, out unusedBitCount, out dataLength))
{
Debug.Fail("TryCopyBitStringBytes failed with a pre-allocated buffer");
throw new CryptographicException();
}
byte[] alloc = new byte[dataLength];
rented.AsSpan(0, dataLength).CopyTo(alloc);
return alloc;
}
finally
{
rented.AsSpan(0, dataLength).Clear();
ArrayPool<byte>.Shared.Return(rented);
}
}
private void ParsePrimitiveBitStringContents(
ReadOnlyMemory<byte> source,
out int unusedBitCount,
out ReadOnlyMemory<byte> value,
out byte normalizedLastByte)
{
// T-REC-X.690-201508 sec 9.2
if (RuleSet == AsnEncodingRules.CER && source.Length > MaxCERSegmentSize)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
// T-REC-X.690-201508 sec 8.6.2.3
if (source.Length == 0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
ReadOnlySpan<byte> sourceSpan = source.Span;
unusedBitCount = sourceSpan[0];
// T-REC-X.690-201508 sec 8.6.2.2
if (unusedBitCount > 7)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (source.Length == 1)
{
// T-REC-X.690-201508 sec 8.6.2.4
if (unusedBitCount > 0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Debug.Assert(unusedBitCount == 0);
value = ReadOnlyMemory<byte>.Empty;
normalizedLastByte = 0;
return;
}
// Build a mask for the bits that are used so the normalized value can be computed
//
// If 3 bits are "unused" then build a mask for them to check for 0.
// -1 << 3 => 0b1111_1111 << 3 => 0b1111_1000
int mask = -1 << unusedBitCount;
byte lastByte = sourceSpan[sourceSpan.Length - 1];
byte maskedByte = (byte)(lastByte & mask);
if (maskedByte != lastByte)
{
// T-REC-X.690-201508 sec 11.2.1
if (RuleSet == AsnEncodingRules.DER || RuleSet == AsnEncodingRules.CER)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
normalizedLastByte = maskedByte;
value = source.Slice(1);
}
private delegate void BitStringCopyAction(
ReadOnlyMemory<byte> value,
byte normalizedLastByte,
Span<byte> destination);
private static void CopyBitStringValue(
ReadOnlyMemory<byte> value,
byte normalizedLastByte,
Span<byte> destination)
{
if (value.Length == 0)
{
return;
}
value.Span.CopyTo(destination);
// Replace the last byte with the normalized answer.
destination[value.Length - 1] = normalizedLastByte;
}
private int CountConstructedBitString(ReadOnlyMemory<byte> source, bool isIndefinite)
{
Span<byte> destination = Span<byte>.Empty;
return ProcessConstructedBitString(
source,
destination,
null,
isIndefinite,
out _,
out _);
}
private void CopyConstructedBitString(
ReadOnlyMemory<byte> source,
Span<byte> destination,
bool isIndefinite,
out int unusedBitCount,
out int bytesRead,
out int bytesWritten)
{
Span<byte> tmpDest = destination;
bytesWritten = ProcessConstructedBitString(
source,
tmpDest,
(value, lastByte, dest) => CopyBitStringValue(value, lastByte, dest),
isIndefinite,
out unusedBitCount,
out bytesRead);
}
private int ProcessConstructedBitString(
ReadOnlyMemory<byte> source,
Span<byte> destination,
BitStringCopyAction copyAction,
bool isIndefinite,
out int lastUnusedBitCount,
out int bytesRead)
{
lastUnusedBitCount = 0;
bytesRead = 0;
int lastSegmentLength = MaxCERSegmentSize;
AsnReader tmpReader = new AsnReader(source, RuleSet);
Stack<(AsnReader, bool, int)> readerStack = null;
int totalLength = 0;
Asn1Tag tag = Asn1Tag.ConstructedBitString;
Span<byte> curDest = destination;
do
{
while (tmpReader.HasData)
{
tag = tmpReader.ReadTagAndLength(out int? length, out int headerLength);
if (tag == Asn1Tag.PrimitiveBitString)
{
if (lastUnusedBitCount != 0)
{
// T-REC-X.690-201508 sec 8.6.4, only the last segment may have
// a number of bits not a multiple of 8.
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (RuleSet == AsnEncodingRules.CER && lastSegmentLength != MaxCERSegmentSize)
{
// T-REC-X.690-201508 sec 9.2
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Debug.Assert(length != null);
ReadOnlyMemory<byte> encodedValue = Slice(tmpReader._data, headerLength, length.Value);
ParsePrimitiveBitStringContents(
encodedValue,
out lastUnusedBitCount,
out ReadOnlyMemory<byte> contents,
out byte normalizedLastByte);
int localLen = headerLength + encodedValue.Length;
tmpReader._data = tmpReader._data.Slice(localLen);
bytesRead += localLen;
totalLength += contents.Length;
lastSegmentLength = encodedValue.Length;
if (copyAction != null)
{
copyAction(contents, normalizedLastByte, curDest);
curDest = curDest.Slice(contents.Length);
}
}
else if (tag == Asn1Tag.EndOfContents && isIndefinite)
{
ValidateEndOfContents(tag, length, headerLength);
bytesRead += headerLength;
if (readerStack?.Count > 0)
{
(AsnReader topReader, bool wasIndefinite, int pushedBytesRead) = readerStack.Pop();
topReader._data = topReader._data.Slice(bytesRead);
bytesRead += pushedBytesRead;
isIndefinite = wasIndefinite;
tmpReader = topReader;
}
else
{
// We have matched the EndOfContents that brought us here.
break;
}
}
else if (tag == Asn1Tag.ConstructedBitString)
{
if (RuleSet == AsnEncodingRules.CER)
{
// T-REC-X.690-201508 sec 9.2
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (readerStack == null)
{
readerStack = new Stack<(AsnReader, bool, int)>();
}
readerStack.Push((tmpReader, isIndefinite, bytesRead));
tmpReader = new AsnReader(
Slice(tmpReader._data, headerLength, length),
RuleSet);
bytesRead = headerLength;
isIndefinite = (length == null);
}
else
{
// T-REC-X.690-201508 sec 8.6.4.1 (in particular, Note 2)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
if (isIndefinite && tag != Asn1Tag.EndOfContents)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (readerStack?.Count > 0)
{
(AsnReader topReader, bool wasIndefinite, int pushedBytesRead) = readerStack.Pop();
tmpReader = topReader;
tmpReader._data = tmpReader._data.Slice(bytesRead);
isIndefinite = wasIndefinite;
bytesRead += pushedBytesRead;
}
else
{
tmpReader = null;
}
} while (tmpReader != null);
return totalLength;
}
private bool TryCopyConstructedBitStringValue(
ReadOnlyMemory<byte> source,
Span<byte> dest,
bool isIndefinite,
out int unusedBitCount,
out int bytesRead,
out int bytesWritten)
{
// Call CountConstructedBitString to get the required byte and to verify that the
// data is well-formed before copying into dest.
int contentLength = CountConstructedBitString(source, isIndefinite);
// Since the unused bits byte from the segments don't count, only one segment
// returns 999 (or less), the second segment bumps the count to 1000, and is legal.
//
// T-REC-X.690-201508 sec 9.2
if (RuleSet == AsnEncodingRules.CER && contentLength < MaxCERSegmentSize)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (dest.Length < contentLength)
{
unusedBitCount = 0;
bytesRead = 0;
bytesWritten = 0;
return false;
}
CopyConstructedBitString(
source,
dest,
isIndefinite,
out unusedBitCount,
out bytesRead,
out bytesWritten);
Debug.Assert(bytesWritten == contentLength);
return true;
}
private bool TryReadPrimitiveBitStringValue(
Asn1Tag expectedTag,
out Asn1Tag actualTag,
out int? contentsLength,
out int headerLength,
out int unusedBitCount,
out ReadOnlyMemory<byte> value,
out byte normalizedLastByte)
{
actualTag = ReadTagAndLength(out contentsLength, out headerLength);
CheckExpectedTag(actualTag, expectedTag, UniversalTagNumber.BitString);
if (actualTag.IsConstructed)
{
if (RuleSet == AsnEncodingRules.DER)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
unusedBitCount = 0;
value = default(ReadOnlyMemory<byte>);
normalizedLastByte = 0;
return false;
}
Debug.Assert(contentsLength.HasValue);
ReadOnlyMemory<byte> encodedValue = Slice(_data, headerLength, contentsLength.Value);
ParsePrimitiveBitStringContents(
encodedValue,
out unusedBitCount,
out value,
out normalizedLastByte);
return true;
}
}
}
| |
// 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.Security;
namespace System
{
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
public static class BitConverter
{
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
public static readonly bool IsLittleEndian /* = false */;
#else
public static readonly bool IsLittleEndian = true;
#endif
// Converts a Boolean into an array of bytes with length one.
public static byte[] GetBytes(bool value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 1);
byte[] r = new byte[1];
r[0] = (value ? (byte)1 : (byte)0);
return r;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts a short into an array of bytes with length
// two.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
fixed (byte* b = bytes)
*((short*)b) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
fixed (byte* b = bytes)
*((int*)b) = value;
return bytes;
}
// Converts a long into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
fixed (byte* b = bytes)
*((long*)b) = value;
return bytes;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
return GetBytes((short)value);
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes((int)value);
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes((long)value);
}
// Converts a float into an array of bytes with length
// four.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
return GetBytes(*(int*)&value);
}
// Converts a double into an array of bytes with length
// eight.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(*(long*)&value);
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return (char)ToInt16(value, startIndex);
}
// Converts an array of bytes into a short.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe short ToInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 2 == 0)
{
// data is aligned
return *((short*)pbyte);
}
else if (IsLittleEndian)
{
return (short)((*pbyte) | (*(pbyte + 1) << 8));
}
else
{
return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
}
// Converts an array of bytes into an int.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe int ToInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 4 == 0)
{
// data is aligned
return *((int*)pbyte);
}
else if (IsLittleEndian)
{
return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
}
else
{
return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
}
}
}
// Converts an array of bytes into a long.
[System.Security.SecuritySafeCritical] // auto-generated
public static unsafe long ToInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
fixed (byte* pbyte = &value[startIndex])
{
if (startIndex % 8 == 0)
{
// data is aligned
return *((long*)pbyte);
}
else if (IsLittleEndian)
{
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
return (uint)i1 | ((long)i2 << 32);
}
else
{
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
return (uint)i2 | ((long)i1 << 32);
}
}
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 2)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return (ushort)ToInt16(value, startIndex);
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return (uint)ToInt32(value, startIndex);
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
return (ulong)ToInt64(value, startIndex);
}
// Converts an array of bytes into a float.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static float ToSingle(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 4)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
int val = ToInt32(value, startIndex);
return *(float*)&val;
}
// Converts an array of bytes into a double.
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static double ToDouble(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if ((uint)startIndex >= value.Length)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 8)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
long val = ToInt64(value, startIndex);
return *(double*)&val;
}
private static char GetHexValue(int i)
{
Debug.Assert(i >= 0 && i < 16, "i is out of range.");
if (i < 10)
{
return (char)(i + '0');
}
return (char)(i - 10 + 'A');
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
ThrowValueArgumentNull();
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
ThrowStartIndexArgumentOutOfRange();
if (length < 0)
throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_GenericPositive);
if (startIndex > value.Length - length)
ThrowValueArgumentTooSmall();
Contract.EndContractBlock();
if (length == 0)
{
return string.Empty;
}
if (length > (int.MaxValue / 3))
{
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException("length", SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
int chArrayLength = length * 3;
char[] chArray = new char[chArrayLength];
int i = 0;
int index = startIndex;
for (i = 0; i < chArrayLength; i += 3)
{
byte b = value[index++];
chArray[i] = GetHexValue(b / 16);
chArray[i + 1] = GetHexValue(b % 16);
chArray[i + 2] = '-';
}
// We don't need the last '-' character
return new string(chArray, 0, chArray.Length - 1);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value)
{
if (value == null)
ThrowValueArgumentNull();
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex)
{
if (value == null)
ThrowValueArgumentNull();
if (startIndex < 0)
ThrowStartIndexArgumentOutOfRange();
if (startIndex > value.Length - 1)
ThrowStartIndexArgumentOutOfRange(); // differs from other overloads, which throw base ArgumentException
Contract.EndContractBlock();
return value[startIndex] != 0;
}
[SecuritySafeCritical]
public static unsafe long DoubleToInt64Bits(double value)
{
// If we're on a big endian machine, what should this method do? You could argue for
// either big endian or little endian, depending on whether you are writing to a file that
// should be used by other programs on that processor, or for compatibility across multiple
// formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile.
// If we ever run on big endian machines, produce two versions where endianness is specified.
Debug.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec.");
return *((long*)&value);
}
[SecuritySafeCritical]
public static unsafe double Int64BitsToDouble(long value)
{
// If we're on a big endian machine, what should this method do? You could argue for
// either big endian or little endian, depending on whether you are writing to a file that
// should be used by other programs on that processor, or for compatibility across multiple
// formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile.
// If we ever run on big endian machines, produce two versions where endianness is specified.
Debug.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec.");
return *((double*)&value);
}
private static void ThrowValueArgumentNull()
{
throw new ArgumentNullException("value");
}
private static void ThrowStartIndexArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index);
}
private static void ThrowValueArgumentTooSmall()
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall, "value");
}
}
}
| |
using System.Net;
using FluentAssertions;
using FluentAssertions.Extensions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Creating;
public sealed class AtomicCreateResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicCreateResourceTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
// These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints.
testContext.UseController<LyricsController>();
testContext.UseController<MusicTracksController>();
testContext.UseController<PlaylistsController>();
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.AllowUnknownFieldsInRequestBody = false;
}
[Fact]
public async Task Can_create_resource()
{
// Arrange
string newArtistName = _fakers.Performer.Generate().ArtistName!;
DateTimeOffset newBornAt = _fakers.Performer.Generate().BornAt;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "performers",
attributes = new
{
artistName = newArtistName,
bornAt = newBornAt
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("performers");
resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName));
resource.Attributes.ShouldContainKey("bornAt").With(value => value.Should().Be(newBornAt));
resource.Relationships.Should().BeNull();
});
int newPerformerId = int.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Performer performerInDatabase = await dbContext.Performers.FirstWithIdAsync(newPerformerId);
performerInDatabase.ArtistName.Should().Be(newArtistName);
performerInDatabase.BornAt.Should().Be(newBornAt);
});
}
[Fact]
public async Task Can_create_resources()
{
// Arrange
const int elementCount = 5;
List<MusicTrack> newTracks = _fakers.MusicTrack.Generate(elementCount);
var operationElements = new List<object>(elementCount);
for (int index = 0; index < elementCount; index++)
{
operationElements.Add(new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTracks[index].Title,
lengthInSeconds = newTracks[index].LengthInSeconds,
genre = newTracks[index].Genre,
releasedAt = newTracks[index].ReleasedAt
}
}
});
}
var requestBody = new
{
atomic__operations = operationElements
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(elementCount);
for (int index = 0; index < elementCount; index++)
{
responseDocument.Results[index].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.ShouldNotBeNull();
resource.Type.Should().Be("musicTracks");
resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTracks[index].Title));
resource.Attributes.ShouldContainKey("lengthInSeconds")
.With(value => value.As<decimal?>().Should().BeApproximately(newTracks[index].LengthInSeconds));
resource.Attributes.ShouldContainKey("genre").With(value => value.Should().Be(newTracks[index].Genre));
resource.Attributes.ShouldContainKey("releasedAt").With(value => value.Should().Be(newTracks[index].ReleasedAt));
resource.Relationships.ShouldNotBeEmpty();
});
}
Guid[] newTrackIds = responseDocument.Results.Select(result => Guid.Parse(result.Data.SingleValue!.Id.ShouldNotBeNull())).ToArray();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.Where(musicTrack => newTrackIds.Contains(musicTrack.Id)).ToListAsync();
tracksInDatabase.ShouldHaveCount(elementCount);
for (int index = 0; index < elementCount; index++)
{
MusicTrack trackInDatabase = tracksInDatabase.Single(musicTrack => musicTrack.Id == newTrackIds[index]);
trackInDatabase.Title.Should().Be(newTracks[index].Title);
trackInDatabase.LengthInSeconds.Should().BeApproximately(newTracks[index].LengthInSeconds);
trackInDatabase.Genre.Should().Be(newTracks[index].Genre);
trackInDatabase.ReleasedAt.Should().Be(newTracks[index].ReleasedAt);
}
});
}
[Fact]
public async Task Can_create_resource_without_attributes_or_relationships()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "performers",
attributes = new
{
},
relationship = new
{
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("performers");
resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().BeNull());
resource.Attributes.ShouldContainKey("bornAt").With(value => value.Should().Be(default(DateTimeOffset)));
resource.Relationships.Should().BeNull();
});
int newPerformerId = int.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Performer performerInDatabase = await dbContext.Performers.FirstWithIdAsync(newPerformerId);
performerInDatabase.ArtistName.Should().BeNull();
performerInDatabase.BornAt.Should().Be(default);
});
}
[Fact]
public async Task Cannot_create_resource_with_unknown_attribute()
{
// Arrange
string newName = _fakers.Playlist.Generate().Name;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
attributes = new
{
doesNotExist = "ignored",
name = newName
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown attribute found.");
error.Detail.Should().Be("Attribute 'doesNotExist' does not exist on resource type 'playlists'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/attributes/doesNotExist");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Can_create_resource_with_unknown_attribute()
{
// Arrange
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.AllowUnknownFieldsInRequestBody = true;
string newName = _fakers.Playlist.Generate().Name;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
attributes = new
{
doesNotExist = "ignored",
name = newName
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("playlists");
resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newName));
resource.Relationships.ShouldNotBeEmpty();
});
long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist performerInDatabase = await dbContext.Playlists.FirstWithIdAsync(newPlaylistId);
performerInDatabase.Name.Should().Be(newName);
});
}
[Fact]
public async Task Cannot_create_resource_with_unknown_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "lyrics",
relationships = new
{
doesNotExist = new
{
data = new
{
type = Unknown.ResourceType,
id = Unknown.StringId.Int32
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown relationship found.");
error.Detail.Should().Be("Relationship 'doesNotExist' does not exist on resource type 'lyrics'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/doesNotExist");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Can_create_resource_with_unknown_relationship()
{
// Arrange
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.AllowUnknownFieldsInRequestBody = true;
string newLyricText = _fakers.Lyric.Generate().Text;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "lyrics",
attributes = new
{
text = newLyricText
},
relationships = new
{
doesNotExist = new
{
data = new
{
type = Unknown.ResourceType,
id = Unknown.StringId.Int32
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("lyrics");
resource.Attributes.ShouldNotBeEmpty();
resource.Relationships.ShouldNotBeEmpty();
});
long newLyricId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.FirstWithIdAsync(newLyricId);
lyricInDatabase.ShouldNotBeNull();
});
}
[Fact]
public async Task Cannot_create_resource_with_client_generated_ID()
{
// Arrange
MusicTrack newTrack = _fakers.MusicTrack.Generate();
newTrack.Id = Guid.NewGuid();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
id = newTrack.StringId,
attributes = new
{
title = newTrack.Title
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("Failed to deserialize request body: The use of client-generated IDs is disabled.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/id");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_href_element()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
href = "/api/v1/musicTracks"
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'href' element is not supported.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/href");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_ref_element()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
@ref = new
{
type = "musicTracks"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'relationship' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_missing_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new object[]
{
new
{
op = "add"
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_null_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new object[]
{
new
{
op = "add",
data = (object?)null
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of 'null'.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_array_data()
{
// Arrange
string newArtistName = _fakers.Performer.Generate().ArtistName!;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new[]
{
new
{
type = "performers",
attributes = new
{
artistName = newArtistName
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of an array.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_missing_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
attributes = new
{
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_for_unknown_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = Unknown.ResourceType
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_attribute_with_blocked_capability()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "lyrics",
attributes = new
{
createdAt = 12.July(1980)
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Attribute value cannot be assigned when creating resource.");
error.Detail.Should().Be("The attribute 'createdAt' on resource type 'lyrics' cannot be assigned to.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/attributes/createdAt");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_with_readonly_attribute()
{
// Arrange
string newPlaylistName = _fakers.Playlist.Generate().Name;
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
attributes = new
{
name = newPlaylistName,
isArchived = true
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Attribute is read-only.");
error.Detail.Should().Be("Attribute 'isArchived' on resource type 'playlists' is read-only.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/attributes/isArchived");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_with_incompatible_attribute_value()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "performers",
attributes = new
{
bornAt = 12345
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Incompatible attribute value found.");
error.Detail.Should().Be("Failed to convert attribute 'bornAt' with value '12345' of type 'Number' to type 'DateTimeOffset'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/attributes/bornAt");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Can_create_resource_with_attributes_and_multiple_relationship_types()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
Performer existingPerformer = _fakers.Performer.Generate();
string newTitle = _fakers.MusicTrack.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingLyric, existingCompany, existingPerformer);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = existingLyric.StringId
}
},
ownedBy = new
{
data = new
{
type = "recordCompanies",
id = existingCompany.StringId
}
},
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformer.StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("musicTracks");
resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTitle));
resource.Relationships.ShouldNotBeEmpty();
});
Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
MusicTrack trackInDatabase = await dbContext.MusicTracks
.Include(musicTrack => musicTrack.Lyric)
.Include(musicTrack => musicTrack.OwnedBy)
.Include(musicTrack => musicTrack.Performers)
.FirstWithIdAsync(newTrackId);
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
trackInDatabase.Title.Should().Be(newTitle);
trackInDatabase.Lyric.ShouldNotBeNull();
trackInDatabase.Lyric.Id.Should().Be(existingLyric.Id);
trackInDatabase.OwnedBy.ShouldNotBeNull();
trackInDatabase.OwnedBy.Id.Should().Be(existingCompany.Id);
trackInDatabase.Performers.ShouldHaveCount(1);
trackInDatabase.Performers[0].Id.Should().Be(existingPerformer.Id);
});
}
}
| |
#pragma warning disable MA0101 // String contains an implicit end of line character
using System.Reflection;
using System.Runtime.Loader;
using FluentAssertions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using TestUtilities;
using Xunit;
namespace Meziantou.Framework.StronglyTypedId.Tests;
public sealed class StronglyTypedIdSourceGeneratorTests
{
private static async Task<(GeneratorDriverRunResult GeneratorResult, Compilation OutputCompilation, byte[] Assembly)> GenerateFiles(string file, bool mustCompile = true, string[] assemblyLocations = null)
{
var netcoreRef = await NuGetHelpers.GetNuGetReferences("Microsoft.NETCore.App.Ref", "5.0.0", "ref/net5.0/");
var newtonsoftJsonRef = await NuGetHelpers.GetNuGetReferences("Newtonsoft.Json", "12.0.3", "lib/netstandard2.0/");
assemblyLocations ??= Array.Empty<string>();
var references = assemblyLocations
.Concat(netcoreRef)
.Concat(newtonsoftJsonRef)
.Select(loc => MetadataReference.CreateFromFile(loc))
.ToArray();
var compilation = CSharpCompilation.Create("compilation",
new[] { CSharpSyntaxTree.ParseText(file) },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var generator = new StronglyTypedIdSourceGenerator();
var wrapperType = (ISourceGenerator)Activator.CreateInstance(Type.GetType("Microsoft.CodeAnalysis.IncrementalGeneratorWrapper, Microsoft.CodeAnalysis", throwOnError: true), generator);
GeneratorDriver driver = CSharpGeneratorDriver.Create(
generators: new ISourceGenerator[] { wrapperType });
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
diagnostics.Should().BeEmpty();
var runResult = driver.GetRunResult();
// Validate the output project compiles
using var ms = new MemoryStream();
var result = outputCompilation.Emit(ms);
if (mustCompile)
{
var diags = string.Join("\n", result.Diagnostics);
var generated = (await runResult.GeneratedTrees[1].GetRootAsync()).ToFullString();
result.Success.Should().BeTrue("Project cannot build:\n" + diags + "\n\n\n" + generated);
result.Diagnostics.Should().BeEmpty();
}
return (runResult, outputCompilation, result.Success ? ms.ToArray() : null);
}
[Fact]
public async Task GenerateStructInNamespaceAndClass()
{
var sourceCode = @"
namespace A
{
namespace B
{
partial class C
{
[StronglyTypedId(typeof(int))]
public partial struct Test {}
}
}
}";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
var type = a.GetType("A.B.C+Test");
var from = (MethodInfo)type.GetMember("FromInt32").Single();
var instance = from.Invoke(null, new object[] { 10 });
var json = System.Text.Json.JsonSerializer.Serialize(instance);
var deserialized = System.Text.Json.JsonSerializer.Deserialize(json, type);
var deserialized2 = System.Text.Json.JsonSerializer.Deserialize(@"{ ""a"": {}, ""b"": false, ""Value"": 10 }", type);
json.Should().Be("10");
deserialized.Should().Be(instance);
deserialized2.Should().Be(instance);
}
}
finally
{
alc.Unload();
}
}
[Fact]
public async Task GenerateStructInNamespace()
{
var sourceCode = @"
namespace A
{
namespace B
{
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test {}
}
}";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
var type = a.GetType("A.B.Test");
var from = (MethodInfo)type.GetMember("FromInt32").Single();
var instance = from.Invoke(null, new object[] { 10 });
var json = System.Text.Json.JsonSerializer.Serialize(instance);
var deserialized = System.Text.Json.JsonSerializer.Deserialize(json, type);
var deserialized2 = System.Text.Json.JsonSerializer.Deserialize(@"{ ""a"": {}, ""b"": false, ""Value"": 10 }", type);
json.Should().Be("10");
deserialized.Should().Be(instance);
deserialized2.Should().Be(instance);
}
}
finally
{
alc.Unload();
}
}
[Fact]
public async Task GenerateStruct_Guid_New()
{
var sourceCode = @"
[StronglyTypedIdAttribute(typeof(System.Guid))]
public partial struct Test {}
";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
var guid = Guid.NewGuid();
var type = a.GetType("Test");
var from = (MethodInfo)type.GetMember("FromGuid").Single();
var newMethod = (MethodInfo)type.GetMember("New").Single();
var emptyInstance = from.Invoke(null, new object[] { Guid.Empty });
var instance = from.Invoke(null, new object[] { guid });
var newInstance = newMethod.Invoke(null, null);
newInstance.Should().NotBe(instance);
newInstance.Should().NotBe(emptyInstance);
}
}
finally
{
alc.Unload();
}
}
[Fact]
public async Task Generate_ExistingOperators()
{
var sourceCode = @"
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test : System.IEquatable<Test>
{
public override string ToString() => null;
public override bool Equals(object a) => true;
public override int GetHashCode() => 0;
public bool Equals(Test a) => true;
public static bool operator ==(Test a, Test b) => true;
public static bool operator !=(Test a, Test b) => true;
}
";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
result.Assembly.Should().NotBeNull();
}
[Fact]
public async Task GenerateStruct_ToString()
{
var sourceCode = @"
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test {}
";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
CultureInfoUtilities.UseCulture("sv-SE", () =>
{
var type = a.GetType("Test");
var from = (MethodInfo)type.GetMember("FromInt32").Single();
var instance = from.Invoke(null, new object[] { -42 });
var str = instance.ToString();
str.Should().Be("Test { Value = -42 }");
});
}
}
finally
{
alc.Unload();
}
}
[Fact]
public async Task GenerateStruct_Parse_ReadOnlySpan()
{
var sourceCode = @"
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test {}
";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
var type = a.GetType("Test");
var parse = type.GetMember("Parse").Length;
parse.Should().Be(2);
}
}
finally
{
alc.Unload();
}
}
[Fact]
public async Task GenerateStruct_Parse_ReadOnlySpan_String()
{
var sourceCode = @"
[StronglyTypedIdAttribute(typeof(string))]
public partial struct Test {}
";
var result = await GenerateFiles(sourceCode);
result.GeneratorResult.Diagnostics.Should().BeEmpty();
result.GeneratorResult.GeneratedTrees.Length.Should().Be(2);
var alc = new AssemblyLoadContext("test", isCollectible: true);
try
{
alc.LoadFromStream(new MemoryStream(result.Assembly));
foreach (var a in alc.Assemblies)
{
var type = a.GetType("Test");
var parse = type.GetMember("Parse").Length;
parse.Should().Be(2);
}
}
finally
{
alc.Unload();
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using Microsoft.JScript.Vsa;
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
internal class Call : AST{
internal AST func;
internal ASTList args;
private Object[] argValues;
private int outParameterCount;
internal bool isConstructor;
internal bool inBrackets;
private FunctionScope enclosingFunctionScope;
private bool alreadyPartiallyEvaluated;
private bool isAssignmentToDefaultIndexedProperty;
internal Call(Context context, AST func, ASTList args, bool inBrackets)
: base(context) {
this.func = func;
this.args = args == null ? new ASTList(context) : args;
this.argValues = null;
this.outParameterCount = 0;
for (int i = 0, n = this.args.count; i < n; i++)
if (this.args[i] is AddressOf)
this.outParameterCount++;
this.isConstructor = false;
this.inBrackets = inBrackets;
this.enclosingFunctionScope = null;
this.alreadyPartiallyEvaluated = false;
this.isAssignmentToDefaultIndexedProperty = false;
ScriptObject scope = Globals.ScopeStack.Peek();
while (!(scope is FunctionScope)){
scope = scope.GetParent();
if (scope == null)
return;
}
this.enclosingFunctionScope = (FunctionScope)scope;
}
private bool AllParamsAreMissing(){
for (int i = 0, n = this.args.count; i < n; i++){
AST p = this.args[i];
if (!(p is ConstantWrapper) || ((ConstantWrapper)p).value != System.Reflection.Missing.Value) return false;
}
return true;
}
private IReflect[] ArgIRs(){
int n = this.args.count;
IReflect[] argIRs = new IReflect[n];
for (int i = 0; i < n; i++){
AST arg = this.args[i];
IReflect ir = argIRs[i] = arg.InferType(null);
if (arg is AddressOf){
if (ir is ClassScope) ir = ((ClassScope)ir).GetBakedSuperType(); //this should change if ever JS can declare out params
argIRs[i] = Convert.ToType("&", Convert.ToType(ir));
}
}
return argIRs;
}
// the parser may invoke this function in error condition to change this call to a function declaration
internal bool CanBeFunctionDeclaration(){
bool canBeFunc = this.func is Lookup && this.outParameterCount == 0;
if (canBeFunc){
for (int i = 0, n = this.args.count; i < n; i++){
AST item = this.args[i];
canBeFunc = item is Lookup;
if (!canBeFunc) break;
}
}
return canBeFunc;
}
internal override void CheckIfOKToUseInSuperConstructorCall(){
this.func.CheckIfOKToUseInSuperConstructorCall();
}
internal override bool Delete(){
Object[] actual_arguments = this.args == null ? null : this.args.EvaluateAsArray();
int n = actual_arguments.Length;
Object ob = this.func.Evaluate();
if (ob == null) return true; //As per the standard, not backwards compatible with JS5
if (n == 0) return true;
Type obType = ob.GetType();
MethodInfo deleteOp = obType.GetMethod("op_Delete", BindingFlags.ExactBinding|BindingFlags.Public|BindingFlags.Static,
null, new Type[]{obType, Typeob.ArrayOfObject}, null);
if (deleteOp == null || (deleteOp.Attributes & MethodAttributes.SpecialName) == 0 || deleteOp.ReturnType != Typeob.Boolean)
return LateBinding.DeleteMember(ob, Convert.ToString(actual_arguments[n-1]));
else{
deleteOp = new JSMethodInfo(deleteOp);
return (bool)deleteOp.Invoke(null, new Object[]{ob, actual_arguments});
}
}
internal override Object Evaluate(){
if (this.outParameterCount > 0 && VsaEngine.executeForJSEE)
throw new JScriptException(JSError.RefParamsNonSupportedInDebugger);
LateBinding funcref = this.func.EvaluateAsLateBinding();
Object[] actual_arguments = this.args == null ? null : this.args.EvaluateAsArray();
Globals.CallContextStack.Push(new CallContext(this.context, funcref, actual_arguments));
try{
try{
Object result = null;
CallableExpression cexpr = this.func as CallableExpression;
if (cexpr == null || !(cexpr.expression is Call))
result = funcref.Call(actual_arguments, this.isConstructor, this.inBrackets, this.Engine);
else
result = LateBinding.CallValue(funcref.obj, actual_arguments, this.isConstructor, this.inBrackets, this.Engine,
cexpr.GetObject2(), JSBinder.ob, null, null);
if (this.outParameterCount > 0)
for (int i = 0, n = this.args.count; i < n; i++)
if (this.args[i] is AddressOf)
this.args[i].SetValue(actual_arguments[i]);
return result;
}catch(TargetInvocationException e){
JScriptException se;
if (e.InnerException is JScriptException){
se = (JScriptException)e.InnerException;
if (se.context == null)
if (((uint)se.Number) == (0x800A0000|(uint)JSError.ObjectExpected))
se.context = this.func.context;
else
se.context = this.context;
}else
se = new JScriptException(e.InnerException, this.context);
throw se;
}catch(JScriptException e){
if (e.context == null){
if (((uint)e.Number) == (0x800A0000|(uint)JSError.ObjectExpected))
e.context = this.func.context;
else
e.context = this.context;
}
throw e;
}catch(Exception e){
throw new JScriptException(e, this.context);
}catch{
throw new JScriptException(JSError.NonClsException, this.context);
}
}finally{
Globals.CallContextStack.Pop();
}
}
internal void EvaluateIndices(){
this.argValues = this.args.EvaluateAsArray();
}
// the parser may invoke this function in error condition to change this call to a function declaration
internal IdentifierLiteral GetName(){
Debug.Assert(this.func is Lookup && this.outParameterCount == 0);
return new IdentifierLiteral(this.func.ToString(), this.func.context);
}
// the parser may invoke this function in error condition to change this call to a function declaration
internal void GetParameters(ArrayList parameters){
Debug.Assert(this.func is Lookup && this.outParameterCount == 0);
for (int i = 0, n = this.args.count; i < n; i++){
AST item = this.args[i];
parameters.Add(new ParameterDeclaration(item.context, item.ToString(), null, null));
}
}
internal override IReflect InferType(JSField inference_target){
if (this.func is Binding)
return ((Binding)this.func).InferTypeOfCall(inference_target, this.isConstructor);
else if (this.func is ConstantWrapper){
Object value = ((ConstantWrapper)this.func).value;
if (value is Type || value is ClassScope || value is TypedArray)
return (IReflect)value;
}
return Typeob.Object;
}
private JSLocalField[] LocalsThatWereOutParameters(){
int n = this.outParameterCount;
if (n == 0) return null;
JSLocalField[] result = new JSLocalField[n];
int m = 0;
for (int i = 0; i < n; i++){
AST arg = this.args[i];
if (arg is AddressOf){
FieldInfo field = ((AddressOf)arg).GetField();
if (field is JSLocalField)
result[m++] = (JSLocalField)field;
}
}
return result;
}
internal void MakeDeletable(){
if (this.func is Binding){
Binding b = (Binding)this.func;
b.InvalidateBinding();
b.PartiallyEvaluateAsCallable();
b.ResolveLHValue();
}
}
internal override AST PartiallyEvaluate(){
if (this.alreadyPartiallyEvaluated)
return this;
this.alreadyPartiallyEvaluated = true;
if (this.inBrackets && this.AllParamsAreMissing()){
if (this.isConstructor) this.args.context.HandleError(JSError.TypeMismatch);
IReflect ir = ((TypeExpression)(new TypeExpression(this.func)).PartiallyEvaluate()).ToIReflect();
return new ConstantWrapper(new TypedArray(ir, this.args.count+1), this.context);
}
this.func = this.func.PartiallyEvaluateAsCallable();
this.args = (ASTList)this.args.PartiallyEvaluate();
IReflect[] argIRs = this.ArgIRs();
this.func.ResolveCall(this.args, argIRs, this.isConstructor, this.inBrackets);
if (!this.isConstructor && !this.inBrackets && this.func is Binding && this.args.count == 1){
Binding b = (Binding)this.func;
if (b.member is Type){
Type t = (Type)b.member;
ConstantWrapper arg0 = this.args[0] as ConstantWrapper;
if (arg0 != null){
try{
if (arg0.value == null || arg0.value is DBNull)
return this;
else if (arg0.isNumericLiteral && (t == Typeob.Decimal || t == Typeob.Int64 || t == Typeob.UInt64 || t == Typeob.Single))
return new ConstantWrapper(Convert.CoerceT(arg0.context.GetCode(), t, true), this.context);
else
return new ConstantWrapper(Convert.CoerceT(arg0.Evaluate(), t, true), this.context);
}catch{
arg0.context.HandleError(JSError.TypeMismatch);
}
}else{
if (!Binding.AssignmentCompatible(t, this.args[0], argIRs[0], false))
this.args[0].context.HandleError(JSError.ImpossibleConversion);
}
}else if (b.member is JSVariableField){
JSVariableField field = (JSVariableField)b.member;
if (field.IsLiteral){
if (field.value is ClassScope){
ClassScope csc = (ClassScope)field.value;
IReflect ut = csc.GetUnderlyingTypeIfEnum();
if (ut != null){
if (!Convert.IsPromotableTo(argIRs[0], ut) && !Convert.IsPromotableTo(ut, argIRs[0]) && (argIRs[0] != Typeob.String || ut == csc))
this.args[0].context.HandleError(JSError.ImpossibleConversion);
}else{
if (!Convert.IsPromotableTo(argIRs[0], csc) && !Convert.IsPromotableTo(csc, argIRs[0]))
this.args[0].context.HandleError(JSError.ImpossibleConversion);
}
}else if (field.value is TypedArray){
TypedArray ta = (TypedArray)field.value;
if (!Convert.IsPromotableTo(argIRs[0], ta) && !Convert.IsPromotableTo(ta, argIRs[0]))
this.args[0].context.HandleError(JSError.ImpossibleConversion);
}
}
}
}
return this;
}
internal override AST PartiallyEvaluateAsReference(){
this.func = this.func.PartiallyEvaluateAsCallable();
this.args = (ASTList)this.args.PartiallyEvaluate();
return this;
}
internal override void SetPartialValue(AST partial_value){
if (this.isConstructor)
this.context.HandleError(JSError.IllegalAssignment);
else if (this.func is Binding)
((Binding)this.func).SetPartialValue(this.args, this.ArgIRs(), partial_value, this.inBrackets);
else if (this.func is ThisLiteral)
((ThisLiteral)this.func).ResolveAssignmentToDefaultIndexedProperty(this.args, this.ArgIRs(), partial_value);
}
internal override void SetValue(Object value){
LateBinding prop = this.func.EvaluateAsLateBinding();
try{
prop.SetIndexedPropertyValue(this.argValues != null ? this.argValues : this.args.EvaluateAsArray(), value);
}catch(JScriptException e){
if (e.context == null)
e.context = this.func.context;
throw e;
}catch(Exception e){
throw new JScriptException(e, this.func.context);
}catch{
throw new JScriptException(JSError.NonClsException, this.context);
}
}
internal override void TranslateToIL(ILGenerator il, Type rtype){
if (this.context.document.debugOn)
il.Emit(OpCodes.Nop);
bool restoreLocals = true;
if (this.enclosingFunctionScope != null && this.enclosingFunctionScope.owner != null){
Binding b = this.func as Binding;
if (b != null && !this.enclosingFunctionScope.closuresMightEscape){
if (b.member is JSLocalField)
this.enclosingFunctionScope.owner.TranslateToILToSaveLocals(il);
else
restoreLocals = false;
}else
this.enclosingFunctionScope.owner.TranslateToILToSaveLocals(il);
}
this.func.TranslateToILCall(il, rtype, this.args, this.isConstructor, this.inBrackets);
if (restoreLocals && this.enclosingFunctionScope != null && this.enclosingFunctionScope.owner != null)
if (this.outParameterCount == 0)
this.enclosingFunctionScope.owner.TranslateToILToRestoreLocals(il);
else
this.enclosingFunctionScope.owner.TranslateToILToRestoreLocals(il, this.LocalsThatWereOutParameters());
}
internal CustomAttribute ToCustomAttribute(){
return new CustomAttribute(this.context, this.func, this.args);
}
internal override void TranslateToILDelete(ILGenerator il, Type rtype){
IReflect ir = this.func.InferType(null);
Type obType = Convert.ToType(ir);
this.func.TranslateToIL(il, obType);
this.args.TranslateToIL(il, Typeob.ArrayOfObject);
if (this.func is Binding){
MethodInfo deleteOp;
if (ir is ClassScope)
deleteOp = ((ClassScope)ir).owner.deleteOpMethod;
else
deleteOp = ir.GetMethod("op_Delete", BindingFlags.ExactBinding|BindingFlags.Public|BindingFlags.Static,
null, new Type[]{obType, Typeob.ArrayOfObject}, null);
if (deleteOp != null && (deleteOp.Attributes & MethodAttributes.SpecialName) != 0 && deleteOp.ReturnType == Typeob.Boolean){
il.Emit(OpCodes.Call, deleteOp);
Convert.Emit(this, il, Typeob.Boolean, rtype);
return;
}
}
ConstantWrapper.TranslateToILInt(il, this.args.count-1);
il.Emit(OpCodes.Ldelem_Ref);
Convert.Emit(this, il, Typeob.Object, Typeob.String);
il.Emit(OpCodes.Call, CompilerGlobals.deleteMemberMethod);
Convert.Emit(this, il, Typeob.Boolean, rtype);
}
internal override void TranslateToILInitializer(ILGenerator il){
this.func.TranslateToILInitializer(il);
this.args.TranslateToILInitializer(il);
}
internal override void TranslateToILPreSet(ILGenerator il){
this.func.TranslateToILPreSet(il, this.args);
}
internal override void TranslateToILPreSet(ILGenerator il, ASTList args){
this.isAssignmentToDefaultIndexedProperty = true;
base.TranslateToILPreSet(il, args);
}
internal override void TranslateToILPreSetPlusGet(ILGenerator il){
this.func.TranslateToILPreSetPlusGet(il, this.args, this.inBrackets);
}
internal override void TranslateToILSet(ILGenerator il, AST rhvalue){
if (this.isAssignmentToDefaultIndexedProperty)
base.TranslateToILSet(il, rhvalue);
else
this.func.TranslateToILSet(il, rhvalue);
}
}
}
| |
// 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 Microsoft.Xunit.Performance;
using Xunit;
using System.Net;
using static System.Buffers.Binary.BinaryPrimitives;
using static System.TestHelpers;
namespace System.Buffers.Binary.Tests
{
public class BinaryReadAndWriteTests
{
private const int InnerCount = 100000;
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructAndReverseBE()
{
Span<byte> spanBE = TestHelpers.GetSpanBE();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = ReadMachineEndian<TestHelpers.TestStructExplicit>(spanBE);
if (BitConverter.IsLittleEndian)
{
readStruct.S0 = ReverseEndianness(readStruct.S0);
readStruct.I0 = ReverseEndianness(readStruct.I0);
readStruct.L0 = ReverseEndianness(readStruct.L0);
readStruct.US0 = ReverseEndianness(readStruct.US0);
readStruct.UI0 = ReverseEndianness(readStruct.UI0);
readStruct.UL0 = ReverseEndianness(readStruct.UL0);
readStruct.S1 = ReverseEndianness(readStruct.S1);
readStruct.I1 = ReverseEndianness(readStruct.I1);
readStruct.L1 = ReverseEndianness(readStruct.L1);
readStruct.US1 = ReverseEndianness(readStruct.US1);
readStruct.UI1 = ReverseEndianness(readStruct.UI1);
readStruct.UL1 = ReverseEndianness(readStruct.UL1);
}
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructAndReverseLE()
{
Span<byte> spanLE = TestHelpers.GetSpanLE();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = ReadMachineEndian<TestHelpers.TestStructExplicit>(spanLE);
if (!BitConverter.IsLittleEndian)
{
readStruct.S0 = ReverseEndianness(readStruct.S0);
readStruct.I0 = ReverseEndianness(readStruct.I0);
readStruct.L0 = ReverseEndianness(readStruct.L0);
readStruct.US0 = ReverseEndianness(readStruct.US0);
readStruct.UI0 = ReverseEndianness(readStruct.UI0);
readStruct.UL0 = ReverseEndianness(readStruct.UL0);
readStruct.S1 = ReverseEndianness(readStruct.S1);
readStruct.I1 = ReverseEndianness(readStruct.I1);
readStruct.L1 = ReverseEndianness(readStruct.L1);
readStruct.US1 = ReverseEndianness(readStruct.US1);
readStruct.UI1 = ReverseEndianness(readStruct.UI1);
readStruct.UL1 = ReverseEndianness(readStruct.UL1);
}
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructFieldByFieldBE()
{
Span<byte> spanBE = TestHelpers.GetSpanBE();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = new TestHelpers.TestStructExplicit
{
S0 = ReadInt16BigEndian(spanBE),
I0 = ReadInt32BigEndian(spanBE.Slice(2)),
L0 = ReadInt64BigEndian(spanBE.Slice(6)),
US0 = ReadUInt16BigEndian(spanBE.Slice(14)),
UI0 = ReadUInt32BigEndian(spanBE.Slice(16)),
UL0 = ReadUInt64BigEndian(spanBE.Slice(20)),
S1 = ReadInt16BigEndian(spanBE.Slice(28)),
I1 = ReadInt32BigEndian(spanBE.Slice(30)),
L1 = ReadInt64BigEndian(spanBE.Slice(34)),
US1 = ReadUInt16BigEndian(spanBE.Slice(42)),
UI1 = ReadUInt32BigEndian(spanBE.Slice(44)),
UL1 = ReadUInt64BigEndian(spanBE.Slice(48))
};
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructFieldByFieldLE()
{
Span<byte> spanLE = TestHelpers.GetSpanLE();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = new TestHelpers.TestStructExplicit
{
S0 = ReadInt16LittleEndian(spanLE),
I0 = ReadInt32LittleEndian(spanLE.Slice(2)),
L0 = ReadInt64LittleEndian(spanLE.Slice(6)),
US0 = ReadUInt16LittleEndian(spanLE.Slice(14)),
UI0 = ReadUInt32LittleEndian(spanLE.Slice(16)),
UL0 = ReadUInt64LittleEndian(spanLE.Slice(20)),
S1 = ReadInt16LittleEndian(spanLE.Slice(28)),
I1 = ReadInt32LittleEndian(spanLE.Slice(30)),
L1 = ReadInt64LittleEndian(spanLE.Slice(34)),
US1 = ReadUInt16LittleEndian(spanLE.Slice(42)),
UI1 = ReadUInt32LittleEndian(spanLE.Slice(44)),
UL1 = ReadUInt64LittleEndian(spanLE.Slice(48))
};
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructFieldByFieldUsingBitConverterLE()
{
Span<byte> spanLE = TestHelpers.GetSpanLE();
byte[] arrayLE = spanLE.ToArray();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = new TestHelpers.TestStructExplicit
{
S0 = BitConverter.ToInt16(arrayLE, 0),
I0 = BitConverter.ToInt32(arrayLE, 2),
L0 = BitConverter.ToInt64(arrayLE, 6),
US0 = BitConverter.ToUInt16(arrayLE, 14),
UI0 = BitConverter.ToUInt32(arrayLE, 16),
UL0 = BitConverter.ToUInt64(arrayLE, 20),
S1 = BitConverter.ToInt16(arrayLE, 28),
I1 = BitConverter.ToInt32(arrayLE, 30),
L1 = BitConverter.ToInt64(arrayLE, 34),
US1 = BitConverter.ToUInt16(arrayLE, 42),
UI1 = BitConverter.ToUInt32(arrayLE, 44),
UL1 = BitConverter.ToUInt64(arrayLE, 48),
};
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void ReadStructFieldByFieldUsingBitConverterBE()
{
Span<byte> spanBE = TestHelpers.GetSpanBE();
byte[] arrayBE = spanBE.ToArray();
var readStruct = new TestHelpers.TestStructExplicit();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
readStruct = new TestHelpers.TestStructExplicit
{
S0 = BitConverter.ToInt16(arrayBE, 0),
I0 = BitConverter.ToInt32(arrayBE, 2),
L0 = BitConverter.ToInt64(arrayBE, 6),
US0 = BitConverter.ToUInt16(arrayBE, 14),
UI0 = BitConverter.ToUInt32(arrayBE, 16),
UL0 = BitConverter.ToUInt64(arrayBE, 20),
S1 = BitConverter.ToInt16(arrayBE, 28),
I1 = BitConverter.ToInt32(arrayBE, 30),
L1 = BitConverter.ToInt64(arrayBE, 34),
US1 = BitConverter.ToUInt16(arrayBE, 42),
UI1 = BitConverter.ToUInt32(arrayBE, 44),
UL1 = BitConverter.ToUInt64(arrayBE, 48),
};
if (BitConverter.IsLittleEndian)
{
readStruct.S0 = ReverseEndianness(readStruct.S0);
readStruct.I0 = ReverseEndianness(readStruct.I0);
readStruct.L0 = ReverseEndianness(readStruct.L0);
readStruct.US0 = ReverseEndianness(readStruct.US0);
readStruct.UI0 = ReverseEndianness(readStruct.UI0);
readStruct.UL0 = ReverseEndianness(readStruct.UL0);
readStruct.S1 = ReverseEndianness(readStruct.S1);
readStruct.I1 = ReverseEndianness(readStruct.I1);
readStruct.L1 = ReverseEndianness(readStruct.L1);
readStruct.US1 = ReverseEndianness(readStruct.US1);
readStruct.UI1 = ReverseEndianness(readStruct.UI1);
readStruct.UL1 = ReverseEndianness(readStruct.UL1);
}
}
}
}
Assert.Equal(TestHelpers.testExplicitStruct, readStruct);
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void MeasureReverseEndianness()
{
var myArray = new int[1000];
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
for (int j = 0; j < myArray.Length; j++)
{
myArray[j] = ReverseEndianness(myArray[j]);
}
}
}
}
}
[Benchmark(InnerIterationCount = InnerCount)]
private static void MeasureReverseUsingNtoH()
{
var myArray = new int[1000];
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
for (int j = 0; j < myArray.Length; j++)
{
myArray[j] = IPAddress.NetworkToHostOrder(myArray[j]);
}
}
}
}
}
}
}
| |
//Sony Computer Entertainment Confidential
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Sce.Atf.Adaptation;
using Sce.Atf.Controls;
namespace Sce.Atf.Applications
{
/// <summary>
/// Class to list assets in a tree control
/// </summary>
[Export(typeof(AssetLister))]
[Export(typeof(IInitializable))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class AssetLister : TreeControlEditor, IControlHostClient, ICommandClient, IInitializable, IPartImportsSatisfiedNotification
{
[ImportingConstructor]
public AssetLister(
IControlHostService controlHostService,
IContextService contextService,
ICommandService commandService,
IFileDialogService fileDialogService)
{
m_controlHostService = controlHostService;
m_contextService = contextService;
m_commandService = commandService;
m_fileDialogService = fileDialogService;
m_treeControl = new TreeControl();
m_treeControl.Dock = DockStyle.Fill;
m_treeControl.AllowDrop = true;
m_treeControl.SelectionMode = SelectionMode.MultiExtended;
m_treeControl.ImageList = ResourceUtil.GetImageList16();
m_treeControl.StateImageList = ResourceUtil.GetImageList16();
m_treeControl.DragOver += new DragEventHandler(treeControl_DragOver);
m_treeControl.DragDrop += new DragEventHandler(treeControl_DragDrop);
m_treeControl.MouseDown += new MouseEventHandler(treeControl_MouseDown);
m_treeControl.MouseUp += new MouseEventHandler(treeControl_MouseUp);
m_treeControl.NodeLabelEdited += new EventHandler<TreeControl.NodeEventArgs>(treeControl_NodeLabelEdited);
m_listView = new ListView();
m_listView.View = View.Details;
m_listView.Dock = DockStyle.Fill;
m_listView.AllowDrop = true;
m_listView.LabelEdit = false;
m_listView.MouseDown += new MouseEventHandler(thumbnailControl_MouseDown);
m_listView.MouseUp += new MouseEventHandler(thumbnailControl_MouseUp);
m_listView.MouseMove += new MouseEventHandler(thumbnailControl_MouseMove);
m_listView.MouseLeave += new EventHandler(thumbnailControl_MouseLeave);
m_listView.DoubleClick += new EventHandler(thumbnailControl_DoubleClick);
m_listView.DragOver += new DragEventHandler(thumbnailControl_DragOver);
m_listView.DragDrop += new DragEventHandler(thumbnailControl_DragDrop);
m_thumbnailControl = new ThumbnailControl();
m_thumbnailControl.IndicatorImageList = ResourceUtil.GetImageList16();
m_thumbnailControl.Dock = DockStyle.Fill;
m_thumbnailControl.AllowDrop = true;
m_thumbnailControl.BackColor = SystemColors.Window;
m_thumbnailControl.SelectionChanged += new EventHandler(thumbnailControl_SelectionChanged);
m_thumbnailControl.MouseDown += new MouseEventHandler(thumbnailControl_MouseDown);
m_thumbnailControl.MouseMove += new MouseEventHandler(thumbnailControl_MouseMove);
m_thumbnailControl.MouseUp += new MouseEventHandler(thumbnailControl_MouseUp);
m_thumbnailControl.MouseLeave += new EventHandler(thumbnailControl_MouseLeave);
m_thumbnailControl.DoubleClick += new EventHandler(thumbnailControl_DoubleClick);
m_thumbnailControl.DragOver += new DragEventHandler(thumbnailControl_DragOver);
m_thumbnailControl.DragDrop += new DragEventHandler(thumbnailControl_DragDrop);
m_splitContainer = new SplitContainer();
m_splitContainer.Name = "Asset";
m_splitContainer.Orientation = Orientation.Vertical;
m_splitContainer.Panel1.Controls.Add(m_treeControl);
m_splitContainer.Panel2.Controls.Add(m_thumbnailControl);
m_splitContainer.Panel2.Controls.Add(m_listView);
m_listView.Hide();
m_selection.Changed += new EventHandler(selection_Changed);
m_treeControlAdapter = new TreeControlAdapter(m_treeControl);
m_assetFolderTreeView = new AssetFolderTreeView(this);
m_treeControlAdapter.TreeView = m_assetFolderTreeView;
m_listViewAdaptor = new ListViewAdaptor(m_listView);
m_assetItemListView = new AssetItemListView(this);
}
private void Contexts_ActiveItemChanged(object sender, EventArgs e)
{
}
private IControlHostService m_controlHostService;
private IContextService m_contextService;
private ICommandService m_commandService;
private IFileDialogService m_fileDialogService;
[Import(AllowDefault = true, AllowRecomposition = true)]
public ISourceControlService m_sourceControlService = null;
[Import(AllowDefault = true)]
private ThumbnailService m_thumbnailService = null;
[Import(AllowDefault = true)]
private ISettingsService m_settingsService = null;
[Import(AllowDefault = true)]
private IStatusService m_statusService = null;
[ImportMany(AllowRecomposition = true)]
private IEnumerable<IContextMenuCommandProvider> m_contextMenuCommandProviders = null;
[ImportMany(AllowRecomposition = true)]
private IEnumerable<IDataObjectConverter> m_dataObjectConverters = null;
#region IInitializable Members
/// <summary>
/// Initialize instance
/// </summary>
void IInitializable.Initialize()
{
m_contextService.Contexts.ActiveItemChanged += new EventHandler(Contexts_ActiveItemChanged);
m_thumbnailService.ThumbnailReady += new EventHandler<ThumbnailReadyEventArgs>(ThumbnailManager_ThumbnailReady);
m_controlHostService.RegisterControl(m_splitContainer, "Assets", "Views asset list", m_controlGroup, this);
RegisterCommands(m_commandService);
RegisterSettings();
}
#endregion
#region IPartImportsSatisfiedNotification Members
void IPartImportsSatisfiedNotification.OnImportsSatisfied()
{
// TODO unhook using old reference
if (m_sourceControlService != null)
{
m_sourceControlService.StatusChanged +=
new EventHandler<SourceControlEventArgs>(sourceControl_StatusChanged);
}
}
#endregion
/// <summary>
/// Gets or sets the asset folder
/// </summary>
public IAssetFolder AssetFolder
{
get { return m_rootAssetFolder; }
set
{
if (m_rootAssetFolder != value)
{
m_rootAssetFolder = value;
TreeView = new AssetFolderTreeView(this);
}
}
}
/// <summary>
/// Gets or sets the control group docking location; set this before initialization
/// </summary>
public StandardControlGroup ControlGroup
{
get { return m_controlGroup; }
set { m_controlGroup = value; }
}
/// <summary>
/// Gets the tree control displaying the asset folder hierarchy</summary>
public TreeControl TreeControl
{
get { return m_treeControl; }
}
/// <summary>
/// Gets the ListView displaying the details view of assets in the selected folder
/// </summary>
public ListView ListView
{
get { return m_listView; }
}
/// <summary>
/// Gets the ThumbnailControl displaying the thumbnail view of assets in the selected folder
/// </summary>
public ThumbnailControl ThumbnailControl
{
get { return m_thumbnailControl; }
}
#region IControlHostClient Members
/// <summary>
/// Activate control
/// </summary>
/// <param name="control">Control</param>
public void Activate(Control control)
{
}
/// <summary>
/// Close control
/// </summary>
/// <param name="control">Control</param>
/// <returns></returns>
public bool Close(Control control)
{
return true;
}
#endregion
/// <summary>
/// Refreshes the tree control at the root</summary>
/// <remarks>Call this method if the asset folder has been reloaded or synched from
/// version control</remarks>
public void Refresh()
{
// if AssetLister has been initialized, refresh tree control at the root
if (m_treeControl != null)
{
m_treeControlAdapter.Refresh(m_rootAssetFolder);
RefreshRightPane();
}
}
#region Event Handlers
/// <summary>
/// Called after selection changed
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event args</param>
void selection_Changed(object sender, EventArgs e)
{
Selection selection = (Selection)sender;
List<Path<object>> newSelection = selection.LastSelected as List<Path<object>>;
if (newSelection != null && newSelection.Count > 0)
{
IAssetFolder assetFolder = newSelection[0].Last as IAssetFolder;
if (assetFolder != null)
{
SetCurrentAssetFolder(assetFolder);
}
}
}
private void treeControl_MouseDown(object sender, MouseEventArgs e)
{
m_lastHit = m_treeControlAdapter.GetItemAt(new Point(e.X, e.Y));
}
private void treeControl_MouseUp(object sender, MouseEventArgs e)
{
Point clientPoint = new Point(e.X, e.Y);
m_lastHit = m_treeControlAdapter.GetItemAt(clientPoint);
OnMouseUp(e);
}
/// <summary>
/// Called on mouse up event
/// </summary>
/// <param name="e">Event args</param>
protected virtual void OnMouseUp(MouseEventArgs e) // for tree control on the left pane
{
if (e.Button == MouseButtons.Right)
{
List<object> commands = ApplicationUtil.GetPopupCommandTags(m_lastHit, m_contextMenuCommandProviders);
Point screenPoint = m_treeControl.PointToScreen(new Point(e.X, e.Y));
m_commandService.RunContextMenu(commands, screenPoint);
}
}
private void treeControl_DragOver(object sender, DragEventArgs e)
{
Point clientPoint = m_treeControl.PointToClient(new Point(e.X, e.Y));
m_lastHit = m_treeControlAdapter.GetItemAt(clientPoint);
OnDragOver(e);
}
/// <summary>
/// Called on dragging mouse over event
/// </summary>
/// <param name="e">Event args</param>
protected virtual void OnDragOver(DragEventArgs e)
{
e.Effect = DragDropEffects.None;
IInstancingContext instancingContext = m_rootAssetFolder.As<IInstancingContext>();
IEnumerable converted = ApplicationUtil.Convert(e.Data, instancingContext, m_dataObjectConverters);
if (converted != null)
e.Effect = DragDropEffects.Move;
}
private void treeControl_DragDrop(object sender, DragEventArgs e)
{
Point clientPoint = m_treeControl.PointToClient(new Point(e.X, e.Y));
m_lastHit = m_treeControlAdapter.GetItemAt(clientPoint);
OnDragDrop(e);
}
/// <summary>
/// Called on drag and drop event
/// </summary>
/// <param name="e">Event args</param>
protected virtual void OnDragDrop(DragEventArgs e)
{
IInstancingContext instancingContext = m_rootAssetFolder.As<IInstancingContext>();
IEnumerable<object> converted = ApplicationUtil.Convert(e.Data, instancingContext, m_dataObjectConverters);
ApplicationUtil.Drop(converted, instancingContext, m_statusService);
}
private void treeControl_NodeLabelEdited(object sender, TreeControl.NodeEventArgs e)
{
OnNodeLabelEdited(e);
}
/// <summary>
/// Called on label edited event
/// </summary>
/// <param name="e">Event args</param>
protected virtual void OnNodeLabelEdited(TreeControl.NodeEventArgs e)
{
INameable nameable = e.Node.Tag.As<INameable>();
if (nameable != null)
{
ITransactionContext transactionContext = Adapters.As<ITransactionContext>(m_treeControlAdapter.TreeView);
transactionContext.DoTransaction(
delegate
{
nameable.Name = e.Node.Label;
},
Localizer.Localize("Edit Label"));
}
}
private void thumbnailControl_MouseDown(object sender, MouseEventArgs e)
{
Point point = new Point(e.X, e.Y);
if (e.Button == MouseButtons.Left)
{
m_hitPoint = point;
}
else if (e.Button == MouseButtons.Right)
{
IResource asset = null;
if (m_thumbnailControl.Visible)
asset = SelectedAsset(m_thumbnailControl, point);
else
asset = SelectedAsset(m_listView, point);
if (asset != null)
{
if (m_thumbnailControl.Visible)
{
ThumbnailControlItem item = m_thumbnailControl.PickThumbnail(point);
Keys modifiers = Control.ModifierKeys;
if ((modifiers & Keys.Control) != 0)
m_thumbnailControl.Selection.Toggle(item);
else if ((modifiers & Keys.Shift) != 0)
m_thumbnailControl.Selection.Add(item);
else
m_thumbnailControl.Selection.Set(item);
m_thumbnailControl.Invalidate();
}
IResource assetObj = asset as IResource;
if (assetObj != null)
{
ISelectionContext selectionContext = m_rootAssetFolder.As<ISelectionContext>();
selectionContext.Selection.Set(assetObj);
}
}
}
}
private void thumbnailControl_MouseMove(object sender, MouseEventArgs e)
{
if (!m_dragging && e.Button == MouseButtons.Left)
{
Size dragSize = SystemInformation.DragSize;
if (Math.Abs(m_hitPoint.X - e.X) >= dragSize.Width ||
Math.Abs(m_hitPoint.Y - e.Y) >= dragSize.Height)
{ /*ATF3
m_dragging = true;
Path<DomObject> assetPath = null;
bool dragSelection = false;
List<Path<DomObject>> assetPaths = new List<Path<DomObject>>();
IResource asset = null;
if (m_thumbnailControl.Visible)
asset = SelectedAsset(m_thumbnailControl, new Point(e.X, e.Y));
else
asset = SelectedAsset(m_listControl, new Point(e.X, e.Y));
if (asset != null)
{
assetPath = new Path<DomObject>(asset.InternalObject.GetPath());
assetPaths.Add(assetPath);
// Determine if we need to multi drag
foreach (Path<DomObject> path in Context.Selection)
{
if (path.Last == assetPath.Last)
{
dragSelection = true;
break;
}
}
if (dragSelection)
{
foreach (Path<DomObject> path in Context.Selection)
{
if (path.Last != assetPath.Last)
{
if (path.Last.CanCreateInterface<IResource>())
{
assetPaths.Add(path);
}
}
}
}
else
{
Context.Selection.Select(assetPath, Control.ModifierKeys);
}
if (m_thumbnailControl.Visible)
m_thumbnailControl.DoDragDrop(assetPaths.ToArray(), DragDropEffects.All | DragDropEffects.Link);
else
m_listControl.DoDragDrop(assetPaths.ToArray(), DragDropEffects.All | DragDropEffects.Link);
}
*/
}
}
}
private void thumbnailControl_MouseUp(object sender, MouseEventArgs e)
{
IResource asset = null;
if (e.Button == MouseButtons.Right)
{
Point screenPoint;
Point clientPoint = new Point(e.X, e.Y);
if (m_thumbnailControl.Visible)
{
asset = SelectedAsset(m_thumbnailControl, clientPoint);
screenPoint = m_thumbnailControl.PointToScreen(clientPoint);
}
else
{
asset = SelectedAsset(m_listView, clientPoint);
screenPoint = m_listView.PointToScreen(clientPoint);
}
if (asset != null)
{
IResource assetObj = asset as IResource;
if (assetObj != null)
{
List<object> commands = ApplicationUtil.GetPopupCommandTags(assetObj, m_contextMenuCommandProviders);
commands.Add(Command.ReloadAsset);
commands.Add(Command.UnloadAssets);
commands.Add(Command.DetailsView);
commands.Add(Command.ThumbnailView);
commands.Add(Command.AddExistingAsset);
m_commandService.RunContextMenu(commands, screenPoint);
}
}
else
{
List<object> commands = new List<object>();
commands.Add(Command.ReloadAsset);
commands.Add(Command.UnloadAssets);
commands.Add(Command.DetailsView);
commands.Add(Command.ThumbnailView);
commands.Add(Command.AddExistingAsset);
m_commandService.RunContextMenu(commands, screenPoint);
}
}
m_dragging = false;
}
private void thumbnailControl_MouseLeave(object sender, EventArgs e)
{
m_dragging = false;
}
private void thumbnailControl_DoubleClick(object sender, EventArgs e)
{
MouseEventArgs args = e as MouseEventArgs;
IResource asset = null;
if (m_thumbnailControl.Visible)
asset = SelectedAsset(m_thumbnailControl, new Point(args.X, args.Y));
else
asset = SelectedAsset(m_listView, new Point(0, 0));
m_assetDoubleClicked = asset;
if (m_modal)
{
// close the form dialog when double clicked on
Control control = m_listView;
if (m_thumbnailControl.Visible)
control = m_thumbnailControl;
if (control != null && control.Parent != null &&
control.Parent.Parent != null && control.Parent.Parent.Parent != null)
{
Form dialog = control.Parent.Parent.Parent as Form;
if (dialog != null)
dialog.DialogResult = DialogResult.OK;
}
return;
}
/*ATF3 if (asset != null)
{
Context.Selection.Select(
new Path<DomObject>(asset.InternalObject.GetPath()),
Control.ModifierKeys);
foreach (IDomDocumentEditor editor in Plugins.GetPlugins<IDomDocumentEditor>())
{
if (asset.Source != null)
{
IDomDocument document = editor.OpenDocument(asset.Source.Collection, false);
if (document != null)
break;
}
}
}*/
}
private void thumbnailControl_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.None;
m_lastHit = m_currentAssetFolder;
IInstancingContext instancingContext = m_rootAssetFolder.As<IInstancingContext>();
IEnumerable converted = ApplicationUtil.Convert(e.Data, instancingContext, m_dataObjectConverters);
if (converted != null)
e.Effect = DragDropEffects.Move;
}
private void thumbnailControl_DragDrop(object sender, DragEventArgs e)
{
m_lastHit = m_currentAssetFolder;
IInstancingContext instancingContext = m_rootAssetFolder.As<IInstancingContext>();
IEnumerable<object> converted = ApplicationUtil.Convert(e.Data, instancingContext, m_dataObjectConverters);
ApplicationUtil.Drop(converted, instancingContext, m_statusService);
}
private IResource SelectedAsset(Control control, Point point)
{
IResource asset = null;
ThumbnailControl thumbnailControl = control as ThumbnailControl;
if (thumbnailControl != null)
{
ThumbnailControlItem item = thumbnailControl.PickThumbnail(point);
if (item != null)
{
asset = item.Tag as IResource;
}
}
else
{
ListView fileListView = control as ListView;
if ((fileListView != null) && (fileListView.SelectedItems.Count > 0))
{
ListViewItem listItem = fileListView.SelectedItems[0];
asset = listItem.Tag as IResource;
}
}
return asset;
}
private void thumbnailControl_SelectionChanged(object sender, EventArgs e)
{
/*ATF3 if (!m_selecting && Context != null)
{
try
{
m_selecting = true;
List<Path<DomObject>> newSelection = new List<Path<DomObject>>();
foreach (ThumbnailControlItem item in m_thumbnailControl.Selection)
{
IResource asset = item.Tag as IResource;
if (asset != null)
newSelection.Add(new Path<DomObject>(asset.InternalObject.GetPath()));
}
Context.Selection.Set(newSelection);
}
finally
{
m_selecting = false;
}
}*/
}
private void ThumbnailManager_ThumbnailReady(object sender, ThumbnailReadyEventArgs e)
{
// get rid of temporary thumbnail
IResource asset = e.Resource;
if (m_requestedThumbs.Contains(asset))
{
// Make sure that asset is still valid
//DomCollection assetCollection = asset.InternalObject.Collection;
//if (assetCollection != null &&
// assetCollection.Repository != null)
{
ThumbnailControlItem item = GetItem(asset);
if (item == null)
{
item = NewItem(asset, e.Image);
m_thumbnailControl.Items.Add(item);
}
else
item.Image = e.Image;
}
m_requestedThumbs.Remove(asset);
}
}
private void sourceControl_StatusChanged(object sender, SourceControlEventArgs e)
{
// Find the item
foreach (ThumbnailControlItem item in m_thumbnailControl.Items)
{
IResource resource = item.Tag as IResource;
if (resource != null && resource.Uri == e.Uri)
{
item.Indicator = SetSourceControlIndicator(resource.Uri, e.Status);
RefreshThumbnail(resource);
break;
}
}
foreach (ListViewItem item in m_listView.Items)
{
IResource resource = item.Tag as IResource;
if (resource != null && resource.Uri == e.Uri)
{
//item.Indicator = SetSourceControlIndicator(src.FilePath, e.Status);
break;
}
}
//if (m_listControl.Visible)
// m_listViewAdaptor.Refresh();
}
#endregion
#region ICommandClient
/// <summary>
/// Checks whether the client can do the command</summary>
/// <param name="commandTag">Command to be done</param>
/// <returns>True iff client can do the command</returns>
public bool CanDoCommand(object commandTag)
{
if (m_rootAssetFolder == null)// in case there is no currently opened document
return false;
if (commandTag is Command)
{
switch ((Command)commandTag)
{
/*ATF3case Command.ReloadAsset:
{
foreach (Path<DomObject> path in LogicalSelection)
{
IResource asset = path.Last.CreateInterface<IResource>();
if (asset != null)
{
return true;
}
}
return false;
}
*/
case Command.UnloadAssets:
return true;
case Command.DetailsView:
if (m_listView.Visible)
return false;
else return true;
case Command.ThumbnailView:
if (m_thumbnailControl.Visible)
return false;
else return true;
case Command.AddExistingAsset:
return m_currentAssetFolder != null;
default:
return false;
}
}
return false;
}
/// <summary>
/// Does the command</summary>
/// <param name="commandTag">Command to be done</param>
public void DoCommand(object commandTag)
{
if (commandTag is Command)
{
switch ((Command)commandTag)
{
/*ATF3 case Command.ReloadAsset:
{
foreach (Path<DomObject> path in LogicalSelection)
{
IResource asset = path.Last.CreateInterface<IResource>();
if (asset != null)
{
ReloadAsset(asset);
}
}
}
break;
*/
case Command.UnloadAssets:
{
//UnloadUnusedAssets(m_rootAssetFolder);
}
break;
case Command.DetailsView:
{
m_thumbnailControl.Hide();
m_listViewAdaptor.ListView = m_assetItemListView;
m_listView.Show();
RefreshRightPane();
}
break;
case Command.ThumbnailView:
{
m_listView.Hide();
m_listViewAdaptor.ListView = null;
m_thumbnailControl.Show();
RefreshRightPane();
}
break;
case Command.AddExistingAsset:
AddExistingAsset();
break;
}
}
}
/// <summary>
/// Updates command state for given command
/// </summary>
/// <param name="commandTag">Command</param>
/// <param name="state">Command state to update</param>
public void UpdateCommand(object commandTag, CommandState state)
{
//if (commandTag is Command)
//{
// switch ((Command)commandTag)
// {
// case Command.ReloadAsset:
// break;
// }
//}
}
#endregion
private void AddExistingAsset()
{
string path = null;
DialogResult result = m_fileDialogService.OpenFileName(ref path, Localizer.Localize("All Files") + " (*.*)|*.*");
if (result == DialogResult.OK)
{
IAssetFolder parent = m_currentAssetFolder;
IResource asset = parent.CreateAsset();
asset.Uri = new Uri(path);
//OnObjectInserted(new ItemInsertedEventArgs<object>(parent.Assets.Count - 1, asset, parent));
}
}
private void UnloadAllAssets(IAssetFolder folder)
{
/*foreach (IResource asset in folder.Assets)
asset.Unload();
foreach (IAssetFolder subFolder in folder.Folders)
UnloadAllAssets(subFolder);*/
}
private void SetCurrentAssetFolder(IAssetFolder assetFolder)
{
if (m_currentAssetFolder != assetFolder)
{
m_currentAssetFolder = assetFolder;
m_requestedThumbs.Clear();
RefreshRightPane();
}
}
internal IAssetFolder CurrentAssetFolder
{
get { return m_currentAssetFolder; }
}
private void RefreshRightPane()
{
if (m_currentAssetFolder != null)
{
m_thumbnailControl.Items.Clear();
// It's much more efficient to call the source control service with many uris at once.
// Doing this will cache the results for the calls to RightPaneAddItem().
if (m_sourceControlService != null)
{
bool folderProcessed = false;
if (m_currentAssetFolder.Assets.Count > 0)
{
IResource asset = m_currentAssetFolder.Assets[0];
folderProcessed = m_sourceControlService.GetFolderStatus(asset.Uri);
}
if (!folderProcessed)
{
List<Uri> uris = new List<Uri>();
foreach (IResource resource in m_currentAssetFolder.Assets)
{
uris.Add(resource.Uri);
}
m_sourceControlService.GetStatus(uris);
}
}
foreach (IResource resource in m_currentAssetFolder.Assets)
{
RightPaneAddItem(resource);
}
if (m_listView.Visible)
m_listViewAdaptor.Load();
}
}
private void ReloadAsset(IResource resource)
{
/*ATF3 DomUri src = asset.Uri;
if (src.ResolvedObject != null)
{
DomCollection collection = src.ResolvedObject.Collection;
collection.Reload();
}*/
}
private void RightPaneAddItem(IResource resource)
{
if (m_thumbnailControl.Visible)
{
m_requestedThumbs.Add(resource);
m_thumbnailService.ResolveThumbnail(resource);
string assetPath = resource.GetPathName();
string assetFileName = Path.GetFileName(assetPath);
Icon shellIcon = FileIconUtil.GetFileIcon(assetFileName, FileIconUtil.IconSize.Large, false);
Bitmap tempThumbnail = shellIcon.ToBitmap();
ThumbnailControlItem item = GetItem(resource);
if (item == null)
{
item = NewItem(resource, tempThumbnail);
m_thumbnailControl.Items.Add(item);
}
else
{
item.Image = tempThumbnail;
}
}
else if (m_listView.Visible)
{
string assetPath = resource.Uri.OriginalString;
string indicator = null;
if (m_sourceControlService != null)
{
SourceControlStatus status = m_sourceControlService.GetStatus(resource.Uri);
indicator = SetSourceControlIndicator(resource.Uri, status);
}
string path = resource.GetPathName();
}
}
private void RefreshThumbnail(IResource asset)
{
m_requestedThumbs.Add(asset);
m_thumbnailService.ResolveThumbnail(asset);
string assetPath = asset.GetPathName();
string assetFileName = Path.GetFileName(assetPath);
Icon shellIcon = FileIconUtil.GetFileIcon(assetFileName, FileIconUtil.IconSize.Large, false);
Bitmap tempThumbnail = shellIcon.ToBitmap();
ThumbnailControlItem item = GetItem(asset);
if (item == null)
{
item = NewItem(asset, tempThumbnail);
m_thumbnailControl.Items.Add(item);
}
else
{
item.Image = tempThumbnail;
}
}
private ThumbnailControlItem GetItem(IResource asset)
{
foreach (ThumbnailControlItem item in m_thumbnailControl.Items)
{
IResource assetTag = item.Tag as IResource;
if (assetTag == asset)
return item;
}
return null;
}
private ThumbnailControlItem NewItem(IResource resource, Image image)
{
ThumbnailControlItem item = new ThumbnailControlItem(image);
item.Tag = resource;
item.Name = Path.GetFileName(resource.GetPathName());
item.Description = resource.GetPathName();
// Set source control status
if (m_sourceControlService != null)
{
SourceControlStatus status = m_sourceControlService.GetStatus(resource.Uri);
item.Indicator = SetSourceControlIndicator(resource.Uri, status);
}
return item;
}
private string SetSourceControlIndicator(Uri uri, SourceControlStatus status)
{
string indicator = null;
switch (status)
{
case SourceControlStatus.Added:
indicator = Resources.DocumentAddImage;
break;
case SourceControlStatus.CheckedIn:
{
if (m_sourceControlService.IsSynched(uri))
indicator = Resources.DocumentLockImage;
else
indicator = Resources.DocumentWarningImage;
}
break;
case SourceControlStatus.CheckedOut:
indicator = Resources.DocumentCheckOutImage;
break;
case SourceControlStatus.NotControlled:
indicator = null;
break;
}
return indicator;
}
private enum Command
{
ReloadAsset,
UnloadAssets,
DetailsView,
ThumbnailView,
AddExistingAsset,
}
private void RegisterCommands(ICommandService commandService)
{
commandService.RegisterCommand(
Command.ReloadAsset,
StandardMenu.File,
StandardCommandGroup.FileOther,
Localizer.Localize("Assets/Reload Asset"),
Localizer.Localize("Reload Asset"),
Keys.None,
null,
CommandVisibility.Menu,
this);
commandService.RegisterCommand(
Command.UnloadAssets,
StandardMenu.File,
StandardCommandGroup.FileOther,
Localizer.Localize("Assets/Unload Unused Assets"),
Localizer.Localize("Unload unused Assets"),
Keys.None,
null,
CommandVisibility.Menu,
this);
commandService.RegisterCommand(
Command.DetailsView,
null,//StandardMenu.View,
StandardCommandGroup.ViewControls,
Localizer.Localize("Details View", "Show detailed view of assets"),
Localizer.Localize("Show detailed view of assets"),
Keys.None,
null,
CommandVisibility.Menu,
this);
commandService.RegisterCommand(
Command.ThumbnailView,
null,//StandardMenu.View,
StandardCommandGroup.ViewControls,
Localizer.Localize("Thumbnail View"),
Localizer.Localize("Show thumbnail view of assets"),
Keys.None,
null,
CommandVisibility.Menu,
this);
commandService.RegisterCommand(
Command.AddExistingAsset,
StandardMenu.Edit,
StandardCommandGroup.EditOther,
Localizer.Localize("Add/Existing Asset"),
Localizer.Localize("Add an existing asset"),
Keys.None,
Resources.Asset,
CommandVisibility.All,
this);
}
/// <summary>
/// Gets or sets the root asset folder
/// </summary>
public IAssetFolder RootAssetFolder
{
get { return m_rootAssetFolder; }
set { m_rootAssetFolder = value; }
}
private class AssetFolderTreeView : ITreeView, IItemView
{
public AssetFolderTreeView(AssetLister assetLister)
{
m_assetLister = assetLister;
}
#region ITreeView Members
/// Gets the root object of the tree</summary>
public object Root
{
get { return m_assetLister.RootAssetFolder; }
}
/// <summary>
/// Gets an enumeration of the children of the given parent object</summary>
/// <param name="parent">Parent object</param>
/// <returns>Enumeration of children of the parent object</returns>
public IEnumerable<object> GetChildren(object parent)
{
IAssetFolder folder = Adapters.As<IAssetFolder>(parent);
foreach (IAssetFolder childfolder in folder.Folders)
yield return childfolder;
}
#endregion
#region IItemView Members
/// <summary>
/// Fills in or modifies the given display info for the item
/// </summary>
/// <param name="item">Item</param>
/// <param name="info">Display info to update</param>
public void GetInfo(object item, ItemInfo info)
{
IAssetFolder assetFolder = item as IAssetFolder;
if (assetFolder != null)
{
string label = assetFolder.Name;
info.Label = label;
info.AllowLabelEdit = false;
//info.ImageIndex = info.ImageList.Images.IndexOfKey(Sce.Atf.Resources.DataImage);
}
}
#endregion
AssetLister m_assetLister;
}
private class AssetItemListView : IListView, IItemView
{
public AssetItemListView(AssetLister assetLister)
{
m_assetLister = assetLister;
}
#region IListView members
/// <summary>
/// Gets names for table columns</summary>
public string[] ColumnNames
{
get { return s_columnNames; }
}
/// <summary>
/// Gets enumeration for the items in the list</summary>
public IEnumerable<object> Items
{
get
{
if (m_assetLister.CurrentAssetFolder != null)
{
foreach (IResource asset in m_assetLister.CurrentAssetFolder.Assets)
yield return asset;
}
}
}
#endregion // IListView members
#region IItemView Members
/// <summary>
/// Fills in or modifies the given display info for the item
/// </summary>
/// <param name="item">Item</param>
/// <param name="info">Display info to update</param>
public void GetInfo(object item, ItemInfo info)
{
IResource asset = item as IResource;
if (asset != null)
{
FileInfo fileInfo = new FileInfo(asset.Uri.LocalPath);
info.Label = fileInfo.Name;
info.ImageIndex = 0; //info.ImageList.Images.IndexOfKey(item.Indicator);
info.AllowLabelEdit = false;
Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
uint flags = Shell32.SHGFI_TYPENAME | Shell32.SHGFI_USEFILEATTRIBUTES;
Shell32.SHGetFileInfo(fileInfo.FullName,
Shell32.FILE_ATTRIBUTE_NORMAL,
ref shfi,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
flags);
string typeName = shfi.szTypeName;
long length;
DateTime lastWriteTime;
try
{
length = fileInfo.Length;
lastWriteTime = fileInfo.LastWriteTime;
}
catch (IOException)
{
length = 0;
lastWriteTime = new DateTime();
}
info.Properties = new object[] { fileInfo.Name, length, typeName, lastWriteTime };
}
}
#endregion
AssetLister m_assetLister;
}
/// <summary>
/// Gets or sets the currently selected asset list view mode. This string is
/// persisted in the user's settings file.
/// </summary>
public string AssetListViewMode
{
get
{
if (m_thumbnailControl.Visible)
return "Thumbnail";
else
return "Details";
}
set
{
// Make sure that 'value' is valid first, in case the the names have changed
// or the settings file is otherwise invalid.
if ("Details" == value)
{
DoCommand(Command.DetailsView);
}
else if ("Thumbnail" == value)
{
DoCommand(Command.ThumbnailView);
}
}
}
/// <summary>
/// Gets or sets the asset chooser dialog location</summary>
public Point AssetDialogLocation
{
get { return m_assetDialogLocation; }
set { m_assetDialogLocation = value; }
}
/// <summary>
/// Gets or sets the asset chooser dialog size</summary>
public Size AssetDialogSize
{
get { return m_assetDialogSize; }
set { m_assetDialogSize = value; }
}
/// <summary>
/// Gets or sets the list view settings
/// </summary>
public string ListViewSettings
{
get { return m_listViewAdaptor.Settings; }
set { m_listViewAdaptor.Settings = value; }
}
/// <summary>
/// Gets or sets the list view control bounds</summary>
public int SplitterDistance
{
get { return m_splitContainer.SplitterDistance; }
set { m_splitContainer.SplitterDistance = value; }
}
private void RegisterSettings()
{
if (m_settingsService != null)
{
m_settingsService.RegisterSettings(
this,
new BoundPropertyDescriptor(this, "AssetListViewMode", "AssetListViewMode", null, null),
new BoundPropertyDescriptor(this, "AssetDialogSize", "AssetDialogSize", null, null),
new BoundPropertyDescriptor(this, "AssetDialogLocation", "AssetDialogLocation", null, null),
new BoundPropertyDescriptor(this, "SplitterDistance", "SplitterDistance", null, null),
new BoundPropertyDescriptor(this, "ListViewSettings", "ListViewSettings", null, null));
}
}
private static string[] s_columnNames = new string[]
{
"Name", "Size", "Type", "Date Modified"
};
private SplitContainer m_splitContainer;
private TreeControlAdapter m_treeControlAdapter;
private TreeControl m_treeControl;
private ThumbnailControl m_thumbnailControl;
private List<IResource> m_requestedThumbs = new List<IResource>();
private ListView m_listView;
private ListViewAdaptor m_listViewAdaptor;
private IAssetFolder m_rootAssetFolder;
private IAssetFolder m_currentAssetFolder;
private AssetFolderTreeView m_assetFolderTreeView;
private AssetItemListView m_assetItemListView;
private object m_lastHit;
private Point m_hitPoint;
private StandardControlGroup m_controlGroup = StandardControlGroup.Bottom;
private IResource m_assetDoubleClicked;
private Point m_assetDialogLocation;
private Size m_assetDialogSize;
private Selection m_selection = new Selection();
private bool m_dragging;
private bool m_selecting;
private bool m_modal;
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.Text;
using System.Diagnostics;
using Axiom.Animating;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
namespace Multiverse.Serialization.Collada
{
/// <summary>
/// This object essentially corresponds to a polygons or
/// triangles clause in the collada file.
/// </summary>
public class MeshGeometry
{
/// <summary>
/// The id of this geometry object.
/// </summary>
public string Id
{
get { return id; }
}
string id;
/// <summary>
///
/// </summary>
public int InputCount
{
get { return inputSources.Count; }
}
/// <summary>
/// The list of faces -- indices of entries into pointSets
/// </summary>
public List<int[]> Faces
{
get { return faces; }
}
List<int[]> faces;
/// <summary>
///
/// </summary>
public List<SubMeshInfo> SubMeshes
{
get { return subMeshes; }
}
List<SubMeshInfo> subMeshes;
///<summary>
/// This is fundamentally the list of all the vertices. Each
/// vertex is represented here as a list indexes into inputs.
///</summary>
//
// This will be used for the vertex buffers. Each vertex will end
// up being composed of one entry for each item in the point set.
// A point set is something like the normal, position, texcoord
// and color of a vertex.
// The PointComponents object is basically just a list of the
// indices for the inputs.
public List<PointComponents> IndexSets
{
get { return pointSets; }
}
List<PointComponents> pointSets;
/// <summary>
/// This is the set of input source collections associated with
/// something like a triangles clause. Some of these input
/// sources are compound (e.g. a vertex), so there is not a
/// one to one mapping from InputSource to entries in the
/// PointComponents object. Use GetAllInputSources if you want
/// the list that maps to PointComponents entries.
/// </summary>
public Dictionary<int, List<InputSourceCollection>> InputSources
{
get { return inputSources; }
}
/// <summary>
/// This is temporary storage for the data that will go in our
/// vertex buffers. I leave in here so I can run transforms on it
/// as we go through this code.
/// </summary>
public List<VertexDataEntry> VertexDataEntries
{
get { return vertexDataEntries; }
}
List<VertexDataEntry> vertexDataEntries;
/// <summary>
/// Our vertex data. This is also stored in the mesh or submesh,
/// but it's convenient to have a handle here as well.
/// </summary>
public VertexData VertexData
{
get { return vertexData; }
set { vertexData = value; }
}
VertexData vertexData = new VertexData();
/// <summary>
///
/// </summary>
public Dictionary<int, List<VertexBoneAssignment>> BoneAssignmentList
{
get { return boneAssignmentList; }
set { boneAssignmentList = value; }
}
Dictionary<int, List<VertexBoneAssignment>> boneAssignmentList = null;
public bool IsSkinned
{
get { return null != BoneAssignmentList; }
}
/// <summary>
///
/// </summary>
public GeometrySet GeometrySet
{
get { return parentGeometrySet; }
}
GeometrySet parentGeometrySet;
// Create a logger for use in this class
protected static readonly log4net.ILog m_Log = log4net.LogManager.GetLogger( typeof( MeshGeometry ) );
// The input sources (e.g. normal vector data or texture coordinates)
// This is a mapping from input index to input source. The index is
// in the context of the parent 'triangles' node, where we are the
// nested input node, and have an 'idx' attribute. The values are
// the lists of input sources associated with that input index.
// These input sources may be simple input sources, like color,
// or complex input source, like the vertex.
Dictionary<int, List<InputSourceCollection>> inputSources;
// Mapping between the vertex id within the parent Geometry object,
// to the vertex indices within this submeshes of that vertex.
Dictionary<int, List<int>> vertexIds;
// The list of vertex entries. Each of these entries corresponds to
// a 'vertices' clause in the xml
Dictionary<string, VertexSet> vertexDict;
/// <summary>
///
/// </summary>
/// <param name="id">id of this mesh</param>
/// <param name="geoSet">the Geometry set this mesh belongs to</param>
public MeshGeometry( string id, GeometrySet geoSet )
{
this.id = id;
parentGeometrySet = geoSet;
inputSources = new Dictionary<int, List<InputSourceCollection>>();
pointSets = new List<PointComponents>();
faces = new List<int[]>();
vertexDict = new Dictionary<string, VertexSet>();
vertexIds = new Dictionary<int, List<int>>();
subMeshes = new List<SubMeshInfo>();
vertexDataEntries = new List<VertexDataEntry>();
}
public MeshGeometry Clone( string id, GeometrySet geoSet )
{
MeshGeometry clone = new MeshGeometry( id, geoSet );
foreach( int ii in this.inputSources.Keys )
{
clone.AddInputs( ii, this.inputSources[ ii ] );
}
foreach( PointComponents pc in this.pointSets )
{
clone.pointSets.Add( pc );
}
foreach( int[] f in this.faces )
{
clone.faces.Add( f );
}
foreach( string vs in this.vertexDict.Keys )
{
clone.vertexDict[ vs ] = this.vertexDict[ vs ];
}
foreach( int vi in this.vertexIds.Keys )
{
clone.vertexIds[ vi ] = this.vertexIds[ vi ];
}
foreach( VertexDataEntry vde in this.vertexDataEntries )
{
clone.vertexDataEntries.Add( vde.Clone() );
}
clone.VertexData = this.VertexData.Clone();
if( this.boneAssignmentList != null )
{
foreach( int vba in this.boneAssignmentList.Keys )
{
clone.boneAssignmentList[ vba ] = this.boneAssignmentList[ vba ];
}
}
int smi_count = 0;
foreach( SubMeshInfo smi in this.subMeshes )
{
SubMeshInfo new_smi = new SubMeshInfo();
new_smi.name = this.subMeshes.Count > 1 ? id + "." + (smi_count++).ToString() : id;
new_smi.material = smi.material;
clone.subMeshes.Add( new_smi );
}
return clone;
}
public void AddSubMesh( SubMeshInfo subMesh )
{
subMeshes.Add( subMesh );
}
public void AddInputs( int inputIndex, List<InputSourceCollection> input )
{
if( inputSources.ContainsKey( inputIndex ) )
{
m_Log.InfoFormat( "Duplicate input index: {0}", inputIndex );
}
inputSources[ inputIndex ] = input;
}
public void AddVertexSet( VertexSet vertexSet )
{
vertexDict[ vertexSet.id ] = vertexSet;
}
private VertexSet GetVertexSet( string name )
{
return vertexDict[ name ];
}
public List<InputSource> GetAllInputSources()
{
List<InputSource> sources = new List<InputSource>();
foreach( List<InputSourceCollection> tmpList in inputSources.Values )
{
foreach( InputSourceCollection tmp in tmpList )
{
sources.AddRange( tmp.GetSources() );
}
}
return sources;
}
public PointComponents BeginPoint()
{
return new PointComponents();
}
/// <summary>
/// Add a point component.
/// </summary>
/// <param name="index">Index within the given input source</param>
public void AddPointComponent( PointComponents currentPoint, int index )
{
currentPoint.Add( index );
}
public void EndPoint( PointComponents currentPoint, List<int> cwPolyPoints, List<int> ccwPolyPoints )
{
AddPointComponents( cwPolyPoints, currentPoint );
// Build a copy of currentPointComponents with normals inverted
if( ccwPolyPoints == null )
return;
PointComponents tmpPointComponents = new PointComponents( currentPoint );
List<InputSource> sources = GetAllInputSources();
for( int accessIndex = 0; accessIndex < sources.Count; ++accessIndex )
{
// For normals, since we need to invert them in the copy,
// we use a negating accessor, and tamper with the point
// component to change the index to the portion that is negated.
if( sources[ accessIndex ].IsNormal )
{
Debug.Assert( sources[ accessIndex ].Accessor is NegatingFloatAccessor );
tmpPointComponents[ accessIndex ] = -1 * tmpPointComponents[ accessIndex ];
}
}
AddPointComponents( ccwPolyPoints, tmpPointComponents );
}
/// <summary>
/// This adds the composite point currentPoint to the set of
/// points in this object. If there is already a point that
/// matches, we will use that instead.
/// </summary>
/// <param name="polyPoints"></param>
/// <param name="currentPoint"></param>
private void AddPointComponents( List<int> polyPoints, PointComponents currentPoint )
{
if( polyPoints == null )
return;
int compositeIndex = pointSets.IndexOf( currentPoint );
if( compositeIndex < 0 )
{
// we don't already have an entry for this point
int vertexIndex = currentPoint.VertexIndex;
if( vertexIndex < 0 )
{
m_Log.ErrorFormat( "No vertex id for point with vertex index: {0}", vertexIndex );
}
pointSets.Add( currentPoint );
compositeIndex = pointSets.Count - 1;
if( !vertexIds.ContainsKey( vertexIndex ) )
{
vertexIds[ vertexIndex ] = new List<int>();
}
vertexIds[ vertexIndex ].Add( compositeIndex );
}
polyPoints.Add( compositeIndex );
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<int> BeginPolygon()
{
return new List<int>();
}
/// <summary>
/// Need to build a triangulation of the polygon
/// </summary>
/// <param name="polyPoints"></param>
/// <param name="front"></param>
/// <param name="back"></param>
public void EndPolygon( List<int> polyPoints )
{
Debug.Assert( polyPoints.Count >= 3 );
// TODO: Check that all the points are coplanar
// TODO: Handle holes and maybe self-intersecting polygons
// For now, I just skip self-intersecting polygons
// TODO: Perhaps a Delaunay triangulation (edge-flip)
// should be done here.
List<Vector3> contour = new List<Vector3>();
List<int> contourToComposite = new List<int>();
List<InputSource> sources = GetAllInputSources();
// Find the input with position semantic
for( int accessIndex = 0; accessIndex < sources.Count; ++accessIndex )
{
if( sources[ accessIndex ].IsPosition )
{
// We found the position source. Use this to build a contour
// and triangluate the polygon.
// This code is not really used anymore, since we can now do
// the triangulation in maya instead.
InputSource source = sources[ accessIndex ];
foreach( int compositeIndex in polyPoints )
{
int inputIndex = pointSets[ compositeIndex ][ accessIndex ];
Vector3 pt;
pt.x = (float) source.Accessor.GetParam( "X", inputIndex );
pt.y = (float) source.Accessor.GetParam( "Y", inputIndex );
pt.z = (float) source.Accessor.GetParam( "Z", inputIndex );
contourToComposite.Add( compositeIndex );
contour.Add( pt );
}
break; // done with position
}
}
List<int[]> result = new List<int[]>();
bool status = Multiverse.MathLib.TriangleTessellation.Process( contour, result );
if( !status )
{
m_Log.Warn( "Skipping self-intersecting polygon - this may simply be a sliver polygon" );
}
else
{
foreach( int[] tri in result )
{
int[] faceIndices;
faceIndices = new int[ 3 ];
faceIndices[ 0 ] = contourToComposite[ tri[ 0 ] ];
faceIndices[ 1 ] = contourToComposite[ tri[ 1 ] ];
faceIndices[ 2 ] = contourToComposite[ tri[ 2 ] ];
faces.Add( faceIndices );
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public int[ , ] GetFaceData()
{
int[ , ] faceData = new int[ faces.Count, 3 ];
for( int faceIndex = 0; faceIndex < faces.Count; ++faceIndex )
{
int[] face = faces[ faceIndex ];
faceData[ faceIndex, 0 ] = face[ 0 ];
faceData[ faceIndex, 1 ] = face[ 1 ];
faceData[ faceIndex, 2 ] = face[ 2 ];
}
return faceData;
}
/// <summary>
///
/// </summary>
/// <param name="vertexId"></param>
/// <returns></returns>
public List<int> GetVertexIds( int vertexId )
{
if( vertexIds.ContainsKey( vertexId ) )
{
return vertexIds[ vertexId ];
}
return null;
}
internal void RigidBindToBone( SubMesh subMesh, Bone bone )
{
m_Log.InfoFormat( "Creating rigid binding from {0} to {1}", Id, bone.Name );
for( int i = 0; i < subMesh.vertexData.vertexCount; ++i )
{
VertexBoneAssignment vba = new VertexBoneAssignment();
vba.boneIndex = bone.Handle;
vba.vertexIndex = i;
vba.weight = 1.0f;
subMesh.AddBoneAssignment( vba );
}
BoneAssignmentList = subMesh.BoneAssignmentList;
}
internal void WeightedBindToBones( SubMesh subMesh, List<VertexBoneAssignment> vbaList )
{
// Some of these vertices needed to be split into multiple vertices.
// Rebuild the vertex bone assignment list, to have entries for our
// new vertex ids instead.
foreach( VertexBoneAssignment item in vbaList )
{
List<int> subMeshVertexIds = GetVertexIds( item.vertexIndex );
if( null != subMeshVertexIds )
{
foreach( int subVertexId in subMeshVertexIds )
{
VertexBoneAssignment vba = new VertexBoneAssignment( item );
vba.vertexIndex = subVertexId;
subMesh.AddBoneAssignment( vba );
}
}
}
BoneAssignmentList = subMesh.BoneAssignmentList;
}
/// <summary>
/// Reskin this geometry to the skeleton's position as the bind position.
/// </summary>
/// <param name="skeleton"></param>
/// <param name="invBindMatrices">Dictionary mapping bone id to inverse bind matrix for that bone</param>
internal void Reskin( Skeleton skeleton, Dictionary<string, Matrix4> invBindMatrices )
{
if( 0 < VertexDataEntries.Count )
{
m_Log.InfoFormat( "Generating per-vertex transforms for {0}", Id );
Debug.Assert( null != VertexDataEntries[ 0 ].fdata,
String.Format( "Invalid VertexDataEntry on geometry '{0}'", Id ) );
int vertexCount = VertexDataEntries[ 0 ].fdata.GetLength( 0 );
for( int vIdx = 0; vIdx < vertexCount; ++vIdx )
{
if( ! BoneAssignmentList.ContainsKey( vIdx ) )
{
// TODO: When does this condition actually occur? --jrl
// Is there a better way to bail out? Do we need notification?
m_Log.InfoFormat(
"No bone assignment for vertex[ {0} ] on geometry '{1}'",
vIdx, Id );
return;
}
Matrix4 vertexTransform = Matrix4.Zero;
foreach( VertexBoneAssignment vba in BoneAssignmentList[ vIdx ] )
{
Bone bone = skeleton.GetBone( vba.boneIndex );
Matrix4 mtx = bone.FullTransform * invBindMatrices[ bone.Name ];
vertexTransform += mtx * vba.weight;
}
Transform( vertexTransform, vIdx );
}
}
}
/// <summary>
/// Transform the vertices
/// </summary>
/// <remarks>
/// TODO: This is conceivably an inefficient implementation. I could
/// restructure the loop to have a similar switch() statement as in
/// Transform( Matrix4, int ), and have Transform*Float3() methods
/// that iterate over the entire array in the entry. I've run some
/// casual performance checks on that type of implementation, and found
/// no improvement in performance. For now, I opt for simpler code.
/// </remarks>
/// <param name="transform"></param>
/// <param name="geometry"></param>
internal void Transform( Matrix4 transform )
{
if( 0 < VertexDataEntries.Count )
{
int vertexCount = VertexDataEntries[ 0 ].fdata.GetLength( 0 );
for( int index = 0; index < vertexCount; index++ )
{
Transform( transform, index );
}
}
}
/// <summary>
/// Transform a single vertex
/// </summary>
/// <param name="transform"></param>
/// <param name="geometry"></param>
/// <param name="index"></param>
private void Transform( Matrix4 transform, int index )
{
foreach( VertexDataEntry entry in VertexDataEntries )
{
switch( entry.semantic )
{
case VertexElementSemantic.Position:
{
TransformFloat3( transform, entry.fdata, index );
break;
}
case VertexElementSemantic.Normal:
case VertexElementSemantic.Tangent:
case VertexElementSemantic.Binormal:
{
TransformAndNormalizeFloat3( transform, entry.fdata, index );
break;
}
}
}
}
private static void TransformFloat3( Matrix4 transform, float[ , ] data, int index )
{
Vector3 tmp = new Vector3( data[ index, 0 ], data[ index, 1 ], data[ index, 2 ] );
tmp = transform * tmp;
data[ index, 0 ] = tmp.x;
data[ index, 1 ] = tmp.y;
data[ index, 2 ] = tmp.z;
}
private static void TransformAndNormalizeFloat3( Matrix4 transform, float[ , ] data, int index )
{
Matrix4 matrix = transform;
matrix.Translation = Vector3.Zero;
Vector3 tmp = matrix * new Vector3( data[ index, 0 ], data[ index, 1 ], data[ index, 2 ] ); ;
tmp.Normalize();
data[ index, 0 ] = tmp.x;
data[ index, 1 ] = tmp.y;
data[ index, 2 ] = tmp.z;
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
// POP3 Email Client
// =================
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use at own risk, no
// responsibility accepted. All rights, title and interest in and to the accompanying content retained. :-)
//
// based on Standard for ARPA Internet Text Messages, http://rfc.net/rfc822.html
// based on MIME Standard, Internet Message Bodies, http://rfc.net/rfc2045.html
// based on MIME Standard, Media Types, http://rfc.net/rfc2046.html
namespace SoftLogik.Mail
{
namespace Mail
{
namespace Pop3
{
/// <summary>
/// Stores all MIME decoded information of a received email. One email might consist of
/// several MIME entities, which have a very similar structure to an email. A RxMailMessage
/// can be a top most level email or a MIME entity the emails contains.
///
/// According to various RFCs, MIME entities can contain other MIME entities
/// recursively. However, they usually need to be mapped to alternative views and
/// attachments, which are non recursive.
///
/// RxMailMessage inherits from System.Net.MailMessage, but provides additional receiving related information
/// </summary>
public class RxMailMessage : MailMessage
{
/// <summary>
/// To whom the email was delivered to
/// </summary>
public MailAddress DeliveredTo;
/// <summary>
/// To whom the email was
/// </summary>
public MailAddress ReturnPath;
/// <summary>
///
/// </summary>
public DateTime DeliveryDate;
/// <summary>
/// Date when the email was received
/// </summary>
public string MessageId;
/// <summary>
/// probably '1,0'
/// </summary>
public string MimeVersion;
/// <summary>
/// It may be desirable to allow one body to make reference to another. Accordingly,
/// bodies may be labelled using the "Content-ID" header field.
/// </summary>
public string ContentId;
/// <summary>
/// some descriptive information for body
/// </summary>
public string ContentDescription;
/// <summary>
/// ContentDisposition contains normally redundant information also stored in the
/// ContentType. Since ContentType is more detailed, it is enough to analyze ContentType
///
/// something like:
/// inline
/// inline; filename="image001.gif
/// attachment; filename="image001.jpg"
/// </summary>
public ContentDisposition ContentDisposition;
/// <summary>
/// something like "7bit" / "8bit" / "binary" / "quoted-printable" / "base64"
/// </summary>
public string TransferType;
/// <summary>
/// similar as TransferType, but .NET supports only "7bit" / "quoted-printable"
/// / "base64" here, "bit8" is marked as "bit7" (i.e. no transfer encoding needed),
/// "binary" is illegal in SMTP
/// </summary>
public TransferEncoding ContentTransferEncoding;
/// <summary>
/// The Content-Type field is used to specify the nature of the data in the body of a
/// MIME entity, by giving media type and subtype identifiers, and by providing
/// auxiliary information that may be required for certain media types. Examples:
/// text/plain;
/// text/plain; charset=ISO-8859-1
/// text/plain; charset=us-ascii
/// text/plain; charset=utf-8
/// text/html;
/// text/html; charset=ISO-8859-1
/// image/gif; name=image004.gif
/// image/jpeg; name="image005.jpg"
/// message/delivery-status
/// message/rfc822
/// multipart/alternative; boundary="----=_Part_4088_29304219.1115463798628"
/// multipart/related; boundary="----=_Part_2067_9241611.1139322711488"
/// multipart/mixed; boundary="----=_Part_3431_12384933.1139387792352"
/// multipart/report; report-type=delivery-status; boundary="k04G6HJ9025016.1136391237/carbon.singnet.com.sg"
/// </summary>
public ContentType ContentType;
/// <summary>
/// .NET framework combines MediaType (text) with subtype (plain) in one property, but
/// often one or the other is needed alone. MediaMainType in this example would be 'text'.
/// </summary>
public string MediaMainType;
/// <summary>
/// .NET framework combines MediaType (text) with subtype (plain) in one property, but
/// often one or the other is needed alone. MediaSubType in this example would be 'plain'.
/// </summary>
public string MediaSubType;
/// <summary>
/// RxMessage can be used for any MIME entity, as a normal message body, an attachement or an alternative view. ContentStream
/// provides the actual content of that MIME entity. It's mainly used internally and later mapped to the corresponding
/// .NET types.
/// </summary>
public Stream ContentStream;
/// <summary>
/// A MIME entity can contain several MIME entities. A MIME entity has the same structure
/// like an email.
/// </summary>
public List<RxMailMessage> Entities;
/// <summary>
/// This entity might be part of a parent entity
/// </summary>
public RxMailMessage Parent;
/// <summary>
/// The top most MIME entity this MIME entity belongs to (grand grand grand .... parent)
/// </summary>
public RxMailMessage TopParent;
/// <summary>
/// The complete entity in raw content. Since this might take up quiet some space, the raw content gets only stored if the
/// Pop3MimeClient.isGetRawEmail is set.
/// </summary>
public string RawContent;
/// <summary>
/// Headerlines not interpretable by Pop3ClientEmail
/// <example></example>
/// </summary>
public List<string> UnknowHeaderlines;
// Constructors
// ------------
/// <summary>
/// default constructor
/// </summary>
public RxMailMessage()
{
//for the moment, we assume to be at the top
//should this entity become a child, TopParent will be overwritten
TopParent = this;
Entities = new List<RxMailMessage>();
UnknowHeaderlines = new List<string>();
}
/// <summary>
/// Set all content type related fields
/// </summary>
public void SetContentTypeFields(string contentTypeString)
{
contentTypeString = contentTypeString.Trim();
//set content type
if (contentTypeString == null || contentTypeString.Length < 1)
{
ContentType = new ContentType("text/plain; charset=us-ascii");
}
else
{
ContentType = new ContentType(contentTypeString);
}
//set encoding (character set)
if (ContentType.CharSet == null)
{
BodyEncoding = Encoding.ASCII;
}
else
{
try
{
BodyEncoding = Encoding.GetEncoding(ContentType.CharSet);
}
catch
{
BodyEncoding = Encoding.ASCII;
}
}
//set media main and sub type
if (ContentType.MediaType == null || ContentType.MediaType.Length < 1)
{
//no mediatype found
ContentType.MediaType = "text/plain";
}
else
{
string mediaTypeString = ContentType.MediaType.Trim().ToLowerInvariant();
int slashPosition = ContentType.MediaType.IndexOf("/");
if (slashPosition < 1)
{
//only main media type found
MediaMainType = mediaTypeString;
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
if (MediaMainType == "text")
{
MediaSubType = "plain";
}
else
{
MediaSubType = "";
}
}
else
{
//also submedia found
MediaMainType = mediaTypeString.Substring(0, slashPosition);
if (mediaTypeString.Length > slashPosition)
{
MediaSubType = mediaTypeString.Substring(slashPosition + 1);
}
else
{
if (MediaMainType == "text")
{
MediaSubType = "plain";
}
else
{
MediaSubType = "";
System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
}
}
}
}
IsBodyHtml = MediaSubType == "html";
}
/// <summary>
/// Creates an empty child MIME entity from the parent MIME entity.
///
/// An email can consist of several MIME entities. A entity has the same structure
/// like an email, that is header and body. The child inherits few properties
/// from the parent as default value.
/// </summary>
public RxMailMessage CreateChildEntity()
{
RxMailMessage child = new RxMailMessage();
child.Parent = this;
child.TopParent = this.TopParent;
child.ContentTransferEncoding = this.ContentTransferEncoding;
return child;
}
private StringBuilder m_mailStructure;
private void AppendLine(string format, object arg)
{
if (arg != null)
{
string argString = arg.ToString();
if (argString.Length > 0)
{
m_mailStructure.AppendLine(string.Format(format, argString));
}
}
}
private void decodeEntity(RxMailMessage entity)
{
AppendLine("From : {0}", entity.From);
AppendLine("Sender: {0}", entity.Sender);
AppendLine("To : {0}", entity.To);
AppendLine("CC : {0}", entity.CC);
AppendLine("ReplyT: {0}", entity.ReplyTo);
AppendLine("Sub : {0}", entity.Subject);
AppendLine("S-Enco: {0}", entity.SubjectEncoding);
if (entity.DeliveryDate > DateTime.MinValue)
{
AppendLine("Date : {0}", entity.DeliveryDate);
}
if (entity.Priority != MailPriority.Normal)
{
AppendLine("Priori: {0}", entity.Priority);
}
if (entity.Body.Length > 0)
{
AppendLine("Body : {0} byte(s)", entity.Body.Length);
AppendLine("B-Enco: {0}", entity.BodyEncoding);
}
else
{
if (entity.BodyEncoding != Encoding.ASCII)
{
AppendLine("B-Enco: {0}", entity.BodyEncoding);
}
}
AppendLine("T-Type: {0}", entity.TransferType);
AppendLine("C-Type: {0}", entity.ContentType);
AppendLine("C-Desc: {0}", entity.ContentDescription);
AppendLine("C-Disp: {0}", entity.ContentDisposition);
AppendLine("C-Id : {0}", entity.ContentId);
AppendLine("M-ID : {0}", entity.MessageId);
AppendLine("Mime : Version {0}", entity.MimeVersion);
if (entity.ContentStream != null)
{
AppendLine("Stream: Length {0}", entity.ContentStream.Length);
}
//decode all shild MIME entities
foreach (RxMailMessage child in entity.Entities)
{
m_mailStructure.AppendLine("------------------------------------");
decodeEntity(child);
}
if (entity.ContentType != null&& entity.ContentType.MediaType != null&& entity.ContentType.MediaType.StartsWith("multipart"))
{
AppendLine("End {0}", entity.ContentType.ToString());
}
}
/// <summary>
/// Convert structure of message into a string
/// </summary>
/// <returns></returns>
public string MailStructure
{
get
{
m_mailStructure = new StringBuilder(1000);
decodeEntity(this);
m_mailStructure.AppendLine("====================================");
return m_mailStructure.ToString();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GitTools.Testing;
using GitVersion;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using GitVersionCore.Tests.Helpers;
using GitVersionCore.Tests.IntegrationTests;
using LibGit2Sharp;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Shouldly;
namespace GitVersionCore.Tests.VersionCalculation
{
public class NextVersionCalculatorTests : TestBase
{
[Test]
public void ShouldIncrementVersionBasedOnConfig()
{
var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now, 0);
var contextBuilder = new GitVersionContextBuilder();
contextBuilder
.OverrideServices(services =>
{
var testBaseVersionCalculator = new TestBaseVersionCalculator(true, new SemanticVersion(1), GitToolsTestingExtensions.CreateMockCommit());
services.AddSingleton<IBaseVersionCalculator>(testBaseVersionCalculator);
services.AddSingleton<IMainlineVersionCalculator>(new TestMainlineVersionCalculator(semanticVersionBuildMetaData));
})
.WithConfig(new Config())
.Build();
var nextVersionCalculator = contextBuilder.ServicesProvider.GetService<INextVersionCalculator>();
nextVersionCalculator.ShouldNotBeNull();
var version = nextVersionCalculator.FindVersion();
version.ToString().ShouldBe("1.0.1");
}
[Test]
public void DoesNotIncrementWhenBaseVersionSaysNotTo()
{
var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now, 0);
var contextBuilder = new GitVersionContextBuilder();
contextBuilder
.OverrideServices(services =>
{
var testBaseVersionCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), GitToolsTestingExtensions.CreateMockCommit());
services.AddSingleton<IBaseVersionCalculator>(testBaseVersionCalculator);
services.AddSingleton<IMainlineVersionCalculator>(new TestMainlineVersionCalculator(semanticVersionBuildMetaData));
})
.WithConfig(new Config())
.Build();
var nextVersionCalculator = contextBuilder.ServicesProvider.GetService<INextVersionCalculator>();
nextVersionCalculator.ShouldNotBeNull();
var version = nextVersionCalculator.FindVersion();
version.ToString().ShouldBe("1.0.0");
}
[Test]
public void AppliesBranchPreReleaseTag()
{
var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 2, "develop", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now, 0);
var contextBuilder = new GitVersionContextBuilder();
contextBuilder
.OverrideServices(services =>
{
var testBaseVersionCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), GitToolsTestingExtensions.CreateMockCommit());
services.AddSingleton<IBaseVersionCalculator>(testBaseVersionCalculator);
services.AddSingleton<IMainlineVersionCalculator>(new TestMainlineVersionCalculator(semanticVersionBuildMetaData));
})
.WithDevelopBranch()
.Build();
var nextVersionCalculator = contextBuilder.ServicesProvider.GetService<INextVersionCalculator>();
nextVersionCalculator.ShouldNotBeNull();
var version = nextVersionCalculator.FindVersion();
version.ToString("f").ShouldBe("1.0.0-alpha.1+2");
}
[Test]
public void PreReleaseTagCanUseBranchName()
{
var config = new Config
{
NextVersion = "1.0.0",
Branches = new Dictionary<string, BranchConfig>
{
{
"custom", new BranchConfig
{
Regex = "custom/",
Tag = "useBranchName",
SourceBranches = new HashSet<string>()
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("custom/foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.0-foo.1+2", config);
}
[Test]
public void PreReleaseVersionMainline()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline,
NextVersion = "1.0.0"
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.0-foo.1", config);
}
[Test]
public void MergeIntoMainline()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline,
NextVersion = "1.0.0"
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("foo");
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MergeNoFF("foo");
fixture.AssertFullSemver("1.0.0", config);
}
[Test]
public void MergeFeatureIntoMainline()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.ApplyTag("1.0.0");
fixture.AssertFullSemver("1.0.0", config);
fixture.BranchTo("feature/foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.1-foo.1", config);
fixture.ApplyTag("1.0.1-foo.1");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.1", config);
}
[Test]
public void MergeFeatureIntoMainlineWithMinorIncrement()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline,
Branches = new Dictionary<string, BranchConfig>()
{
{ "feature", new BranchConfig { Increment = IncrementStrategy.Minor } }
},
Ignore = new IgnoreConfig() { ShAs = new List<string>() },
MergeMessageFormats = new Dictionary<string, string>()
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.ApplyTag("1.0.0");
fixture.AssertFullSemver("1.0.0", config);
fixture.BranchTo("feature/foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-foo.1", config);
fixture.ApplyTag("1.1.0-foo.1");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", config);
}
[Test]
public void MergeFeatureIntoMainlineWithMinorIncrementAndThenMergeHotfix()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline,
Branches = new Dictionary<string, BranchConfig>()
{
{ "feature", new BranchConfig { Increment = IncrementStrategy.Minor } }
},
Ignore = new IgnoreConfig() { ShAs = new List<string>() },
MergeMessageFormats = new Dictionary<string, string>()
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.ApplyTag("1.0.0");
fixture.AssertFullSemver("1.0.0", config);
fixture.BranchTo("feature/foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-foo.1", config);
fixture.ApplyTag("1.1.0-foo.1");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", config);
fixture.ApplyTag("1.1.0");
fixture.BranchTo("hotfix/bar");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1-beta.1", config);
fixture.ApplyTag("1.1.1-beta.1");
fixture.Checkout("master");
fixture.MergeNoFF("hotfix/bar");
fixture.AssertFullSemver("1.1.1", config);
}
[Test]
public void PreReleaseTagCanUseBranchNameVariable()
{
var config = new Config
{
NextVersion = "1.0.0",
Branches = new Dictionary<string, BranchConfig>
{
{
"custom", new BranchConfig
{
Regex = "custom/",
Tag = "alpha.{BranchName}",
SourceBranches = new HashSet<string>()
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("custom/foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.0-alpha.foo.1+2", config);
}
[Test]
public void PreReleaseNumberShouldBeScopeToPreReleaseLabelInContinuousDelivery()
{
var config = new Config
{
VersioningMode = VersioningMode.ContinuousDelivery,
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
Tag = "beta"
}
},
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
fixture.Repository.CreateBranch("feature/test");
Commands.Checkout(fixture.Repository, "feature/test");
fixture.Repository.MakeATaggedCommit("0.1.0-test.1");
fixture.Repository.MakeACommit();
fixture.AssertFullSemver("0.1.0-test.2+2", config);
Commands.Checkout(fixture.Repository, "master");
fixture.Repository.Merge("feature/test", Generate.SignatureNow());
fixture.AssertFullSemver("0.1.0-beta.1+2", config);
}
[Test]
public void GetNextVersionOnNonMainlineBranchWithoutCommitsShouldWorkNormally()
{
var config = new Config
{
VersioningMode = VersioningMode.Mainline,
NextVersion = "1.0.0"
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("initial commit");
fixture.BranchTo("feature/f1");
fixture.AssertFullSemver("1.0.0-f1.0", config);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class CustomRenderTests : TestBase
{
public CustomRenderTests()
: base(@"Controls\CustomRender")
{
}
[Fact]
public async Task Clip()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
context.FillRectangle(
Brushes.Red,
new Rect(control.Bounds.Size),
4);
using (context.PushClip(new Rect(control.Bounds.Size).Deflate(10)))
{
context.FillRectangle(
Brushes.Blue,
new Rect(control.Bounds.Size),
4);
}
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task GeometryClip()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
var clip = new EllipseGeometry(new Rect(control.Bounds.Size));
context.FillRectangle(
Brushes.Red,
new Rect(control.Bounds.Size),
4);
using (context.PushGeometryClip(clip))
{
context.FillRectangle(
Brushes.Blue,
new Rect(control.Bounds.Size),
4);
}
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task GeometryClip_With_Transform()
{
var target = new Border
{
Background = Brushes.White,
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
using (var transform = context.PushPreTransform(Matrix.CreateTranslation(100, 100)))
using (var clip = context.PushClip(new Rect(0, 0, 100, 100)))
{
context.FillRectangle(Brushes.Blue, new Rect(0, 0, 200, 200));
}
context.FillRectangle(Brushes.Red, new Rect(0, 0, 100, 100));
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Clip_With_Transform()
{
var target = new Border
{
Background = Brushes.White,
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
using (var transform = context.PushPreTransform(Matrix.CreateTranslation(100, 100)))
using (var clip = context.PushClip(new Rect(0, 0, 100, 100)))
{
context.FillRectangle(Brushes.Blue, new Rect(0, 0, 200, 200));
}
context.FillRectangle(Brushes.Red, new Rect(0, 0, 100, 100));
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Opacity()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
context.FillRectangle(
Brushes.Red,
new Rect(control.Bounds.Size),
4);
using (context.PushOpacity(0.5))
{
context.FillRectangle(
Brushes.Blue,
new Rect(control.Bounds.Size).Deflate(10),
4);
}
}),
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task OpacityMask()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new CustomRenderer((control, context) =>
{
var mask = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromUInt32(0xffffffff), 0),
new GradientStop(Color.FromUInt32(0x00ffffff), 1)
},
};
context.FillRectangle(
Brushes.Red,
new Rect(control.Bounds.Size),
4);
using (context.PushOpacityMask(mask, new Rect(control.Bounds.Size)))
{
context.FillRectangle(
Brushes.Blue,
new Rect(control.Bounds.Size).Deflate(10),
4);
}
}),
};
await RenderToFile(target);
CompareImages();
}
class CustomRenderer : Control
{
private Action<CustomRenderer, DrawingContext> _render;
public CustomRenderer(Action<CustomRenderer, DrawingContext> render) => _render = render;
public override void Render(DrawingContext context) => _render(this, context);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonDictionaryContract : JsonContainerContract
{
/// <summary>
/// Gets or sets the property name resolver.
/// </summary>
/// <value>The property name resolver.</value>
[Obsolete("PropertyNameResolver is obsolete. Use DictionaryKeyResolver instead.")]
public Func<string, string> PropertyNameResolver
{
get { return DictionaryKeyResolver; }
set { DictionaryKeyResolver = value; }
}
/// <summary>
/// Gets or sets the dictionary key resolver.
/// </summary>
/// <value>The dictionary key resolver.</value>
public Func<string, string> DictionaryKeyResolver { get; set; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary keys.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary keys.</value>
public Type DictionaryKeyType { get; private set; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary values.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary values.</value>
public Type DictionaryValueType { get; private set; }
internal JsonContract KeyContract { get; set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryDictionaryCreator;
internal bool ShouldCreateWrapper { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _overrideCreator;
private ObjectConstructor<object> _parameterizedCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set { _overrideCreator = value; }
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the dictionary values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal
{
get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonDictionaryContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Dictionary;
Type keyType;
Type valueType;
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>)))
CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
#if !(NET40 || NET35 || NET20 || PORTABLE40)
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>));
#endif
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>)))
CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType);
IsReadOnlyOrFixedSize = true;
}
#endif
else
{
ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType);
if (UnderlyingType == typeof(IDictionary))
CreatedType = typeof(Dictionary<object, object>);
}
if (keyType != null && valueType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType));
#if !(NET35 || NET20)
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType);
}
#endif
}
ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType);
DictionaryKeyType = keyType;
DictionaryValueType = valueType;
#if (NET20 || NET35)
if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType))
{
Type tempDictioanryType;
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType))
{
ShouldCreateWrapper = true;
}
}
#endif
#if !(NET20 || NET35 || NET40)
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
}
#endif
}
internal IWrappedDictionary CreateWrapper(object dictionary)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType);
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedDictionary)_genericWrapperCreator(dictionary);
}
internal IDictionary CreateTemporaryDictionary()
{
if (_genericTemporaryDictionaryCreator == null)
{
Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object));
_genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType);
}
return (IDictionary)_genericTemporaryDictionaryCreator();
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IdentityServer4.Services
{
/// <summary>
/// Default claims provider implementation
/// </summary>
public class DefaultClaimsService : IClaimsService
{
/// <summary>
/// The logger
/// </summary>
protected readonly ILogger Logger;
/// <summary>
/// The user service
/// </summary>
protected readonly IProfileService Profile;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultClaimsService"/> class.
/// </summary>
/// <param name="profile">The profile service</param>
/// <param name="logger">The logger</param>
public DefaultClaimsService(IProfileService profile, ILogger<DefaultClaimsService> logger)
{
Logger = logger;
Profile = profile;
}
/// <summary>
/// Returns claims for an identity token
/// </summary>
/// <param name="subject">The subject</param>
/// <param name="resources">The requested resources</param>
/// <param name="includeAllIdentityClaims">Specifies if all claims should be included in the token, or if the userinfo endpoint can be used to retrieve them</param>
/// <param name="request">The raw request</param>
/// <returns>
/// Claims for the identity token
/// </returns>
public virtual async Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resources, bool includeAllIdentityClaims, ValidatedRequest request)
{
Logger.LogDebug("Getting claims for identity token for subject: {subject} and client: {clientId}",
subject.GetSubjectId(),
request.Client.ClientId);
var outputClaims = new List<Claim>(GetStandardSubjectClaims(subject));
outputClaims.AddRange(GetOptionalClaims(subject));
// fetch all identity claims that need to go into the id token
if (includeAllIdentityClaims || request.Client.AlwaysIncludeUserClaimsInIdToken)
{
var additionalClaimTypes = new List<string>();
foreach (var identityResource in resources.Resources.IdentityResources)
{
foreach (var userClaim in identityResource.UserClaims)
{
additionalClaimTypes.Add(userClaim);
}
}
// filter so we don't ask for claim types that we will eventually filter out
additionalClaimTypes = FilterRequestedClaimTypes(additionalClaimTypes).ToList();
var context = new ProfileDataRequestContext(
subject,
request.Client,
IdentityServerConstants.ProfileDataCallers.ClaimsProviderIdentityToken,
additionalClaimTypes)
{
RequestedResources = resources,
ValidatedRequest = request
};
await Profile.GetProfileDataAsync(context);
var claims = FilterProtocolClaims(context.IssuedClaims);
if (claims != null)
{
outputClaims.AddRange(claims);
}
}
else
{
Logger.LogDebug("In addition to an id_token, an access_token was requested. No claims other than sub are included in the id_token. To obtain more user claims, either use the user info endpoint or set AlwaysIncludeUserClaimsInIdToken on the client configuration.");
}
return outputClaims;
}
/// <summary>
/// Returns claims for an access token.
/// </summary>
/// <param name="subject">The subject.</param>
/// <param name="resourceResult">The validated resource result</param>
/// <param name="request">The raw request.</param>
/// <returns>
/// Claims for the access token
/// </returns>
public virtual async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, ResourceValidationResult resourceResult, ValidatedRequest request)
{
Logger.LogDebug("Getting claims for access token for client: {clientId}", request.Client.ClientId);
var outputClaims = new List<Claim>
{
new Claim(JwtClaimTypes.ClientId, request.ClientId)
};
// log if client ID is overwritten
if (!string.Equals(request.ClientId, request.Client.ClientId))
{
Logger.LogDebug("Client {clientId} is impersonating {impersonatedClientId}", request.Client.ClientId, request.ClientId);
}
// check for client claims
if (request.ClientClaims != null && request.ClientClaims.Any())
{
if (subject == null || request.Client.AlwaysSendClientClaims)
{
foreach (var claim in request.ClientClaims)
{
var claimType = claim.Type;
if (request.Client.ClientClaimsPrefix.IsPresent())
{
claimType = request.Client.ClientClaimsPrefix + claimType;
}
outputClaims.Add(new Claim(claimType, claim.Value, claim.ValueType));
}
}
}
// add scopes (filter offline_access)
// we use the ScopeValues collection rather than the Resources.Scopes because we support dynamic scope values
// from the request, so this issues those in the token.
foreach (var scope in resourceResult.RawScopeValues.Where(x => x != IdentityServerConstants.StandardScopes.OfflineAccess))
{
outputClaims.Add(new Claim(JwtClaimTypes.Scope, scope));
}
// a user is involved
if (subject != null)
{
if (resourceResult.Resources.OfflineAccess)
{
outputClaims.Add(new Claim(JwtClaimTypes.Scope, IdentityServerConstants.StandardScopes.OfflineAccess));
}
Logger.LogDebug("Getting claims for access token for subject: {subject}", subject.GetSubjectId());
outputClaims.AddRange(GetStandardSubjectClaims(subject));
outputClaims.AddRange(GetOptionalClaims(subject));
// fetch all resource claims that need to go into the access token
var additionalClaimTypes = new List<string>();
foreach (var api in resourceResult.Resources.ApiResources)
{
// add claims configured on api resource
if (api.UserClaims != null)
{
foreach (var claim in api.UserClaims)
{
additionalClaimTypes.Add(claim);
}
}
}
foreach(var scope in resourceResult.Resources.ApiScopes)
{
// add claims configured on scopes
if (scope.UserClaims != null)
{
foreach (var claim in scope.UserClaims)
{
additionalClaimTypes.Add(claim);
}
}
}
// filter so we don't ask for claim types that we will eventually filter out
additionalClaimTypes = FilterRequestedClaimTypes(additionalClaimTypes).ToList();
var context = new ProfileDataRequestContext(
subject,
request.Client,
IdentityServerConstants.ProfileDataCallers.ClaimsProviderAccessToken,
additionalClaimTypes.Distinct())
{
RequestedResources = resourceResult,
ValidatedRequest = request
};
await Profile.GetProfileDataAsync(context);
var claims = FilterProtocolClaims(context.IssuedClaims);
if (claims != null)
{
outputClaims.AddRange(claims);
}
}
return outputClaims;
}
/// <summary>
/// Gets the standard subject claims.
/// </summary>
/// <param name="subject">The subject.</param>
/// <returns>A list of standard claims</returns>
protected virtual IEnumerable<Claim> GetStandardSubjectClaims(ClaimsPrincipal subject)
{
var claims = new List<Claim>
{
new Claim(JwtClaimTypes.Subject, subject.GetSubjectId()),
new Claim(JwtClaimTypes.AuthenticationTime, subject.GetAuthenticationTimeEpoch().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtClaimTypes.IdentityProvider, subject.GetIdentityProvider())
};
claims.AddRange(subject.GetAuthenticationMethods());
return claims;
}
/// <summary>
/// Gets additional (and optional) claims from the cookie or incoming subject.
/// </summary>
/// <param name="subject">The subject.</param>
/// <returns>Additional claims</returns>
protected virtual IEnumerable<Claim> GetOptionalClaims(ClaimsPrincipal subject)
{
var claims = new List<Claim>();
var acr = subject.FindFirst(JwtClaimTypes.AuthenticationContextClassReference);
if (acr != null) claims.Add(acr);
return claims;
}
/// <summary>
/// Filters out protocol claims like amr, nonce etc..
/// </summary>
/// <param name="claims">The claims.</param>
/// <returns></returns>
protected virtual IEnumerable<Claim> FilterProtocolClaims(IEnumerable<Claim> claims)
{
var claimsToFilter = claims.Where(x => Constants.Filters.ClaimsServiceFilterClaimTypes.Contains(x.Type));
if (claimsToFilter.Any())
{
var types = claimsToFilter.Select(x => x.Type);
Logger.LogDebug("Claim types from profile service that were filtered: {claimTypes}", types);
}
return claims.Except(claimsToFilter);
}
/// <summary>
/// Filters out protocol claims like amr, nonce etc..
/// </summary>
/// <param name="claimTypes">The claim types.</param>
protected virtual IEnumerable<string> FilterRequestedClaimTypes(IEnumerable<string> claimTypes)
{
var claimTypesToFilter = claimTypes.Where(x => Constants.Filters.ClaimsServiceFilterClaimTypes.Contains(x));
return claimTypes.Except(claimTypesToFilter);
}
}
}
| |
// 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!
using gaxgrpc = Google.Api.Gax.Grpc;
using gcoc = Google.Cloud.OsLogin.Common;
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.OsLogin.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedOsLoginServiceClientTest
{
[xunit::FactAttribute]
public void DeletePosixAccountRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePosixAccount()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePosixAccountResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request.PosixAccountName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request.PosixAccountName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request.PosixAccountName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKey()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKeyResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request.SshPublicKeyName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfileRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
ProjectId = "project_id43ad98b0",
SystemId = "system_id43548ac1",
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
ProjectId = "project_id43ad98b0",
SystemId = "system_id43548ac1",
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfile()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfileResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request.UserName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.UserName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.UserName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKey()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKeyResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request.SshPublicKeyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey1()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey1Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey1ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey1ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey2()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey, request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey2Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey2ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey, request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey2ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey1()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey1Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey1ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey1ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey2()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey2Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey2ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey2ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
' Copyright (c) 2011 DotNetNuke Corporation
' All rights reserved.
'
' 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 DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Users.Social;
using DotNetNuke.Framework;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Web.Client.ClientResourceManagement;
using DotNetNuke.Modules.Journal.Components;
using DotNetNuke.Security.Roles;
namespace DotNetNuke.Modules.Journal {
/// -----------------------------------------------------------------------------
/// <summary>
/// The ViewJournal class displays the content
/// </summary>
/// -----------------------------------------------------------------------------
public partial class View : JournalModuleBase {
public int PageSize = 20;
public bool AllowPhotos = true;
public bool AllowFiles = true;
public int MaxMessageLength = 250;
public bool CanRender = true;
public bool ShowEditor = true;
public bool CanComment = true;
public bool IsGroup = false;
public string BaseUrl;
public string ProfilePage;
public int Gid = -1;
public int Pid = -1;
public long MaxUploadSize = Config.GetMaxUploadSize();
#region Event Handlers
override protected void OnInit(EventArgs e)
{
JavaScript.RequestRegistration(CommonJs.DnnPlugins);
JavaScript.RequestRegistration(CommonJs.jQueryFileUpload);
ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
JavaScript.RequestRegistration(CommonJs.Knockout);
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journal.js");
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journalcomments.js");
ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js");
ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Scripts/json2.js");
var isAdmin = UserInfo.IsInRole(RoleController.Instance.GetRoleById(PortalId, PortalSettings.AdministratorRoleId).RoleName);
if (!Request.IsAuthenticated || (!UserInfo.IsSuperUser && !isAdmin && UserInfo.IsInRole("Unverified Users")))
{
ShowEditor = false;
}
else
{
ShowEditor = EditorEnabled;
}
if (Settings.ContainsKey(Constants.DefaultPageSize))
{
PageSize = Convert.ToInt16(Settings[Constants.DefaultPageSize]);
}
if (Settings.ContainsKey(Constants.MaxCharacters))
{
MaxMessageLength = Convert.ToInt16(Settings[Constants.MaxCharacters]);
}
if (Settings.ContainsKey(Constants.AllowPhotos))
{
AllowPhotos = Convert.ToBoolean(Settings[Constants.AllowPhotos]);
}
if (Settings.ContainsKey(Constants.AllowFiles))
{
AllowFiles = Convert.ToBoolean(Settings[Constants.AllowFiles]);
}
ctlJournalList.Enabled = true;
ctlJournalList.ProfileId = -1;
ctlJournalList.PageSize = PageSize;
ctlJournalList.ModuleId = ModuleId;
ModuleInfo moduleInfo = ModuleContext.Configuration;
foreach (var module in ModuleController.Instance.GetTabModules(TabId).Values)
{
if (module.ModuleDefinition.FriendlyName == "Social Groups")
{
if (GroupId == -1 && FilterMode == JournalMode.Auto)
{
ShowEditor = false;
ctlJournalList.Enabled = false;
}
if (GroupId > 0)
{
RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, GroupId);
if (roleInfo != null)
{
if (UserInfo.IsInRole(roleInfo.RoleName))
{
ShowEditor = true;
CanComment = true;
IsGroup = true;
} else
{
ShowEditor = false;
CanComment = false;
}
if (!roleInfo.IsPublic && !ShowEditor)
{
ctlJournalList.Enabled = false;
}
if (roleInfo.IsPublic && !ShowEditor)
{
ctlJournalList.Enabled = true;
}
if (roleInfo.IsPublic && ShowEditor)
{
ctlJournalList.Enabled = true;
}
}
else
{
ShowEditor = false;
ctlJournalList.Enabled = false;
}
}
}
}
if (!String.IsNullOrEmpty(Request.QueryString["userId"]))
{
ctlJournalList.ProfileId = Convert.ToInt32(Request.QueryString["userId"]);
if (!UserInfo.IsSuperUser && !isAdmin && ctlJournalList.ProfileId != UserId)
{
ShowEditor = ShowEditor && AreFriends(UserController.GetUserById(PortalId, ctlJournalList.ProfileId), UserInfo);
}
}
else if (GroupId > 0)
{
ctlJournalList.SocialGroupId = Convert.ToInt32(Request.QueryString["groupId"]);
}
InitializeComponent();
base.OnInit(e);
}
private bool AreFriends(UserInfo profileUser, UserInfo currentUser)
{
var friendsRelationShip = RelationshipController.Instance.GetFriendRelationship(profileUser, currentUser);
return (friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted);
}
private void InitializeComponent() {
Load += Page_Load;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Page_Load runs when the control is loaded
/// </summary>
/// -----------------------------------------------------------------------------
private void Page_Load(object sender, EventArgs e) {
try
{
BaseUrl = Globals.ApplicationPath;
BaseUrl = BaseUrl.EndsWith("/") ? BaseUrl : BaseUrl + "/";
BaseUrl += "DesktopModules/Journal/";
ProfilePage = Common.Globals.NavigateURL(PortalSettings.UserTabId, string.Empty, new[] {"userId=xxx"});
if (!String.IsNullOrEmpty(Request.QueryString["userId"]))
{
Pid = Convert.ToInt32(Request.QueryString["userId"]);
ctlJournalList.ProfileId = Pid;
}
else if (GroupId > 0)
{
Gid = GroupId;
ctlJournalList.SocialGroupId = GroupId;
}
ctlJournalList.PageSize = PageSize;
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#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.Globalization;
using System.Threading;
using Xunit;
namespace System.Tests
{
public static class DateTimeOffsetTests
{
[Fact]
public static void MaxValue()
{
VerifyDateTimeOffset(DateTimeOffset.MaxValue, 9999, 12, 31, 23, 59, 59, 999, TimeSpan.Zero);
}
[Fact]
public static void MinValue()
{
VerifyDateTimeOffset(DateTimeOffset.MinValue, 1, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
}
[Fact]
public static void Ctor_Empty()
{
VerifyDateTimeOffset(new DateTimeOffset(), 1, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
VerifyDateTimeOffset(default(DateTimeOffset), 1, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
}
[Fact]
public static void Ctor_DateTime()
{
var dateTimeOffset = new DateTimeOffset(new DateTime(2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Utc));
VerifyDateTimeOffset(dateTimeOffset, 2012, 6, 11, 0, 0, 0, 0, TimeSpan.Zero);
dateTimeOffset = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 4, DateTimeKind.Local));
VerifyDateTimeOffset(dateTimeOffset, 1986, 8, 15, 10, 20, 5, 4, null);
DateTimeOffset today = new DateTimeOffset(DateTime.Today);
DateTimeOffset now = DateTimeOffset.Now;
VerifyDateTimeOffset(today, now.Year, now.Month, now.Day, 0, 0, 0, 0, now.Offset);
today = new DateTimeOffset(new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc));
Assert.Equal(TimeSpan.Zero, today.Offset);
Assert.False(today.UtcDateTime.IsDaylightSavingTime());
}
[Fact]
public static void Ctor_DateTime_Invalid()
{
// DateTime < DateTimeOffset.MinValue
DateTimeOffset min = DateTimeOffset.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year - 1, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month - 1, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day - 1, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour - 1, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute - 1, min.Second, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second - 1, min.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond - 1, DateTimeKind.Utc)));
// DateTime > DateTimeOffset.MaxValue
DateTimeOffset max = DateTimeOffset.MaxValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year + 1, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month + 1, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day + 1, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour + 1, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute + 1, max.Second, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second + 1, max.Millisecond, DateTimeKind.Utc)));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond + 1, DateTimeKind.Utc)));
}
[Fact]
public static void Ctor_DateTime_TimeSpan()
{
var dateTimeOffset = new DateTimeOffset(DateTime.MinValue, TimeSpan.FromHours(-14));
VerifyDateTimeOffset(dateTimeOffset, 1, 1, 1, 0, 0, 0, 0, TimeSpan.FromHours(-14));
dateTimeOffset = new DateTimeOffset(DateTime.MaxValue, TimeSpan.FromHours(14));
VerifyDateTimeOffset(dateTimeOffset, 9999, 12, 31, 23, 59, 59, 999, TimeSpan.FromHours(14));
dateTimeOffset = new DateTimeOffset(new DateTime(2012, 12, 31, 13, 50, 10), TimeSpan.Zero);
VerifyDateTimeOffset(dateTimeOffset, 2012, 12, 31, 13, 50, 10, 0, TimeSpan.Zero);
}
[Fact]
public static void Ctor_DateTime_TimeSpan_Invalid()
{
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(15))); // Local time and non timezone timespan
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(-15))); // Local time and non timezone timespan
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, TimeSpan.FromHours(1))); // Local time and non zero timespan
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0, 0, 0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0, 0, 0, 0, -3))); // TimeSpan is not whole minutes
// DateTime < DateTimeOffset.MinValue
DateTimeOffset min = DateTimeOffset.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year - 1, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month - 1, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day - 1, min.Hour, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour - 1, min.Minute, min.Second, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute - 1, min.Second, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second - 1, min.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(new DateTime(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond - 1, DateTimeKind.Utc), TimeSpan.Zero));
// DateTime > DateTimeOffset.MaxValue
DateTimeOffset max = DateTimeOffset.MaxValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year + 1, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month + 1, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day + 1, max.Hour, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour + 1, max.Minute, max.Second, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute + 1, max.Second, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second + 1, max.Millisecond, DateTimeKind.Utc), TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(new DateTime(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond + 1, DateTimeKind.Utc), TimeSpan.Zero));
// Invalid offset
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.Now, TimeSpan.FromTicks(1)));
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(DateTime.UtcNow, TimeSpan.FromTicks(1)));
}
[Fact]
public static void Ctor_Long_TimeSpan()
{
var expected = new DateTime(1, 2, 3, 4, 5, 6, 7);
var dateTimeOffset = new DateTimeOffset(expected.Ticks, TimeSpan.Zero);
VerifyDateTimeOffset(dateTimeOffset, dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, dateTimeOffset.Hour, dateTimeOffset.Minute, dateTimeOffset.Second, dateTimeOffset.Millisecond, TimeSpan.Zero);
}
[Fact]
public static void Ctor_Long_TimeSpan_Invalid()
{
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(0, new TimeSpan(0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(0, new TimeSpan(0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(0, new TimeSpan(0, 0, 0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(0, new TimeSpan(0, 0, 0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(0, TimeSpan.FromHours(-15))); // TimeZone.Offset > 14
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(0, TimeSpan.FromHours(15))); // TimeZone.Offset < -14
Assert.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTimeOffset(DateTimeOffset.MinValue.Ticks - 1, TimeSpan.Zero)); // Ticks < DateTimeOffset.MinValue.Ticks
Assert.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTimeOffset(DateTimeOffset.MaxValue.Ticks + 1, TimeSpan.Zero)); // Ticks > DateTimeOffset.MaxValue.Ticks
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_TimeSpan()
{
var dateTimeOffset = new DateTimeOffset(1973, 10, 6, 14, 30, 0, 500, TimeSpan.Zero);
VerifyDateTimeOffset(dateTimeOffset, 1973, 10, 6, 14, 30, 0, 500, TimeSpan.Zero);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_TimeSpan_Invalid()
{
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, TimeSpan.FromHours(-15))); // TimeZone.Offset > 14
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1, TimeSpan.FromHours(15))); // TimeZone.Offset < -14
// Invalid DateTime
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(0, 1, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Year < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(10000, 1, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Year > 9999
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 0, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Month < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 13, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Motnh > 23
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 0, 1, 1, 1, 1, TimeSpan.Zero)); // Day < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 32, 1, 1, 1, 1, TimeSpan.Zero)); // Day > days in month
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, -1, 1, 1, 1, TimeSpan.Zero)); // Hour < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 24, 1, 1, 1, TimeSpan.Zero)); // Hour > 23
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, -1, 1, 1, TimeSpan.Zero)); // Minute < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 60, 1, 1, TimeSpan.Zero)); // Minute > 59
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 1, -1, 1, TimeSpan.Zero)); // Second < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 1, 60, 1, TimeSpan.Zero)); // Second > 59
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, -1, TimeSpan.Zero)); // Millisecond < 0
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, 1000, TimeSpan.Zero)); // Millisecond > 999
// DateTime < DateTimeOffset.MinValue
DateTimeOffset min = DateTimeOffset.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year - 1, min.Month, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month - 1, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day - 1, min.Hour, min.Minute, min.Second, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour - 1, min.Minute, min.Second, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour, min.Minute - 1, min.Second, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second - 1, min.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second, min.Millisecond - 1, TimeSpan.Zero));
// DateTime > DateTimeOffset.MaxValue
DateTimeOffset max = DateTimeOffset.MaxValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year + 1, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month + 1, max.Day + 1, max.Hour, max.Minute, max.Second, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day + 1, max.Hour, max.Minute, max.Second, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour + 1, max.Minute, max.Second, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour, max.Minute + 1, max.Second, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second + 1, max.Millisecond, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second, max.Millisecond + 1, TimeSpan.Zero));
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_TimeSpan()
{
var dateTimeOffset = new DateTimeOffset(1973, 10, 6, 14, 30, 0, TimeSpan.Zero);
VerifyDateTimeOffset(dateTimeOffset, 1973, 10, 6, 14, 30, 0, 0, TimeSpan.Zero);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_TimeSpan_Invalid()
{
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 0, 0, 3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, new TimeSpan(0, 0, 0, 0, -3))); // TimeSpan is not whole minutes
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, TimeSpan.FromHours(-15))); // TimeZone.Offset > 14
Assert.Throws<ArgumentOutOfRangeException>("offset", () => new DateTimeOffset(1, 1, 1, 1, 1, 1, TimeSpan.FromHours(15))); // TimeZone.Offset < -14
// Invalid DateTime
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(0, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Year < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(10000, 1, 1, 1, 1, 1, TimeSpan.Zero)); // Year > 9999
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 0, 1, 1, 1, 1, TimeSpan.Zero)); // Month < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 13, 1, 1, 1, 1, TimeSpan.Zero)); // Month > 23
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 0, 1, 1, 1, TimeSpan.Zero)); // Day < 1
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 32, 1, 1, 1, TimeSpan.Zero)); // Day > days in month
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, -1, 1, 1, TimeSpan.Zero)); // Hour < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 24, 1, 1, TimeSpan.Zero)); // Hour > 23
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, -1, 1, TimeSpan.Zero)); // Minute < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 60, 1, TimeSpan.Zero)); // Minute > 59
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 1, -1, TimeSpan.Zero)); // Second < 0
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(1, 1, 1, 1, 1, 60, TimeSpan.Zero)); // Second > 59
// DateTime < DateTimeOffset.MinValue
DateTimeOffset min = DateTimeOffset.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year - 1, min.Month, min.Day, min.Hour, min.Minute, min.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month - 1, min.Day, min.Hour, min.Minute, min.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day - 1, min.Hour, min.Minute, min.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour - 1, min.Minute, min.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour, min.Minute - 1, min.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(min.Year, min.Month, min.Day, min.Hour, min.Minute, min.Second - 1, TimeSpan.Zero));
// DateTime > DateTimeOffset.MaxValue
DateTimeOffset max = DateTimeOffset.MaxValue;
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year + 1, max.Month, max.Day, max.Hour, max.Minute, max.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month + 1, max.Day + 1, max.Hour, max.Minute, max.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day + 1, max.Hour, max.Minute, max.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour + 1, max.Minute, max.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour, max.Minute + 1, max.Second, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>(null, () => new DateTimeOffset(max.Year, max.Month, max.Day, max.Hour, max.Minute, max.Second + 1, TimeSpan.Zero));
}
[Fact]
public static void ImplicitCast_DateTime()
{
DateTime dateTime = new DateTime(2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Utc);
DateTimeOffset dateTimeOffset = dateTime;
VerifyDateTimeOffset(dateTimeOffset, 2012, 6, 11, 0, 0, 0, 0, TimeSpan.Zero);
}
[Fact]
public static void AddSubtract_TimeSpan()
{
var dateTimeOffset = new DateTimeOffset(new DateTime(2012, 6, 18, 10, 5, 1, 0));
TimeSpan timeSpan = dateTimeOffset.TimeOfDay;
DateTimeOffset newDate = dateTimeOffset.Subtract(timeSpan);
Assert.Equal(new DateTimeOffset(new DateTime(2012, 6, 18, 0, 0, 0, 0)).Ticks, newDate.Ticks);
Assert.Equal(dateTimeOffset.Ticks, newDate.Add(timeSpan).Ticks);
}
public static IEnumerable<object[]> Subtract_TimeSpan_TestData()
{
var dateTimeOffset = new DateTimeOffset(new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc));
yield return new object[] { dateTimeOffset, new TimeSpan(10, 5, 1), new DateTimeOffset(new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc)) };
yield return new object[] { dateTimeOffset, new TimeSpan(-10, -5, -1), new DateTimeOffset(new DateTime(2012, 6, 18, 20, 10, 2, 0, DateTimeKind.Utc)) };
}
[Theory]
[MemberData(nameof(Subtract_TimeSpan_TestData))]
public static void Subtract_TimeSpan(DateTimeOffset dt, TimeSpan ts, DateTimeOffset expected)
{
Assert.Equal(expected, dt - ts);
Assert.Equal(expected, dt.Subtract(ts));
}
public static IEnumerable<object[]> Subtract_DateTimeOffset_TestData()
{
var dateTimeOffset1 = new DateTimeOffset(new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc));
var dateTimeOffset2 = new DateTimeOffset(new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc));
var dateTimeOffset3 = new DateTimeOffset(new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc));
yield return new object[] { dateTimeOffset2, dateTimeOffset1, new TimeSpan(185, 14, 47, 0) };
yield return new object[] { dateTimeOffset1, dateTimeOffset2, new TimeSpan(-185, -14, -47, 0) };
yield return new object[] { dateTimeOffset1, dateTimeOffset2, new TimeSpan(-185, -14, -47, 0) };
}
[Theory]
[MemberData(nameof(Subtract_DateTimeOffset_TestData))]
public static void Subtract_DateTimeOffset(DateTimeOffset dt1, DateTimeOffset dt2, TimeSpan expected)
{
Assert.Equal(expected, dt1 - dt2);
Assert.Equal(expected, dt1.Subtract(dt2));
}
public static IEnumerable<object[]> Add_TimeSpan_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1000)), new TimeSpan(10), new DateTimeOffset(new DateTime(1010)) };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), TimeSpan.Zero, new DateTimeOffset(new DateTime(1000)) };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), new TimeSpan(-10), new DateTimeOffset(new DateTime(990)) };
}
[Theory]
[MemberData(nameof(Add_TimeSpan_TestData))]
public static void Add_TimeSpan(DateTimeOffset dateTimeOffset, TimeSpan timeSpan, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.Add(timeSpan));
Assert.Equal(expected, dateTimeOffset + timeSpan);
}
[Fact]
public static void Add_TimeSpan_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.Add(TimeSpan.FromTicks(-1)));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.Add(TimeSpan.FromTicks(11)));
}
public static IEnumerable<object[]> AddYears_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 10, new DateTimeOffset(new DateTime(1996, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -10, new DateTimeOffset(new DateTime(1976, 8, 15, 10, 20, 5, 70)) };
}
[Theory]
[MemberData(nameof(AddYears_TestData))]
public static void AddYears(DateTimeOffset dateTimeOffset, int years, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddYears(years));
}
[Fact]
public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("years", () => DateTimeOffset.Now.AddYears(10001));
Assert.Throws<ArgumentOutOfRangeException>("years", () => DateTimeOffset.Now.AddYears(-10001));
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MaxValue.AddYears(1));
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MinValue.AddYears(-1));
}
public static IEnumerable<object[]> AddMonths_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 2, new DateTimeOffset(new DateTime(1986, 10, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -2, new DateTimeOffset(new DateTime(1986, 6, 15, 10, 20, 5, 70)) };
}
[Theory]
[MemberData(nameof(AddMonths_TestData))]
public static void AddMonths(DateTimeOffset dateTimeOffset, int months, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddMonths(months));
}
[Fact]
public static void AddMonths_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.Now.AddMonths(120001));
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.Now.AddMonths(-120001));
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MaxValue.AddMonths(1));
Assert.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MinValue.AddMonths(-1));
}
public static IEnumerable<object[]> AddDays_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 2, new DateTimeOffset(new DateTime(1986, 8, 17, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -2, new DateTimeOffset(new DateTime(1986, 8, 13, 10, 20, 5, 70)) };
}
[Theory]
[MemberData(nameof(AddDays_TestData))]
public static void AddDays(DateTimeOffset dateTimeOffset, double days, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddDays(days));
}
[Fact]
public static void AddDays_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddDays(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddDays(-1));
}
public static IEnumerable<object[]> AddHours_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 3, new DateTimeOffset(new DateTime(1986, 8, 15, 13, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -3, new DateTimeOffset(new DateTime(1986, 8, 15, 7, 20, 5, 70)) };
}
[Theory]
[MemberData(nameof(AddHours_TestData))]
public static void AddHours(DateTimeOffset dateTimeOffset, double hours, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddHours(hours));
}
[Fact]
public static void AddHours_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddHours(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddHours(-1));
}
public static IEnumerable<object[]> AddMinutes_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 5, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 25, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -5, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 15, 5, 70)) };
}
[Theory]
[MemberData(nameof(AddMinutes_TestData))]
public static void AddMinutes(DateTimeOffset dateTimeOffset, double minutes, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddMinutes(minutes));
}
[Fact]
public static void AddMinutes_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddMinutes(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddMinutes(-1));
}
public static IEnumerable<object[]> AddSeconds_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 30, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 35, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -3, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 2, 70)) };
}
[Theory]
[MemberData(nameof(AddSeconds_TestData))]
public static void AddSeconds(DateTimeOffset dateTimeOffset, double seconds, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddSeconds(seconds));
}
[Fact]
public static void AddSeconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddSeconds(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddSeconds(-1));
}
public static IEnumerable<object[]> AddMilliseconds_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 10, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 80)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), 0, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)) };
yield return new object[] { new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)), -10, new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 60)) };
}
[Theory]
[MemberData(nameof(AddMilliseconds_TestData))]
public static void AddMilliseconds(DateTimeOffset dateTimeOffset, double milliseconds, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddMilliseconds(milliseconds));
}
[Fact]
public static void AddMilliseconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddMilliseconds(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddMilliseconds(-1));
}
public static IEnumerable<object[]> AddTicks_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1000)), 10, new DateTimeOffset(new DateTime(1010)) };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), 0, new DateTimeOffset(new DateTime(1000)) };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), -10, new DateTimeOffset(new DateTime(990)) };
}
[Theory]
[MemberData(nameof(AddTicks_TestData))]
public static void AddTicks(DateTimeOffset dateTimeOffset, long ticks, DateTimeOffset expected)
{
Assert.Equal(expected, dateTimeOffset.AddTicks(ticks));
}
[Fact]
public static void AddTicks_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MaxValue.AddTicks(1));
Assert.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.MinValue.AddTicks(-1));
}
[Fact]
public static void ToFromFileTime()
{
var today = new DateTimeOffset(DateTime.Today);
long dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTimeOffset.FromFileTime(dateTimeRaw));
}
[Fact]
public static void UtcDateTime()
{
DateTime now = DateTime.Now;
var dateTimeOffset = new DateTimeOffset(now);
Assert.Equal(DateTime.Today, dateTimeOffset.Date);
Assert.Equal(now, dateTimeOffset.DateTime);
Assert.Equal(now.ToUniversalTime(), dateTimeOffset.UtcDateTime);
}
[Fact]
public static void UtcNow()
{
DateTimeOffset start = DateTimeOffset.UtcNow;
Assert.True(
SpinWait.SpinUntil(() => DateTimeOffset.UtcNow > start, TimeSpan.FromSeconds(2)),
"Expected UtcNow to changes");
}
[Fact]
public static void DayOfYear()
{
DateTimeOffset dateTimeOffset = new DateTimeOffset();
Assert.Equal(dateTimeOffset.DateTime.DayOfYear, dateTimeOffset.DayOfYear);
}
[Fact]
public static void DayOfWeekTest()
{
DateTimeOffset dateTimeOffset = new DateTimeOffset();
Assert.Equal(dateTimeOffset.DateTime.DayOfWeek, dateTimeOffset.DayOfWeek);
}
[Fact]
public static void TimeOfDay()
{
DateTimeOffset dateTimeOffset = new DateTimeOffset();
Assert.Equal(dateTimeOffset.DateTime.TimeOfDay, dateTimeOffset.TimeOfDay);
}
private static IEnumerable<object[]> UnixTime_TestData()
{
yield return new object[] { TestTime.FromMilliseconds(DateTimeOffset.MinValue, -62135596800000) };
yield return new object[] { TestTime.FromMilliseconds(DateTimeOffset.MaxValue, 253402300799999) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero), 0) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(2014, 6, 13, 17, 21, 50, TimeSpan.Zero), 1402680110000) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(2830, 12, 15, 1, 23, 45, TimeSpan.Zero), 27169089825000) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(2830, 12, 15, 1, 23, 45, 399, TimeSpan.Zero), 27169089825399) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(9999, 12, 30, 23, 24, 25, TimeSpan.Zero), 253402212265000) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(1907, 7, 7, 7, 7, 7, TimeSpan.Zero), -1971967973000) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(1907, 7, 7, 7, 7, 7, 1, TimeSpan.Zero), -1971967972999) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(1907, 7, 7, 7, 7, 7, 777, TimeSpan.Zero), -1971967972223) };
yield return new object[] { TestTime.FromMilliseconds(new DateTimeOffset(601636288270011234, TimeSpan.Zero), -1971967972999) };
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void ToUnixTimeMilliseconds(TestTime test)
{
long expectedMilliseconds = test.UnixTimeMilliseconds;
long actualMilliseconds = test.DateTimeOffset.ToUnixTimeMilliseconds();
Assert.Equal(expectedMilliseconds, actualMilliseconds);
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void ToUnixTimeMilliseconds_RoundTrip(TestTime test)
{
long unixTimeMilliseconds = test.DateTimeOffset.ToUnixTimeMilliseconds();
FromUnixTimeMilliseconds(TestTime.FromMilliseconds(test.DateTimeOffset, unixTimeMilliseconds));
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void ToUnixTimeSeconds(TestTime test)
{
long expectedSeconds = test.UnixTimeSeconds;
long actualSeconds = test.DateTimeOffset.ToUnixTimeSeconds();
Assert.Equal(expectedSeconds, actualSeconds);
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void oUnixTimeSeconds_RoundTrip(TestTime test)
{
long unixTimeSeconds = test.DateTimeOffset.ToUnixTimeSeconds();
FromUnixTimeSeconds(TestTime.FromSeconds(test.DateTimeOffset, unixTimeSeconds));
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void FromUnixTimeMilliseconds(TestTime test)
{
// Only assert that expected == actual up to millisecond precision for conversion from milliseconds
long expectedTicks = (test.DateTimeOffset.UtcTicks / TimeSpan.TicksPerMillisecond) * TimeSpan.TicksPerMillisecond;
long actualTicks = DateTimeOffset.FromUnixTimeMilliseconds(test.UnixTimeMilliseconds).UtcTicks;
Assert.Equal(expectedTicks, actualTicks);
}
[Fact]
public static void FromUnixTimeMilliseconds_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("milliseconds", () => DateTimeOffset.FromUnixTimeMilliseconds(-62135596800001)); // Milliseconds < DateTimeOffset.MinValue
Assert.Throws<ArgumentOutOfRangeException>("milliseconds", () => DateTimeOffset.FromUnixTimeMilliseconds(253402300800000)); // Milliseconds > DateTimeOffset.MaxValue
Assert.Throws<ArgumentOutOfRangeException>("milliseconds", () => DateTimeOffset.FromUnixTimeMilliseconds(long.MinValue)); // Milliseconds < DateTimeOffset.MinValue
Assert.Throws<ArgumentOutOfRangeException>("milliseconds", () => DateTimeOffset.FromUnixTimeMilliseconds(long.MaxValue)); // Milliseconds > DateTimeOffset.MaxValue
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void FromUnixTimeSeconds(TestTime test)
{
// Only assert that expected == actual up to second precision for conversion from seconds
long expectedTicks = (test.DateTimeOffset.UtcTicks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond;
long actualTicks = DateTimeOffset.FromUnixTimeSeconds(test.UnixTimeSeconds).UtcTicks;
Assert.Equal(expectedTicks, actualTicks);
}
[Fact]
public static void FromUnixTimeSeconds_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("seconds", () => DateTimeOffset.FromUnixTimeSeconds(-62135596801));// Seconds < DateTimeOffset.MinValue
Assert.Throws<ArgumentOutOfRangeException>("seconds", () => DateTimeOffset.FromUnixTimeSeconds(253402300800)); // Seconds > DateTimeOffset.MaxValue
Assert.Throws<ArgumentOutOfRangeException>("seconds", () => DateTimeOffset.FromUnixTimeSeconds(long.MinValue)); // Seconds < DateTimeOffset.MinValue
Assert.Throws<ArgumentOutOfRangeException>("seconds", () => DateTimeOffset.FromUnixTimeSeconds(long.MaxValue)); // Seconds < DateTimeOffset.MinValue
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void FromUnixTimeMilliseconds_RoundTrip(TestTime test)
{
DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeMilliseconds(test.UnixTimeMilliseconds);
ToUnixTimeMilliseconds(TestTime.FromMilliseconds(dateTime, test.UnixTimeMilliseconds));
}
[Theory]
[MemberData(nameof(UnixTime_TestData))]
public static void FromUnixTimeSeconds_RoundTrip(TestTime test)
{
DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeSeconds(test.UnixTimeSeconds);
ToUnixTimeSeconds(TestTime.FromSeconds(dateTime, test.UnixTimeSeconds));
}
[Fact]
public static void ToLocalTime()
{
DateTimeOffset dateTimeOffset = new DateTimeOffset(new DateTime(1000));
Assert.Equal(new DateTimeOffset(dateTimeOffset.UtcDateTime.ToLocalTime()), dateTimeOffset.ToLocalTime());
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { DateTimeOffset.MinValue, DateTimeOffset.MinValue, true, true };
yield return new object[] { DateTimeOffset.MinValue, DateTimeOffset.MaxValue, false, false };
yield return new object[] { DateTimeOffset.Now, new object(), false, false };
yield return new object[] { DateTimeOffset.Now, null, false, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(DateTimeOffset dateTimeOffset1, object obj, bool expectedEquals, bool expectedEqualsExact)
{
Assert.Equal(expectedEquals, dateTimeOffset1.Equals(obj));
if (obj is DateTimeOffset)
{
DateTimeOffset dateTimeOffset2 = (DateTimeOffset)obj;
Assert.Equal(expectedEquals, dateTimeOffset1.Equals(dateTimeOffset2));
Assert.Equal(expectedEquals, DateTimeOffset.Equals(dateTimeOffset1, dateTimeOffset2));
Assert.Equal(expectedEquals, dateTimeOffset1.GetHashCode().Equals(dateTimeOffset2.GetHashCode()));
Assert.Equal(expectedEqualsExact, dateTimeOffset1.EqualsExact(dateTimeOffset2));
Assert.Equal(expectedEquals, dateTimeOffset1 == dateTimeOffset2);
Assert.Equal(!expectedEquals, dateTimeOffset1 != dateTimeOffset2);
}
}
public static IEnumerable<object[]> Compare_TestData()
{
yield return new object[] { new DateTimeOffset(new DateTime(1000)), new DateTimeOffset(new DateTime(1000)), 0 };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), new DateTimeOffset(new DateTime(1001)), -1 };
yield return new object[] { new DateTimeOffset(new DateTime(1000)), new DateTimeOffset(new DateTime(999)), 1 };
}
[Theory]
[MemberData(nameof(Compare_TestData))]
public static void Compare(DateTimeOffset dateTimeOffset1, DateTimeOffset dateTimeOffset2, int expected)
{
Assert.Equal(expected, Math.Sign(dateTimeOffset1.CompareTo(dateTimeOffset2)));
Assert.Equal(expected, Math.Sign(DateTimeOffset.Compare(dateTimeOffset1, dateTimeOffset2)));
IComparable comparable = dateTimeOffset1;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(dateTimeOffset2)));
if (expected > 0)
{
Assert.True(dateTimeOffset1 > dateTimeOffset2);
Assert.Equal(expected >= 0, dateTimeOffset1 >= dateTimeOffset2);
Assert.False(dateTimeOffset1 < dateTimeOffset2);
Assert.Equal(expected == 0, dateTimeOffset1 <= dateTimeOffset2);
}
else if (expected < 0)
{
Assert.False(dateTimeOffset1 > dateTimeOffset2);
Assert.Equal(expected == 0, dateTimeOffset1 >= dateTimeOffset2);
Assert.True(dateTimeOffset1 < dateTimeOffset2);
Assert.Equal(expected <= 0, dateTimeOffset1 <= dateTimeOffset2);
}
else if (expected == 0)
{
Assert.False(dateTimeOffset1 > dateTimeOffset2);
Assert.True(dateTimeOffset1 >= dateTimeOffset2);
Assert.False(dateTimeOffset1 < dateTimeOffset2);
Assert.True(dateTimeOffset1 <= dateTimeOffset2);
}
}
[Fact]
public static void Parse_String()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString();
DateTimeOffset result = DateTimeOffset.Parse(expectedString);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString();
DateTimeOffset result = DateTimeOffset.Parse(expectedString, null);
Assert.Equal(expectedString, result.ToString((IFormatProvider)null));
}
[Fact]
public static void Parse_String_FormatProvider_DateTimeStyles()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString();
DateTimeOffset result = DateTimeOffset.Parse(expectedString, null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_Japanese()
{
var expected = new DateTimeOffset(new DateTime(2012, 12, 21, 10, 8, 6));
var cultureInfo = new CultureInfo("ja-JP");
string expectedString = string.Format(cultureInfo, "{0}", expected);
Assert.Equal(expected, DateTimeOffset.Parse(expectedString, cultureInfo));
}
[Fact]
public static void TryParse_String()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("u");
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParse(expectedString, out result));
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_U()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("u");
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParse(expectedString, null, DateTimeStyles.None, out result));
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_G()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("g");
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParse(expectedString, null, DateTimeStyles.AssumeUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_TimeDesignators()
{
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTimeOffset.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
[Fact]
public static void ParseExact_String_String_FormatProvider()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("u");
DateTimeOffset result = DateTimeOffset.ParseExact(expectedString, "u", null);
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_U()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("u");
DateTimeOffset result = DateTimeOffset.ParseExact(expectedString, "u", null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_G()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("g");
DateTimeOffset result = DateTimeOffset.ParseExact(expectedString, "g", null, DateTimeStyles.AssumeUniversal);
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("o");
DateTimeOffset result = DateTimeOffset.ParseExact(expectedString, "o", null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString("o"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider()
{
var formatter = new MyFormatter();
string dateBefore = DateTime.Now.ToString();
DateTimeOffset dateAfter = DateTimeOffset.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AssumeUniversal);
Assert.Equal(dateBefore, dateAfter.DateTime.ToString());
}
[Fact]
public static void ParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTimeOffset result = DateTimeOffset.ParseExact(expectedString, formats, null, DateTimeStyles.AssumeUniversal);
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParseExact_String_String_FormatProvider_DateTimeStyles_NullFormatProvider()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("g");
DateTimeOffset resulted;
Assert.True(DateTimeOffset.TryParseExact(expectedString, "g", null, DateTimeStyles.AssumeUniversal, out resulted));
Assert.Equal(expectedString, resulted.ToString("g"));
}
[Fact]
public static void TryParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTimeOffset expected = DateTimeOffset.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTimeOffset result;
Assert.True(DateTimeOffset.TryParseExact(expectedString, formats, null, DateTimeStyles.AssumeUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Theory]
[InlineData(~(DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.AllowInnerWhite | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind))]
[InlineData(DateTimeStyles.NoCurrentDateDefault)]
public static void Parse_InvalidDateTimeStyle_ThrowsArgumentException(DateTimeStyles style)
{
Assert.Throws<ArgumentException>("styles", () => DateTimeOffset.Parse("06/08/1990", null, style));
Assert.Throws<ArgumentException>("styles", () => DateTimeOffset.ParseExact("06/08/1990", "Y", null, style));
DateTimeOffset dateTimeOffset;
Assert.Throws<ArgumentException>("styles", () => DateTimeOffset.TryParse("06/08/1990", null, style, out dateTimeOffset));
Assert.Equal(default(DateTimeOffset), dateTimeOffset);
Assert.Throws<ArgumentException>("styles", () => DateTimeOffset.TryParseExact("06/08/1990", "Y", null, style, out dateTimeOffset));
Assert.Equal(default(DateTimeOffset), dateTimeOffset);
}
private static void VerifyDateTimeOffset(DateTimeOffset dateTimeOffset, int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan? offset)
{
Assert.Equal(year, dateTimeOffset.Year);
Assert.Equal(month, dateTimeOffset.Month);
Assert.Equal(day, dateTimeOffset.Day);
Assert.Equal(hour, dateTimeOffset.Hour);
Assert.Equal(minute, dateTimeOffset.Minute);
Assert.Equal(second, dateTimeOffset.Second);
Assert.Equal(millisecond, dateTimeOffset.Millisecond);
if (offset.HasValue)
{
Assert.Equal(offset.Value, dateTimeOffset.Offset);
}
}
private class MyFormatter : IFormatProvider
{
public object GetFormat(Type formatType)
{
return typeof(IFormatProvider) == formatType ? this : null;
}
}
public class TestTime
{
private TestTime(DateTimeOffset dateTimeOffset, long unixTimeMilliseconds, long unixTimeSeconds)
{
DateTimeOffset = dateTimeOffset;
UnixTimeMilliseconds = unixTimeMilliseconds;
UnixTimeSeconds = unixTimeSeconds;
}
public static TestTime FromMilliseconds(DateTimeOffset dateTimeOffset, long unixTimeMilliseconds)
{
long unixTimeSeconds = unixTimeMilliseconds / 1000;
// Always round UnixTimeSeconds down toward 1/1/0001 00:00:00
// (this happens automatically for unixTimeMilliseconds > 0)
bool hasSubSecondPrecision = unixTimeMilliseconds % 1000 != 0;
if (unixTimeMilliseconds < 0 && hasSubSecondPrecision)
{
--unixTimeSeconds;
}
return new TestTime(dateTimeOffset, unixTimeMilliseconds, unixTimeSeconds);
}
public static TestTime FromSeconds(DateTimeOffset dateTimeOffset, long unixTimeSeconds)
{
return new TestTime(dateTimeOffset, unixTimeSeconds * 1000, unixTimeSeconds);
}
public DateTimeOffset DateTimeOffset { get; private set; }
public long UnixTimeMilliseconds { get; private set; }
public long UnixTimeSeconds { get; private set; }
}
}
}
| |
#define TUPLE
#pragma warning disable 162
#pragma warning disable 429
namespace Pathfinding {
/** Binary heap implementation.
* Binary heaps are really fast for ordering nodes in a way that
* makes it possible to get the node with the lowest F score.
* Also known as a priority queue.
*
* This has actually been rewritten as a d-ary heap (by default a 4-ary heap)
* for performance, but it's the same principle.
*
* \see http://en.wikipedia.org/wiki/Binary_heap
* \see https://en.wikipedia.org/wiki/D-ary_heap
*/
public class BinaryHeapM {
/** Number of items in the tree */
public int numberOfItems;
/** The tree will grow by at least this factor every time it is expanded */
public float growthFactor = 2;
/**
* Number of children of each node in the tree.
* Different values have been tested and 4 has been empirically found to perform the best.
* \see https://en.wikipedia.org/wiki/D-ary_heap
*/
const int D = 4;
/** Sort nodes by G score if there is a tie when comparing the F score */
const bool SortGScores = true;
/** Internal backing array for the tree */
private Tuple[] binaryHeap;
private struct Tuple {
public uint F;
public PathNode node;
public Tuple ( uint f, PathNode node ) {
this.F = f;
this.node = node;
}
}
public BinaryHeapM ( int numberOfElements ) {
binaryHeap = new Tuple[numberOfElements];
numberOfItems = 0;
}
public void Clear () {
numberOfItems = 0;
}
internal PathNode GetNode (int i) {
return binaryHeap[i].node;
}
internal void SetF (int i, uint f) {
binaryHeap[i].F = f;
}
/** Adds a node to the heap */
public void Add(PathNode node) {
if (node == null) throw new System.ArgumentNullException ("node");
if (numberOfItems == binaryHeap.Length) {
int newSize = System.Math.Max(binaryHeap.Length+4,(int)System.Math.Round(binaryHeap.Length*growthFactor));
if (newSize > 1<<18) {
throw new System.Exception ("Binary Heap Size really large (2^18). A heap size this large is probably the cause of pathfinding running in an infinite loop. " +
"\nRemove this check (in BinaryHeap.cs) if you are sure that it is not caused by a bug");
}
var tmp = new Tuple[newSize];
for (int i=0;i<binaryHeap.Length;i++) {
tmp[i] = binaryHeap[i];
}
binaryHeap = tmp;
}
var obj = new Tuple(node.F,node);
binaryHeap[numberOfItems] = obj;
int bubbleIndex = numberOfItems;
uint nodeF = node.F;
uint nodeG = node.G;
while (bubbleIndex != 0 ) {
int parentIndex = (bubbleIndex-1) / D;
if (nodeF < binaryHeap[parentIndex].F || (nodeF == binaryHeap[parentIndex].F && nodeG > binaryHeap[parentIndex].node.G)) {
binaryHeap[bubbleIndex] = binaryHeap[parentIndex];
binaryHeap[parentIndex] = obj;
bubbleIndex = parentIndex;
} else {
break;
}
}
numberOfItems++;
}
/** Returns the node with the lowest F score from the heap */
public PathNode Remove() {
numberOfItems--;
PathNode returnItem = binaryHeap[0].node;
binaryHeap[0] = binaryHeap[numberOfItems];
int swapItem = 0, parent;
do {
if (D == 0) {
parent = swapItem;
int p2 = parent * D;
if (p2 + 1 <= numberOfItems) {
// Both children exist
if (binaryHeap[parent].F > binaryHeap[p2].F) {
swapItem = p2;//2 * parent;
}
if (binaryHeap[swapItem].F > binaryHeap[p2 + 1].F) {
swapItem = p2 + 1;
}
} else if ((p2) <= numberOfItems) {
// Only one child exists
if (binaryHeap[parent].F > binaryHeap[p2].F) {
swapItem = p2;
}
}
} else {
parent = swapItem;
uint swapF = binaryHeap[swapItem].F;
int pd = parent * D + 1;
if (D >= 1 && pd+0 <= numberOfItems && (binaryHeap[pd+0].F < swapF || (SortGScores && binaryHeap[pd+0].F == swapF && binaryHeap[pd+0].node.G < binaryHeap[swapItem].node.G))) {
swapF = binaryHeap[pd+0].F;
swapItem = pd+0;
}
if (D >= 2 && pd+1 <= numberOfItems && (binaryHeap[pd+1].F < swapF || (SortGScores && binaryHeap[pd+1].F == swapF && binaryHeap[pd+1].node.G < binaryHeap[swapItem].node.G))) {
swapF = binaryHeap[pd+1].F;
swapItem = pd+1;
}
if (D >= 3 && pd+2 <= numberOfItems && (binaryHeap[pd+2].F < swapF || (SortGScores && binaryHeap[pd+2].F == swapF && binaryHeap[pd+2].node.G < binaryHeap[swapItem].node.G))) {
swapF = binaryHeap[pd+2].F;
swapItem = pd+2;
}
if (D >= 4 && pd+3 <= numberOfItems && (binaryHeap[pd+3].F < swapF || (SortGScores && binaryHeap[pd+3].F == swapF && binaryHeap[pd+3].node.G < binaryHeap[swapItem].node.G))) {
swapF = binaryHeap[pd+3].F;
swapItem = pd+3;
}
if (D >= 5 && pd+4 <= numberOfItems && binaryHeap[pd+4].F < swapF ) {
swapF = binaryHeap[pd+4].F;
swapItem = pd+4;
}
if (D >= 6 && pd+5 <= numberOfItems && binaryHeap[pd+5].F < swapF ) {
swapF = binaryHeap[pd+5].F;
swapItem = pd+5;
}
if (D >= 7 && pd+6 <= numberOfItems && binaryHeap[pd+6].F < swapF ) {
swapF = binaryHeap[pd+6].F;
swapItem = pd+6;
}
if (D >= 8 && pd+7 <= numberOfItems && binaryHeap[pd+7].F < swapF ) {
swapF = binaryHeap[pd+7].F;
swapItem = pd+7;
}
if (D >= 9 && pd+8 <= numberOfItems && binaryHeap[pd+8].F < swapF ) {
swapF = binaryHeap[pd+8].F;
swapItem = pd+8;
}
}
// One if the parent's children are smaller or equal, swap them
if (parent != swapItem) {
var tmpIndex = binaryHeap[parent];
binaryHeap[parent] = binaryHeap[swapItem];
binaryHeap[swapItem] = tmpIndex;
} else {
break;
}
} while (true);
//Validate ();
return returnItem;
}
void Validate () {
for ( int i = 1; i < numberOfItems; i++ ) {
int parentIndex = (i-1)/D;
if ( binaryHeap[parentIndex].F > binaryHeap[i].F ) {
throw new System.Exception ("Invalid state at " + i + ":" + parentIndex + " ( " + binaryHeap[parentIndex].F + " > " + binaryHeap[i].F + " ) " );
}
}
}
/** Rebuilds the heap by trickeling down all items.
* Usually called after the hTarget on a path has been changed */
public void Rebuild () {
for (int i=2;i<numberOfItems;i++) {
int bubbleIndex = i;
var node = binaryHeap[i];
uint nodeF = node.F;
while (bubbleIndex != 1) {
int parentIndex = bubbleIndex / D;
if (nodeF < binaryHeap[parentIndex].F) {
//Node tmpValue = binaryHeap[parentIndex];
binaryHeap[bubbleIndex] = binaryHeap[parentIndex];
binaryHeap[parentIndex] = node;
bubbleIndex = parentIndex;
} else {
break;
}
}
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////
///
/// NewScriptGenerator.cs
///
/// (c)2013 Kim, Hyoun Woo
///
///////////////////////////////////////////////////////////////////////////////
using System;
using UnityEngine;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Globalization;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class NewScriptGenerator
{
private const int kCommentWrapLength = 35;
private TextWriter m_Writer;
private string m_Text;
private ScriptPrescription m_ScriptPrescription;
private string m_Indentation;
private int m_IndentLevel = 0;
private int IndentLevel
{
get
{
return m_IndentLevel;
}
set
{
m_IndentLevel = value;
m_Indentation = String.Empty;
for (int i=0; i<m_IndentLevel; i++)
m_Indentation += " ";
}
}
private string ClassName
{
get
{
if (m_ScriptPrescription.className != string.Empty)
return m_ScriptPrescription.className;
return "Example";
}
}
private string WorkSheetClassName
{
get
{
if (m_ScriptPrescription.worksheetClassName != string.Empty)
return m_ScriptPrescription.worksheetClassName;
return "Empty_WorkSheetClass_Name";
}
}
private string DataClassName
{
get
{
if (m_ScriptPrescription.dataClassName != string.Empty)
return m_ScriptPrescription.dataClassName;
return "Empty_DataClass_Name";
}
}
private string AssetFileCreateFuncName
{
get
{
if (m_ScriptPrescription.assetFileCreateFuncName != string.Empty)
return m_ScriptPrescription.assetFileCreateFuncName;
return "Empty_AssetFileCreateFunc_Name";
}
}
private string ImportedFilePath
{
get
{
if (m_ScriptPrescription.importedFilePath != string.Empty)
return m_ScriptPrescription.importedFilePath;
return "Empty_FilePath";
}
}
private string AssetFilePath
{
get
{
if (m_ScriptPrescription.assetFilepath != string.Empty)
return m_ScriptPrescription.assetFilepath;
return "Empty_AssetFilePath";
}
}
private string AssetPostprocessorClass
{
get
{
if (m_ScriptPrescription.assetPostprocessorClass != String.Empty)
return m_ScriptPrescription.assetPostprocessorClass;
return "Empty_AssetPostprocessorClass";
}
}
public NewScriptGenerator (ScriptPrescription scriptPrescription)
{
m_ScriptPrescription = scriptPrescription;
}
/// <summary>
/// Replace markdown keywords in the template text file which is currently read in.
/// </summary>
public override string ToString ()
{
m_Text = m_ScriptPrescription.template;
m_Writer = new StringWriter ();
m_Writer.NewLine = "\n";
// Make sure all line endings are Unix (Mac OS X) format
m_Text = Regex.Replace (m_Text, @"\r\n?", delegate(Match m) { return "\n"; });
// Class Name
m_Text = m_Text.Replace ("$ClassName", ClassName);
m_Text = m_Text.Replace ("$WorkSheetClassName", WorkSheetClassName);
m_Text = m_Text.Replace ("$DataClassName", DataClassName);
m_Text = m_Text.Replace ("$AssetFileCreateFuncName", AssetFileCreateFuncName);
m_Text = m_Text.Replace ("$AssetPostprocessorClass", AssetPostprocessorClass);
m_Text = m_Text.Replace ("$IMPORT_PATH", ImportedFilePath);
m_Text = m_Text.Replace ("$ASSET_PATH", AssetFilePath);
// Other replacements
foreach (KeyValuePair<string, string> kvp in m_ScriptPrescription.m_StringReplacements)
m_Text = m_Text.Replace (kvp.Key, kvp.Value);
// Do not change tabs to spcaes of the .txt template files.
Match match = Regex.Match (m_Text, @"(\t*)\$MemberFields");
if (match.Success)
{
// Set indent level to number of tabs before $Functions keyword
IndentLevel = match.Groups[1].Value.Length;
if (m_ScriptPrescription.memberFields != null)
{
foreach(var field in m_ScriptPrescription.memberFields)
{
WriteMemberField(field);
WriteBlankLine();
WriteProperty(field);
WriteBlankLine();
}
m_Text = m_Text.Replace (match.Value + "\n", m_Writer.ToString ());
}
}
// Return the text of the script
return m_Text;
}
private void PutCurveBracesOnNewLine ()
{
m_Text = Regex.Replace (m_Text, @"(\t*)(.*) {\n((\t*)\n(\t*))?", delegate(Match match)
{
return match.Groups[1].Value + match.Groups[2].Value + "\n" + match.Groups[1].Value + "{\n" +
(match.Groups[4].Value == match.Groups[5].Value ? match.Groups[4].Value : match.Groups[3].Value);
});
}
///
/// Write a member field of a data class.
///
private void WriteMemberField(MemberFieldData field)
{
m_Writer.WriteLine (m_Indentation + "[SerializeField]");
string tmp;
if (field.type == CellType.Enum)
tmp = field.Name + " " + field.Name.ToLower() + ";";
else
{
if (field.IsArrayType)
tmp = field.Type + "[]" + " " + field.Name.ToLower() + " = new " + field.Type + "[0]" +";";
else
tmp = field.Type + " " + field.Name.ToLower() + ";";
}
m_Writer.WriteLine (m_Indentation + tmp);
}
///
/// Write a property of a data class.
///
private void WriteProperty(MemberFieldData field)
{
TextInfo ti = new CultureInfo("en-US",false).TextInfo;
m_Writer.WriteLine (m_Indentation + "[ExposeProperty]");
string tmp = string.Empty;
if (field.type == CellType.Enum)
tmp += "public " + field.Name + " " + field.Name.ToUpper() + " ";
else
{
if (field.IsArrayType)
tmp += "public " + field.Type + "[]" + " " + ti.ToTitleCase(field.Name) + " ";
else
tmp += "public " + field.Type + " " + ti.ToTitleCase(field.Name) + " ";
}
tmp += "{ get {return " + field.Name.ToLower() + "; } set { " + field.Name.ToLower() + " = value;} }";
m_Writer.WriteLine (m_Indentation + tmp);
}
private void WriteBlankLine ()
{
m_Writer.WriteLine (m_Indentation);
}
private void WriteComment (string comment)
{
int index = 0;
while (true)
{
if (comment.Length <= index + kCommentWrapLength)
{
m_Writer.WriteLine (m_Indentation + "// " + comment.Substring (index));
break;
}
else
{
int wrapIndex = comment.IndexOf (' ', index + kCommentWrapLength);
if (wrapIndex < 0)
{
m_Writer.WriteLine (m_Indentation + "// " + comment.Substring (index));
break;
}
else
{
m_Writer.WriteLine (m_Indentation + "// " + comment.Substring (index, wrapIndex-index));
index = wrapIndex + 1;
}
}
}
}
}
}
| |
// ZipFile.Read.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-05 11:38:59>
//
// ------------------------------------------------------------------
//
// This module defines the methods for Reading zip files.
//
// ------------------------------------------------------------------
//
using System;
using System.IO;
using System.Collections.Generic;
namespace Ionic.Zip
{
/// <summary>
/// A class for collecting the various options that can be used when
/// Reading zip files for extraction or update.
/// </summary>
///
/// <remarks>
/// <para>
/// When reading a zip file, there are several options an
/// application can set, to modify how the file is read, or what
/// the library does while reading. This class collects those
/// options into one container.
/// </para>
///
/// <para>
/// Pass an instance of the <c>ReadOptions</c> class into the
/// <c>ZipFile.Read()</c> method.
/// </para>
///
/// <seealso cref="ZipFile.Read(String, ReadOptions)"/>.
/// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/>.
/// </remarks>
public class ReadOptions
{
/// <summary>
/// An event handler for Read operations. When opening large zip
/// archives, you may want to display a progress bar or other
/// indicator of status progress while reading. This parameter
/// allows you to specify a ReadProgress Event Handler directly.
/// When you call <c>Read()</c>, the progress event is invoked as
/// necessary.
/// </summary>
public EventHandler<ReadProgressEventArgs> ReadProgress { get; set; }
/// <summary>
/// The <c>System.IO.TextWriter</c> to use for writing verbose status messages
/// during operations on the zip archive. A console application may wish to
/// pass <c>System.Console.Out</c> to get messages on the Console. A graphical
/// or headless application may wish to capture the messages in a different
/// <c>TextWriter</c>, such as a <c>System.IO.StringWriter</c>.
/// </summary>
public TextWriter StatusMessageWriter { get; set; }
/// <summary>
/// The <c>System.Text.Encoding</c> to use when reading in the zip archive. Be
/// careful specifying the encoding. If the value you use here is not the same
/// as the Encoding used when the zip archive was created (possibly by a
/// different archiver) you will get unexpected results and possibly exceptions.
/// </summary>
///
/// <seealso cref="ZipFile.ProvisionalAlternateEncoding"/>
///
public System.Text.Encoding @Encoding { get; set; }
}
public partial class ZipFile
{
/// <summary>
/// Reads a zip file archive and returns the instance.
/// </summary>
///
/// <remarks>
/// <para>
/// The stream is read using the default <c>System.Text.Encoding</c>, which is the
/// <c>IBM437</c> codepage.
/// </para>
/// </remarks>
///
/// <exception cref="System.Exception">
/// Thrown if the <c>ZipFile</c> cannot be read. The implementation of this method
/// relies on <c>System.IO.File.OpenRead</c>, which can throw a variety of exceptions,
/// including specific exceptions if a file is not found, an unauthorized access
/// exception, exceptions for poorly formatted filenames, and so on.
/// </exception>
///
/// <param name="fileName">
/// The name of the zip archive to open. This can be a fully-qualified or relative
/// pathname.
/// </param>
///
/// <seealso cref="ZipFile.Read(String, ReadOptions)"/>.
///
/// <returns>The instance read from the zip archive.</returns>
///
public static ZipFile Read(string fileName)
{
return ZipFile.Read(fileName, null, null, null);
}
/// <summary>
/// Reads a zip file archive from the named filesystem file using the
/// specified options.
/// </summary>
///
/// <remarks>
/// <para>
/// This version of the <c>Read()</c> method allows the caller to pass
/// in a <c>TextWriter</c> an <c>Encoding</c>, via an instance of the
/// <c>ReadOptions</c> class. The <c>ZipFile</c> is read in using the
/// specified encoding for entries where UTF-8 encoding is not
/// explicitly specified.
/// </para>
/// </remarks>
///
/// <example>
///
/// <para>
/// This example shows how to read a zip file using the Big-5 Chinese
/// code page (950), and extract each entry in the zip file, while
/// sending status messages out to the Console.
/// </para>
///
/// <para>
/// For this code to work as intended, the zipfile must have been
/// created using the big5 code page (CP950). This is typical, for
/// example, when using WinRar on a machine with CP950 set as the
/// default code page. In that case, the names of entries within the
/// Zip archive will be stored in that code page, and reading the zip
/// archive must be done using that code page. If the application did
/// not use the correct code page in ZipFile.Read(), then names of
/// entries within the zip archive would not be correctly retrieved.
/// </para>
///
/// <code lang="C#">
/// string zipToExtract = "MyArchive.zip";
/// string extractDirectory = "extract";
/// var options = new ReadOptions
/// {
/// StatusMessageWriter = System.Console.Out,
/// Encoding = System.Text.Encoding.GetEncoding(950)
/// };
/// using (ZipFile zip = ZipFile.Read(zipToExtract, options))
/// {
/// foreach (ZipEntry e in zip)
/// {
/// e.Extract(extractDirectory);
/// }
/// }
/// </code>
///
///
/// <code lang="VB">
/// Dim zipToExtract as String = "MyArchive.zip"
/// Dim extractDirectory as String = "extract"
/// Dim options as New ReadOptions
/// options.Encoding = System.Text.Encoding.GetEncoding(950)
/// options.StatusMessageWriter = System.Console.Out
/// Using zip As ZipFile = ZipFile.Read(zipToExtract, options)
/// Dim e As ZipEntry
/// For Each e In zip
/// e.Extract(extractDirectory)
/// Next
/// End Using
/// </code>
/// </example>
///
///
/// <example>
///
/// <para>
/// This example shows how to read a zip file using the default
/// code page, to remove entries that have a modified date before a given threshold,
/// sending status messages out to a <c>StringWriter</c>.
/// </para>
///
/// <code lang="C#">
/// var options = new ReadOptions
/// {
/// StatusMessageWriter = new System.IO.StringWriter()
/// };
/// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options))
/// {
/// var Threshold = new DateTime(2007,7,4);
/// // We cannot remove the entry from the list, within the context of
/// // an enumeration of said list.
/// // So we add the doomed entry to a list to be removed later.
/// // pass 1: mark the entries for removal
/// var MarkedEntries = new System.Collections.Generic.List<ZipEntry>();
/// foreach (ZipEntry e in zip)
/// {
/// if (e.LastModified < Threshold)
/// MarkedEntries.Add(e);
/// }
/// // pass 2: actually remove the entry.
/// foreach (ZipEntry zombie in MarkedEntries)
/// zip.RemoveEntry(zombie);
/// zip.Comment = "This archive has been updated.";
/// zip.Save();
/// }
/// // can now use contents of sw, eg store in an audit log
/// </code>
///
/// <code lang="VB">
/// Dim options as New ReadOptions
/// options.StatusMessageWriter = New System.IO.StringWriter
/// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options)
/// Dim Threshold As New DateTime(2007, 7, 4)
/// ' We cannot remove the entry from the list, within the context of
/// ' an enumeration of said list.
/// ' So we add the doomed entry to a list to be removed later.
/// ' pass 1: mark the entries for removal
/// Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry)
/// Dim e As ZipEntry
/// For Each e In zip
/// If (e.LastModified < Threshold) Then
/// MarkedEntries.Add(e)
/// End If
/// Next
/// ' pass 2: actually remove the entry.
/// Dim zombie As ZipEntry
/// For Each zombie In MarkedEntries
/// zip.RemoveEntry(zombie)
/// Next
/// zip.Comment = "This archive has been updated."
/// zip.Save
/// End Using
/// ' can now use contents of sw, eg store in an audit log
/// </code>
/// </example>
///
/// <exception cref="System.Exception">
/// Thrown if the zipfile cannot be read. The implementation of
/// this method relies on <c>System.IO.File.OpenRead</c>, which
/// can throw a variety of exceptions, including specific
/// exceptions if a file is not found, an unauthorized access
/// exception, exceptions for poorly formatted filenames, and so
/// on.
/// </exception>
///
/// <param name="fileName">
/// The name of the zip archive to open.
/// This can be a fully-qualified or relative pathname.
/// </param>
///
/// <param name="options">
/// The set of options to use when reading the zip file.
/// </param>
///
/// <returns>The ZipFile instance read from the zip archive.</returns>
///
/// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/>
///
public static ZipFile Read(string fileName,
ReadOptions options)
{
if (options == null)
throw new ArgumentNullException("options");
return Read(fileName,
options.StatusMessageWriter,
options.Encoding,
options.ReadProgress);
}
/// <summary>
/// Reads a zip file archive using the specified text encoding, the specified
/// TextWriter for status messages, and the specified ReadProgress event handler,
/// and returns the instance.
/// </summary>
///
/// <param name="fileName">
/// The name of the zip archive to open.
/// This can be a fully-qualified or relative pathname.
/// </param>
///
/// <param name="readProgress">
/// An event handler for Read operations.
/// </param>
///
/// <param name="statusMessageWriter">
/// The <c>System.IO.TextWriter</c> to use for writing verbose status messages
/// during operations on the zip archive. A console application may wish to
/// pass <c>System.Console.Out</c> to get messages on the Console. A graphical
/// or headless application may wish to capture the messages in a different
/// <c>TextWriter</c>, such as a <c>System.IO.StringWriter</c>.
/// </param>
///
/// <param name="encoding">
/// The <c>System.Text.Encoding</c> to use when reading in the zip archive. Be
/// careful specifying the encoding. If the value you use here is not the same
/// as the Encoding used when the zip archive was created (possibly by a
/// different archiver) you will get unexpected results and possibly exceptions.
/// </param>
///
/// <returns>The instance read from the zip archive.</returns>
///
private static ZipFile Read(string fileName,
TextWriter statusMessageWriter,
System.Text.Encoding encoding,
EventHandler<ReadProgressEventArgs> readProgress)
{
ZipFile zf = new ZipFile();
zf.AlternateEncoding = encoding ?? DefaultEncoding;
zf.AlternateEncodingUsage = ZipOption.Always;
zf._StatusMessageTextWriter = statusMessageWriter;
zf._name = fileName;
if (readProgress != null)
zf.ReadProgress = readProgress;
if (zf.Verbose) zf._StatusMessageTextWriter.WriteLine("reading from {0}...", fileName);
ReadIntoInstance(zf);
zf._fileAlreadyExists = true;
return zf;
}
/// <summary>
/// Reads a zip archive from a stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When reading from a file, it's probably easier to just use
/// <see cref="ZipFile.Read(String,
/// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This
/// overload is useful when when the zip archive content is
/// available from an already-open stream. The stream must be
/// open and readable and seekable when calling this method. The
/// stream is left open when the reading is completed.
/// </para>
///
/// <para>
/// Using this overload, the stream is read using the default
/// <c>System.Text.Encoding</c>, which is the <c>IBM437</c>
/// codepage. If you want to specify the encoding to use when
/// reading the zipfile content, see
/// <see cref="ZipFile.Read(Stream,
/// ReadOptions)">ZipFile.Read(Stream, ReadOptions)</see>. This
/// </para>
///
/// <para>
/// Reading of zip content begins at the current position in the
/// stream. This means if you have a stream that concatenates
/// regular data and zip data, if you position the open, readable
/// stream at the start of the zip data, you will be able to read
/// the zip archive using this constructor, or any of the ZipFile
/// constructors that accept a <see cref="System.IO.Stream" /> as
/// input. Some examples of where this might be useful: the zip
/// content is concatenated at the end of a regular EXE file, as
/// some self-extracting archives do. (Note: SFX files produced
/// by DotNetZip do not work this way; they can be read as normal
/// ZIP files). Another example might be a stream being read from
/// a database, where the zip content is embedded within an
/// aggregate stream of data.
/// </para>
///
/// </remarks>
///
/// <example>
/// <para>
/// This example shows how to Read zip content from a stream, and
/// extract one entry into a different stream. In this example,
/// the filename "NameOfEntryInArchive.doc", refers only to the
/// name of the entry within the zip archive. A file by that
/// name is not created in the filesystem. The I/O is done
/// strictly with the given streams.
/// </para>
///
/// <code>
/// using (ZipFile zip = ZipFile.Read(InputStream))
/// {
/// zip.Extract("NameOfEntryInArchive.doc", OutputStream);
/// }
/// </code>
///
/// <code lang="VB">
/// Using zip as ZipFile = ZipFile.Read(InputStream)
/// zip.Extract("NameOfEntryInArchive.doc", OutputStream)
/// End Using
/// </code>
/// </example>
///
/// <param name="zipStream">the stream containing the zip data.</param>
///
/// <returns>The ZipFile instance read from the stream</returns>
///
public static ZipFile Read(Stream zipStream)
{
return Read(zipStream, null, null, null);
}
/// <summary>
/// Reads a zip file archive from the given stream using the
/// specified options.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When reading from a file, it's probably easier to just use
/// <see cref="ZipFile.Read(String,
/// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This
/// overload is useful when when the zip archive content is
/// available from an already-open stream. The stream must be
/// open and readable and seekable when calling this method. The
/// stream is left open when the reading is completed.
/// </para>
///
/// <para>
/// Reading of zip content begins at the current position in the
/// stream. This means if you have a stream that concatenates
/// regular data and zip data, if you position the open, readable
/// stream at the start of the zip data, you will be able to read
/// the zip archive using this constructor, or any of the ZipFile
/// constructors that accept a <see cref="System.IO.Stream" /> as
/// input. Some examples of where this might be useful: the zip
/// content is concatenated at the end of a regular EXE file, as
/// some self-extracting archives do. (Note: SFX files produced
/// by DotNetZip do not work this way; they can be read as normal
/// ZIP files). Another example might be a stream being read from
/// a database, where the zip content is embedded within an
/// aggregate stream of data.
/// </para>
/// </remarks>
///
/// <param name="zipStream">the stream containing the zip data.</param>
///
/// <param name="options">
/// The set of options to use when reading the zip file.
/// </param>
///
/// <exception cref="System.Exception">
/// Thrown if the zip archive cannot be read.
/// </exception>
///
/// <returns>The ZipFile instance read from the stream.</returns>
///
/// <seealso cref="ZipFile.Read(String, ReadOptions)"/>
///
public static ZipFile Read(Stream zipStream, ReadOptions options)
{
if (options == null)
throw new ArgumentNullException("options");
return Read(zipStream,
options.StatusMessageWriter,
options.Encoding,
options.ReadProgress);
}
/// <summary>
/// Reads a zip archive from a stream, using the specified text Encoding, the
/// specified TextWriter for status messages,
/// and the specified ReadProgress event handler.
/// </summary>
///
/// <remarks>
/// <para>
/// Reading of zip content begins at the current position in the stream. This
/// means if you have a stream that concatenates regular data and zip data, if
/// you position the open, readable stream at the start of the zip data, you
/// will be able to read the zip archive using this constructor, or any of the
/// ZipFile constructors that accept a <see cref="System.IO.Stream" /> as
/// input. Some examples of where this might be useful: the zip content is
/// concatenated at the end of a regular EXE file, as some self-extracting
/// archives do. (Note: SFX files produced by DotNetZip do not work this
/// way). Another example might be a stream being read from a database, where
/// the zip content is embedded within an aggregate stream of data.
/// </para>
/// </remarks>
///
/// <param name="zipStream">the stream containing the zip data.</param>
///
/// <param name="statusMessageWriter">
/// The <c>System.IO.TextWriter</c> to which verbose status messages are written
/// during operations on the <c>ZipFile</c>. For example, in a console
/// application, System.Console.Out works, and will get a message for each entry
/// added to the ZipFile. If the TextWriter is <c>null</c>, no verbose messages
/// are written.
/// </param>
///
/// <param name="encoding">
/// The text encoding to use when reading entries that do not have the UTF-8
/// encoding bit set. Be careful specifying the encoding. If the value you use
/// here is not the same as the Encoding used when the zip archive was created
/// (possibly by a different archiver) you will get unexpected results and
/// possibly exceptions. See the <see cref="ProvisionalAlternateEncoding"/>
/// property for more information.
/// </param>
///
/// <param name="readProgress">
/// An event handler for Read operations.
/// </param>
///
/// <returns>an instance of ZipFile</returns>
private static ZipFile Read(Stream zipStream,
TextWriter statusMessageWriter,
System.Text.Encoding encoding,
EventHandler<ReadProgressEventArgs> readProgress)
{
if (zipStream == null)
throw new ArgumentNullException("zipStream");
ZipFile zf = new ZipFile();
zf._StatusMessageTextWriter = statusMessageWriter;
zf._alternateEncoding = encoding ?? ZipFile.DefaultEncoding;
zf._alternateEncodingUsage = ZipOption.Always;
if (readProgress != null)
zf.ReadProgress += readProgress;
zf._readstream = (zipStream.Position == 0L)
? zipStream
: new OffsetStream(zipStream);
zf._ReadStreamIsOurs = false;
if (zf.Verbose) zf._StatusMessageTextWriter.WriteLine("reading from stream...");
ReadIntoInstance(zf);
return zf;
}
private static void ReadIntoInstance(ZipFile zf)
{
Stream s = zf.ReadStream;
try
{
zf._readName = zf._name; // workitem 13915
if (!s.CanSeek)
{
ReadIntoInstance_Orig(zf);
return;
}
zf.OnReadStarted();
// change for workitem 8098
//zf._originPosition = s.Position;
// Try reading the central directory, rather than scanning the file.
uint datum = ReadFirstFourBytes(s);
if (datum == ZipConstants.EndOfCentralDirectorySignature)
return;
// start at the end of the file...
// seek backwards a bit, then look for the EoCD signature.
int nTries = 0;
bool success = false;
// The size of the end-of-central-directory-footer plus 2 bytes is 18.
// This implies an archive comment length of 0. We'll add a margin of
// safety and start "in front" of that, when looking for the
// EndOfCentralDirectorySignature
long posn = s.Length - 64;
long maxSeekback = Math.Max(s.Length - 0x4000, 10);
do
{
if (posn < 0) posn = 0; // BOF
s.Seek(posn, SeekOrigin.Begin);
long bytesRead = SharedUtilities.FindSignature(s, (int)ZipConstants.EndOfCentralDirectorySignature);
if (bytesRead != -1)
success = true;
else
{
if (posn==0) break; // started at the BOF and found nothing
nTries++;
// Weird: with NETCF, negative offsets from SeekOrigin.End DO
// NOT WORK. So rather than seek a negative offset, we seek
// from SeekOrigin.Begin using a smaller number.
posn -= (32 * (nTries + 1) * nTries);
}
}
while (!success && posn > maxSeekback);
if (success)
{
// workitem 8299
zf._locEndOfCDS = s.Position - 4;
byte[] block = new byte[16];
s.Read(block, 0, block.Length);
zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2);
if (zf._diskNumberWithCd == 0xFFFF)
throw new ZipException("Spanned archives with more than 65534 segments are not supported at this time.");
zf._diskNumberWithCd++; // I think the number in the file differs from reality by 1
int i = 12;
uint offset32 = (uint) BitConverter.ToUInt32(block, i);
if (offset32 == 0xFFFFFFFF)
{
Zip64SeekToCentralDirectory(zf);
}
else
{
zf._OffsetOfCentralDirectory = offset32;
// change for workitem 8098
s.Seek(offset32, SeekOrigin.Begin);
}
ReadCentralDirectory(zf);
}
else
{
// Could not find the central directory.
// Fallback to the old method.
// workitem 8098: ok
//s.Seek(zf._originPosition, SeekOrigin.Begin);
s.Seek(0L, SeekOrigin.Begin);
ReadIntoInstance_Orig(zf);
}
}
catch (Exception ex1)
{
if (zf._ReadStreamIsOurs && zf._readstream != null)
{
try
{
#if NETCF
zf._readstream.Close();
#else
zf._readstream.Dispose();
#endif
zf._readstream = null;
}
finally { }
}
throw new ZipException("Cannot read that as a ZipFile", ex1);
}
// the instance has been read in
zf._contentsChanged = false;
}
private static void Zip64SeekToCentralDirectory(ZipFile zf)
{
Stream s = zf.ReadStream;
byte[] block = new byte[16];
// seek back to find the ZIP64 EoCD.
// I think this might not work for .NET CF ?
s.Seek(-40, SeekOrigin.Current);
s.Read(block, 0, 16);
Int64 offset64 = BitConverter.ToInt64(block, 8);
zf._OffsetOfCentralDirectory = 0xFFFFFFFF;
zf._OffsetOfCentralDirectory64 = offset64;
// change for workitem 8098
s.Seek(offset64, SeekOrigin.Begin);
//zf.SeekFromOrigin(Offset64);
uint datum = (uint)Ionic.Zip.SharedUtilities.ReadInt(s);
if (datum != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature)
throw new BadReadException(String.Format(" Bad signature (0x{0:X8}) looking for ZIP64 EoCD Record at position 0x{1:X8}", datum, s.Position));
s.Read(block, 0, 8);
Int64 Size = BitConverter.ToInt64(block, 0);
block = new byte[Size];
s.Read(block, 0, block.Length);
offset64 = BitConverter.ToInt64(block, 36);
// change for workitem 8098
s.Seek(offset64, SeekOrigin.Begin);
//zf.SeekFromOrigin(Offset64);
}
private static uint ReadFirstFourBytes(Stream s)
{
uint datum = (uint)Ionic.Zip.SharedUtilities.ReadInt(s);
return datum;
}
private static void ReadCentralDirectory(ZipFile zf)
{
// We must have the central directory footer record, in order to properly
// read zip dir entries from the central directory. This because the logic
// knows when to open a spanned file when the volume number for the central
// directory differs from the volume number for the zip entry. The
// _diskNumberWithCd was set when originally finding the offset for the
// start of the Central Directory.
// workitem 9214
bool inputUsesZip64 = false;
ZipEntry de;
// in lieu of hashset, use a dictionary
var previouslySeen = new Dictionary<String,object>();
while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null)
{
de.ResetDirEntry();
zf.OnReadEntry(true, null);
if (zf.Verbose)
zf.StatusMessageTextWriter.WriteLine("entry {0}", de.FileName);
zf._entries.Add(de.FileName,de);
// workitem 9214
if (de._InputUsesZip64) inputUsesZip64 = true;
previouslySeen.Add(de.FileName, null); // to prevent dupes
}
// workitem 9214; auto-set the zip64 flag
if (inputUsesZip64) zf.UseZip64WhenSaving = Zip64Option.Always;
// workitem 8299
if (zf._locEndOfCDS > 0)
zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin);
ReadCentralDirectoryFooter(zf);
if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment))
zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment);
// We keep the read stream open after reading.
if (zf.Verbose)
zf.StatusMessageTextWriter.WriteLine("read in {0} entries.", zf._entries.Count);
zf.OnReadCompleted();
}
// build the TOC by reading each entry in the file.
private static void ReadIntoInstance_Orig(ZipFile zf)
{
zf.OnReadStarted();
//zf._entries = new System.Collections.Generic.List<ZipEntry>();
zf._entries = new System.Collections.Generic.Dictionary<String,ZipEntry>();
ZipEntry e;
if (zf.Verbose)
if (zf.Name == null)
zf.StatusMessageTextWriter.WriteLine("Reading zip from stream...");
else
zf.StatusMessageTextWriter.WriteLine("Reading zip {0}...", zf.Name);
// work item 6647: PK00 (packed to removable disk)
bool firstEntry = true;
ZipContainer zc = new ZipContainer(zf);
while ((e = ZipEntry.ReadEntry(zc, firstEntry)) != null)
{
if (zf.Verbose)
zf.StatusMessageTextWriter.WriteLine(" {0}", e.FileName);
zf._entries.Add(e.FileName,e);
firstEntry = false;
}
// read the zipfile's central directory structure here.
// workitem 9912
// But, because it may be corrupted, ignore errors.
try
{
ZipEntry de;
// in lieu of hashset, use a dictionary
var previouslySeen = new Dictionary<String,Object>();
while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null)
{
// Housekeeping: Since ZipFile exposes ZipEntry elements in the enumerator,
// we need to copy the comment that we grab from the ZipDirEntry
// into the ZipEntry, so the application can access the comment.
// Also since ZipEntry is used to Write zip files, we need to copy the
// file attributes to the ZipEntry as appropriate.
ZipEntry e1 = zf._entries[de.FileName];
if (e1 != null)
{
e1._Comment = de.Comment;
if (de.IsDirectory) e1.MarkAsDirectory();
}
previouslySeen.Add(de.FileName,null); // to prevent dupes
}
// workitem 8299
if (zf._locEndOfCDS > 0)
zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin);
ReadCentralDirectoryFooter(zf);
if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment))
zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment);
}
catch (ZipException) { }
catch (IOException) { }
zf.OnReadCompleted();
}
private static void ReadCentralDirectoryFooter(ZipFile zf)
{
Stream s = zf.ReadStream;
int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
byte[] block = null;
int j = 0;
if (signature == ZipConstants.Zip64EndOfCentralDirectoryRecordSignature)
{
// We have a ZIP64 EOCD
// This data block is 4 bytes sig, 8 bytes size, 44 bytes fixed data,
// followed by a variable-sized extension block. We have read the sig already.
// 8 - datasize (64 bits)
// 2 - version made by
// 2 - version needed to extract
// 4 - number of this disk
// 4 - number of the disk with the start of the CD
// 8 - total number of entries in the CD on this disk
// 8 - total number of entries in the CD
// 8 - size of the CD
// 8 - offset of the CD
// -----------------------
// 52 bytes
block = new byte[8 + 44];
s.Read(block, 0, block.Length);
Int64 DataSize = BitConverter.ToInt64(block, 0); // == 44 + the variable length
if (DataSize < 44)
throw new ZipException("Bad size in the ZIP64 Central Directory.");
zf._versionMadeBy = BitConverter.ToUInt16(block, j);
j += 2;
zf._versionNeededToExtract = BitConverter.ToUInt16(block, j);
j += 2;
zf._diskNumberWithCd = BitConverter.ToUInt32(block, j);
j += 2;
//zf._diskNumberWithCd++; // hack!!
// read the extended block
block = new byte[DataSize - 44];
s.Read(block, 0, block.Length);
// discard the result
signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
if (signature != ZipConstants.Zip64EndOfCentralDirectoryLocatorSignature)
throw new ZipException("Inconsistent metadata in the ZIP64 Central Directory.");
block = new byte[16];
s.Read(block, 0, block.Length);
// discard the result
signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
}
// Throw if this is not a signature for "end of central directory record"
// This is a sanity check.
if (signature != ZipConstants.EndOfCentralDirectorySignature)
{
s.Seek(-4, SeekOrigin.Current);
throw new BadReadException(String.Format("Bad signature ({0:X8}) at position 0x{1:X8}",
signature, s.Position));
}
// read the End-of-Central-Directory-Record
block = new byte[16];
zf.ReadStream.Read(block, 0, block.Length);
// off sz data
// -------------------------------------------------------
// 0 4 end of central dir signature (0x06054b50)
// 4 2 number of this disk
// 6 2 number of the disk with start of the central directory
// 8 2 total number of entries in the central directory on this disk
// 10 2 total number of entries in the central directory
// 12 4 size of the central directory
// 16 4 offset of start of central directory with respect to the starting disk number
// 20 2 ZIP file comment length
// 22 ?? ZIP file comment
if (zf._diskNumberWithCd == 0)
{
zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2);
//zf._diskNumberWithCd++; // hack!!
}
// read the comment here
ReadZipFileComment(zf);
}
private static void ReadZipFileComment(ZipFile zf)
{
// read the comment here
byte[] block = new byte[2];
zf.ReadStream.Read(block, 0, block.Length);
Int16 commentLength = (short)(block[0] + block[1] * 256);
if (commentLength > 0)
{
block = new byte[commentLength];
zf.ReadStream.Read(block, 0, block.Length);
// workitem 10392 - prefer ProvisionalAlternateEncoding,
// first. The fix for workitem 6513 tried to use UTF-8
// only as necessary, but that is impossible to test
// for, in this direction. There's no way to know what
// characters the already-encoded bytes refer
// to. Therefore, must do what the user tells us.
string s1 = zf.AlternateEncoding.GetString(block, 0, block.Length);
zf.Comment = s1;
}
}
// private static bool BlocksAreEqual(byte[] a, byte[] b)
// {
// if (a.Length != b.Length) return false;
// for (int i = 0; i < a.Length; i++)
// {
// if (a[i] != b[i]) return false;
// }
// return true;
// }
/// <summary>
/// Checks the given file to see if it appears to be a valid zip file.
/// </summary>
/// <remarks>
///
/// <para>
/// Calling this method is equivalent to calling <see cref="IsZipFile(string,
/// bool)"/> with the testExtract parameter set to false.
/// </para>
/// </remarks>
///
/// <param name="fileName">The file to check.</param>
/// <returns>true if the file appears to be a zip file.</returns>
public static bool IsZipFile(string fileName)
{
return IsZipFile(fileName, false);
}
/// <summary>
/// Checks a file to see if it is a valid zip file.
/// </summary>
///
/// <remarks>
/// <para>
/// This method opens the specified zip file, reads in the zip archive,
/// verifying the ZIP metadata as it reads.
/// </para>
///
/// <para>
/// If everything succeeds, then the method returns true. If anything fails -
/// for example if an incorrect signature or CRC is found, indicating a
/// corrupt file, the the method returns false. This method also returns
/// false for a file that does not exist.
/// </para>
///
/// <para>
/// If <paramref name="testExtract"/> is true, as part of its check, this
/// method reads in the content for each entry, expands it, and checks CRCs.
/// This provides an additional check beyond verifying the zip header and
/// directory data.
/// </para>
///
/// <para>
/// If <paramref name="testExtract"/> is true, and if any of the zip entries
/// are protected with a password, this method will return false. If you want
/// to verify a <c>ZipFile</c> that has entries which are protected with a
/// password, you will need to do that manually.
/// </para>
///
/// </remarks>
///
/// <param name="fileName">The zip file to check.</param>
/// <param name="testExtract">true if the caller wants to extract each entry.</param>
/// <returns>true if the file contains a valid zip file.</returns>
public static bool IsZipFile(string fileName, bool testExtract)
{
bool result = false;
try
{
if (!File.Exists(fileName)) return false;
using (var s = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
result = IsZipFile(s, testExtract);
}
}
catch (IOException) { }
catch (ZipException) { }
return result;
}
/// <summary>
/// Checks a stream to see if it contains a valid zip archive.
/// </summary>
///
/// <remarks>
/// <para>
/// This method reads the zip archive contained in the specified stream, verifying
/// the ZIP metadata as it reads. If testExtract is true, this method also extracts
/// each entry in the archive, dumping all the bits into <see cref="Stream.Null"/>.
/// </para>
///
/// <para>
/// If everything succeeds, then the method returns true. If anything fails -
/// for example if an incorrect signature or CRC is found, indicating a corrupt
/// file, the the method returns false. This method also returns false for a
/// file that does not exist.
/// </para>
///
/// <para>
/// If <c>testExtract</c> is true, this method reads in the content for each
/// entry, expands it, and checks CRCs. This provides an additional check
/// beyond verifying the zip header data.
/// </para>
///
/// <para>
/// If <c>testExtract</c> is true, and if any of the zip entries are protected
/// with a password, this method will return false. If you want to verify a
/// ZipFile that has entries which are protected with a password, you will need
/// to do that manually.
/// </para>
/// </remarks>
///
/// <seealso cref="IsZipFile(string, bool)"/>
///
/// <param name="stream">The stream to check.</param>
/// <param name="testExtract">true if the caller wants to extract each entry.</param>
/// <returns>true if the stream contains a valid zip archive.</returns>
public static bool IsZipFile(Stream stream, bool testExtract)
{
if (stream == null)
throw new ArgumentNullException("stream");
bool result = false;
try
{
if (!stream.CanRead) return false;
var bitBucket = Stream.Null;
using (ZipFile zip1 = ZipFile.Read(stream, null, null, null))
{
if (testExtract)
{
foreach (var e in zip1)
{
if (!e.IsDirectory)
{
e.Extract(bitBucket);
}
}
}
}
result = true;
}
catch (IOException) { }
catch (ZipException) { }
return result;
}
}
}
| |
/* 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 System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Collections.ObjectModel;
namespace XenAdmin.Controls
{
partial class MultiSelectTreeView
{
public sealed class MultiSelectTreeSelectedNodeCollection : IList<MultiSelectTreeNode>
{
private readonly MultiSelectTreeView _parent;
public MultiSelectTreeSelectedNodeCollection(MultiSelectTreeView parent)
{
Util.ThrowIfParameterNull(parent, "parent");
_parent = parent;
}
public void SetContents(IEnumerable<MultiSelectTreeNode> items)
{
Util.ThrowIfParameterNull(items, "items");
IList<MultiSelectTreeNode> itemsAsList = items as IList<MultiSelectTreeNode>;
int itemsCount = itemsAsList != null ? itemsAsList.Count : (new List<MultiSelectTreeNode>(items).Count);
bool different = itemsCount != Count;
if (!different)
{
List<MultiSelectTreeNode> existing = new List<MultiSelectTreeNode>(this);
// check if contents are different.
foreach (MultiSelectTreeNode node in items)
{
int index = existing.IndexOf(node);
if (index < 0)
{
different = true;
break;
}
else
{
existing.RemoveAt(index);
}
}
different |= existing.Count > 0;
}
if (different)
{
_parent._selectionChanged = false;
_parent.UnselectAllNodes(TreeViewAction.Unknown);
foreach (MultiSelectTreeNode item in items)
{
_parent.SelectNode(item, true, TreeViewAction.Unknown);
}
_parent.OnSelectionsChanged();
}
}
#region IList<TreeNode> Members
public int IndexOf(MultiSelectTreeNode item)
{
return _parent._internalSelectedNodes.IndexOf(item);
}
public void Insert(int index, MultiSelectTreeNode item)
{
_parent._selectionChanged = false;
_parent.SelectNode(item, true, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public void RemoveAt(int index)
{
MultiSelectTreeNode item = _parent._internalSelectedNodes[index];
_parent._selectionChanged = false;
_parent.SelectNode(item, false, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public MultiSelectTreeNode this[int index]
{
get
{
return _parent._internalSelectedNodes[index];
}
set
{
throw new InvalidOperationException();
}
}
#endregion
#region ICollection<TreeNode> Members
public void Add(MultiSelectTreeNode item)
{
_parent._selectionChanged = false;
_parent.SelectNode(item, true, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public void Clear()
{
_parent._selectionChanged = false;
_parent.UnselectAllNodes(TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
}
public bool Contains(MultiSelectTreeNode item)
{
return _parent._internalSelectedNodes.Contains(item);
}
public void CopyTo(MultiSelectTreeNode[] array, int arrayIndex)
{
_parent._internalSelectedNodes.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _parent._internalSelectedNodes.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(MultiSelectTreeNode item)
{
bool ret = Contains(item);
_parent._selectionChanged = false;
_parent.SelectNode(item, false, TreeViewAction.Unknown);
_parent.OnSelectionsChanged();
return ret;
}
#endregion
#region IEnumerable<MultiSelectTreeNode> Members
public IEnumerator<MultiSelectTreeNode> GetEnumerator()
{
return _parent._internalSelectedNodes.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
private class InternalSelectedNodeCollection : Collection<MultiSelectTreeNode>
{
protected override void ClearItems()
{
List<MultiSelectTreeNode> nodes = new List<MultiSelectTreeNode>(this);
base.ClearItems();
foreach (MultiSelectTreeNode node in nodes)
{
((IMultiSelectTreeNode)node).SetSelected(false);
}
}
protected override void InsertItem(int index, MultiSelectTreeNode item)
{
base.InsertItem(index, item);
((IMultiSelectTreeNode)item).SetSelected(true);
}
protected override void RemoveItem(int index)
{
MultiSelectTreeNode node = this[index];
base.RemoveItem(index);
((IMultiSelectTreeNode)node).SetSelected(false);
}
protected override void SetItem(int index, MultiSelectTreeNode item)
{
MultiSelectTreeNode toRemove = this[index];
base.SetItem(index, item);
((IMultiSelectTreeNode)toRemove).SetSelected(false);
((IMultiSelectTreeNode)item).SetSelected(true);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using IServiceProvider = System.IServiceProvider;
namespace Microsoft.VisualStudioTools.Project
{
/// <summary>
/// This object is in charge of reloading nodes that have file monikers that can be listened to changes
/// </summary>
internal class FileChangeManager : IVsFileChangeEvents
{
#region nested objects
/// <summary>
/// Defines a data structure that can link a item moniker to the item and its file change cookie.
/// </summary>
private struct ObservedItemInfo
{
/// <summary>
/// Defines the id of the item that is to be reloaded.
/// </summary>
private uint itemID;
/// <summary>
/// Defines the file change cookie that is returned when listening on file changes on the nested project item.
/// </summary>
private uint fileChangeCookie;
/// <summary>
/// Defines the nested project item that is to be reloaded.
/// </summary>
internal uint ItemID
{
get
{
return this.itemID;
}
set
{
this.itemID = value;
}
}
/// <summary>
/// Defines the file change cookie that is returned when listenning on file changes on the nested project item.
/// </summary>
internal uint FileChangeCookie
{
get
{
return this.fileChangeCookie;
}
set
{
this.fileChangeCookie = value;
}
}
}
#endregion
#region Fields
/// <summary>
/// Event that is raised when one of the observed file names have changed on disk.
/// </summary>
internal event EventHandler<FileChangedOnDiskEventArgs> FileChangedOnDisk;
/// <summary>
/// Reference to the FileChange service.
/// </summary>
private IVsFileChangeEx fileChangeService;
/// <summary>
/// Maps between the observed item identified by its filename (in canonicalized form) and the cookie used for subscribing
/// to the events.
/// </summary>
private Dictionary<string, ObservedItemInfo> observedItems = new Dictionary<string, ObservedItemInfo>();
/// <summary>
/// Has Disposed already been called?
/// </summary>
private bool disposed;
#endregion
#region Constructor
/// <summary>
/// Overloaded ctor.
/// </summary>
/// <param name="nodeParam">An instance of a project item.</param>
internal FileChangeManager(IServiceProvider serviceProvider)
{
#region input validation
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
#endregion
this.fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
if (this.fileChangeService == null)
{
// VS is in bad state, since the SVsFileChangeEx could not be proffered.
throw new InvalidOperationException();
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes resources.
/// </summary>
public void Dispose()
{
// Don't dispose more than once
if (this.disposed)
{
return;
}
this.disposed = true;
// Unsubscribe from the observed source files.
foreach (var info in this.observedItems.Values)
{
ErrorHandler.ThrowOnFailure(this.fileChangeService.UnadviseFileChange(info.FileChangeCookie));
}
// Clean the observerItems list
this.observedItems.Clear();
}
#endregion
#region IVsFileChangeEvents Members
/// <summary>
/// Called when one of the file have changed on disk.
/// </summary>
/// <param name="numberOfFilesChanged">Number of files changed.</param>
/// <param name="filesChanged">Array of file names.</param>
/// <param name="flags">Array of flags indicating the type of changes. See _VSFILECHANGEFLAGS.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
int IVsFileChangeEvents.FilesChanged(uint numberOfFilesChanged, string[] filesChanged, uint[] flags)
{
if (filesChanged == null)
{
throw new ArgumentNullException("filesChanged");
}
if (flags == null)
{
throw new ArgumentNullException("flags");
}
if (this.FileChangedOnDisk != null)
{
for (var i = 0; i < numberOfFilesChanged; i++)
{
var fullFileName = Utilities.CanonicalizeFileName(filesChanged[i]);
if (this.observedItems.ContainsKey(fullFileName))
{
var info = this.observedItems[fullFileName];
this.FileChangedOnDisk(this, new FileChangedOnDiskEventArgs(fullFileName, info.ItemID, (_VSFILECHANGEFLAGS)flags[i]));
}
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Notifies clients of changes made to a directory.
/// </summary>
/// <param name="directory">Name of the directory that had a change.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
int IVsFileChangeEvents.DirectoryChanged(string directory)
{
return VSConstants.S_OK;
}
#endregion
#region helpers
/// <summary>
/// Observe when the given file is updated on disk. In this case we do not care about the item id that represents the file in the hierarchy.
/// </summary>
/// <param name="fileName">File to observe.</param>
internal void ObserveItem(string fileName)
{
this.ObserveItem(fileName, VSConstants.VSITEMID_NIL);
}
/// <summary>
/// Observe when the given file is updated on disk.
/// </summary>
/// <param name="fileName">File to observe.</param>
/// <param name="id">The item id of the item to observe.</param>
internal void ObserveItem(string fileName, uint id)
{
#region Input validation
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName");
}
#endregion
var fullFileName = Utilities.CanonicalizeFileName(fileName);
if (!this.observedItems.ContainsKey(fullFileName))
{
// Observe changes to the file
uint fileChangeCookie;
ErrorHandler.ThrowOnFailure(this.fileChangeService.AdviseFileChange(fullFileName, (uint)(_VSFILECHANGEFLAGS.VSFILECHG_Time | _VSFILECHANGEFLAGS.VSFILECHG_Del), this, out fileChangeCookie));
var itemInfo = new ObservedItemInfo();
itemInfo.ItemID = id;
itemInfo.FileChangeCookie = fileChangeCookie;
// Remember that we're observing this file (used in FilesChanged event handler)
this.observedItems.Add(fullFileName, itemInfo);
}
}
/// <summary>
/// Ignore item file changes for the specified item.
/// </summary>
/// <param name="fileName">File to ignore observing.</param>
/// <param name="ignore">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
internal void IgnoreItemChanges(string fileName, bool ignore)
{
#region Input validation
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName");
}
#endregion
var fullFileName = Utilities.CanonicalizeFileName(fileName);
if (this.observedItems.ContainsKey(fullFileName))
{
// Call ignore file with the flags specified.
ErrorHandler.ThrowOnFailure(this.fileChangeService.IgnoreFile(0, fileName, ignore ? 1 : 0));
}
}
/// <summary>
/// Stop observing when the file is updated on disk.
/// </summary>
/// <param name="fileName">File to stop observing.</param>
internal void StopObservingItem(string fileName)
{
#region Input validation
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileName");
}
#endregion
var fullFileName = Utilities.CanonicalizeFileName(fileName);
if (this.observedItems.ContainsKey(fullFileName))
{
// Get the cookie that was used for this.observedItems to this file.
var itemInfo = this.observedItems[fullFileName];
// Remove the file from our observed list. It's important that this is done before the call to
// UnadviseFileChange, because for some reason, the call to UnadviseFileChange can trigger a
// FilesChanged event, and we want to be able to filter that event away.
this.observedItems.Remove(fullFileName);
// Stop observing the file
ErrorHandler.ThrowOnFailure(this.fileChangeService.UnadviseFileChange(itemInfo.FileChangeCookie));
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ChefsForSeniors.Models;
using ChefsForSeniors.Services.ConfigurationService;
using Newtonsoft.Json;
namespace ChefsForSeniors.Services
{
public class RealDataService : IDataService
{
private static IRestService _restService;
private static ISqliteService _sqliteService;
private static RestConfiguration _restConfig = new RestConfiguration();
public RealDataService(IRestService restService, ISqliteService sqliteService)
{
_restService = restService;
_sqliteService = sqliteService;
}
public IEntityDAL<Chef> Chef { get; } = new ChefLogic();
public class ChefLogic : IEntityDAL<Chef>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Chef>> GetManyAsync(int? fk = default(int?))
{
var allUri = _restConfig.CreateGetAll("Chef");
var result = await _restService.GetStringAsync(allUri);
var chefs = JsonConvert.DeserializeObject<List<Chef>>(result);
return chefs;
}
public async Task<Chef> GetOneAsync(int id)
{
var getOneUri = _restConfig.CreateOne("Chef", id);
var result = await _restService.GetStringAsync(getOneUri);
var chef = JsonConvert.DeserializeObject<List<Chef>>(result);
return chef.First<Chef>();
}
public Task<Chef> InsertAsync(Chef item) { throw new NotImplementedException(); }
public Task<Chef> SaveAsync(Chef item) { throw new NotImplementedException(); }
}
public IEntityDAL<Client> Client { get; } = new ClientLogic();
public class ClientLogic : IEntityDAL<Client>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Client>> GetManyAsync(int? fk = default(int?))
{
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetClientByChefID", "ID", fk?.ToString());
var result = await _restService.GetStringAsync(allUri);
var clients = JsonConvert.DeserializeObject<List<Client>>(result);
return clients;
}
public async Task<Client> GetOneAsync(int id)
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetClientByID", "ID", id.ToString());
var result = await _restService.GetStringAsync(allUri);
var client = JsonConvert.DeserializeObject<Client>(result);
return client;
}
public Task<Client> InsertAsync(Client item) { throw new NotImplementedException(); }
public Task<Client> SaveAsync(Client item) { throw new NotImplementedException(); }
}
public IEntityDAL<Week> Week { get; } = new WeekLogic();
public class WeekLogic : IEntityDAL<Week>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Week>> GetManyAsync(int? fk = default(int?))
{
//TODO: Make sure this creates the correct URL & week logic needed
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetWeeksByClientID", "ID", fk?.ToString());
var result = await _restService.GetStringAsync(allUri);
var weeks = JsonConvert.DeserializeObject<List<Week>>(result);
return weeks;
}
public async Task<Week> GetOneAsync(int id)
{
//TODO: Make sure this creates the correct URL & week logic needed
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetWeekByWeekID", "ID", id.ToString());
var result = await _restService.GetStringAsync(allUri);
var week = JsonConvert.DeserializeObject<Week>(result);
return week;
}
public Task<Week> InsertAsync(Week item) { throw new NotImplementedException(); }
public Task<Week> SaveAsync(Week item) { throw new NotImplementedException(); }
}
public IEntityDAL<Meal> Meal { get; } = new MealLogic();
public class MealLogic : IEntityDAL<Meal>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Meal>> GetManyAsync(int? fk = default(int?))
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetMealsByWeekID", "ID", fk?.ToString());
var result = await _restService.GetStringAsync(allUri);
var meals = JsonConvert.DeserializeObject<List<Meal>>(result);
return meals;
}
public async Task<Meal> GetOneAsync(int id)
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetMealByWeekID", "ID", id.ToString());
var result = await _restService.GetStringAsync(allUri);
var meal = JsonConvert.DeserializeObject<Meal>(result);
return meal;
}
public Task<Meal> InsertAsync(Meal item) { throw new NotImplementedException(); }
public Task<Meal> SaveAsync(Meal item) { throw new NotImplementedException(); }
}
public IEntityDAL<Recipe> Recipe { get; } = new RecipeLogic();
public class RecipeLogic : IEntityDAL<Recipe>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Recipe>> GetManyAsync(int? fk = default(int?))
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetRecipesByMealID", "ID", fk?.ToString());
var result = await _restService.GetStringAsync(allUri);
var recipes = JsonConvert.DeserializeObject<List<Recipe>>(result);
return recipes;
}
public async Task<Recipe> GetOneAsync(int id)
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetRecipeByMealID", "ID", id.ToString());
var result = await _restService.GetStringAsync(allUri);
var recipe = JsonConvert.DeserializeObject<Recipe>(result);
return recipe;
}
public Task<Recipe> InsertAsync(Recipe item) { throw new NotImplementedException(); }
public Task<Recipe> SaveAsync(Recipe item) { throw new NotImplementedException(); }
}
public IEntityDAL<Ingredient> Ingredient { get; } = new IngredientLogic();
public class IngredientLogic : IEntityDAL<Ingredient>
{
public Task DeleteAsync(int id) { throw new NotImplementedException(); }
public async Task<IEnumerable<Ingredient>> GetManyAsync(int? fk = default(int?))
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetIngredientsByRecipeID", "ID", fk?.ToString());
var result = await _restService.GetStringAsync(allUri);
var ingredients = JsonConvert.DeserializeObject<List<Ingredient>>(result);
return ingredients;
}
public async Task<Ingredient> GetOneAsync(int id)
{
//TODO: Make sure this creates the correct URL
var allUri = _restConfig.CreateCustomWithParameter("Client", "GetIngredientByRecipeID", "ID", id.ToString());
var result = await _restService.GetStringAsync(allUri);
var ingredient = JsonConvert.DeserializeObject<Ingredient>(result);
return ingredient;
}
public Task<Ingredient> InsertAsync(Ingredient item) { throw new NotImplementedException(); }
public Task<Ingredient> SaveAsync(Ingredient item) { throw new NotImplementedException(); }
}
public Task<bool> LoginAsync(Chef chef, string password)
{
throw new NotImplementedException();
}
public Task<IEnumerable<RecipeType>> GetRecipeTypesAsync()
{
throw new NotImplementedException();
}
public Task<IEnumerable<IngredientCategory>> GetIngredientCategoriesAsync()
{
throw new NotImplementedException();
}
public Task<IEnumerable<IngredientUnit>> GetIngredientUnits()
{
throw new NotImplementedException();
}
public Task<IEnumerable<Ingredient>> GetShoppingPendingAsync(int weekId)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Ingredient>> GetShoppingPurchasedAsync(int weekId)
{
throw new NotImplementedException();
}
public void MarkIngredientPurchased(int weekId, int ingredientId)
{
throw new NotImplementedException();
}
public void MarkIngredientPending(int weekId, int ingredientId)
{
throw new NotImplementedException();
}
public Task<IEnumerable<MealType>> GetMealTypesAsync()
{
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class MethodExtractor
{
protected abstract partial class Analyzer
{
private readonly SemanticDocument _semanticDocument;
protected readonly CancellationToken CancellationToken;
protected readonly SelectionResult SelectionResult;
protected Analyzer(SelectionResult selectionResult, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(selectionResult);
this.SelectionResult = selectionResult;
_semanticDocument = selectionResult.SemanticDocument;
this.CancellationToken = cancellationToken;
}
/// <summary>
/// convert text span to node range for the flow analysis API
/// </summary>
protected abstract Tuple<SyntaxNode, SyntaxNode> GetFlowAnalysisNodeRange();
/// <summary>
/// check whether selection contains return statement or not
/// </summary>
protected abstract bool ContainsReturnStatementInSelectedCode(IEnumerable<SyntaxNode> jumpOutOfRegionStatements);
/// <summary>
/// create VariableInfo type
/// </summary>
protected abstract VariableInfo CreateFromSymbol(Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle variableStyle, bool variableDeclared);
/// <summary>
/// among variables that will be used as parameters at the extracted method, check whether one of the parameter can be used as return
/// </summary>
protected abstract int GetIndexOfVariableInfoToUseAsReturnValue(IList<VariableInfo> variableInfo);
/// <summary>
/// get type of the range variable symbol
/// </summary>
protected abstract ITypeSymbol GetRangeVariableType(SemanticModel model, IRangeVariableSymbol symbol);
/// <summary>
/// check whether the selection is at the placed where read-only field is allowed to be extracted out
/// </summary>
/// <returns></returns>
protected abstract bool ReadOnlyFieldAllowed();
public async Task<AnalyzerResult> AnalyzeAsync()
{
// do data flow analysis
var model = _semanticDocument.SemanticModel;
var dataFlowAnalysisData = GetDataFlowAnalysisData(model);
// build symbol map for the identifiers used inside of the selection
var symbolMap = GetSymbolMap(model);
// gather initial local or parameter variable info
var variableInfoMap = GenerateVariableInfoMap(model, dataFlowAnalysisData, symbolMap);
// check whether instance member is used inside of the selection
var instanceMemberIsUsed = IsInstanceMemberUsedInSelectedCode(dataFlowAnalysisData);
// check whether end of selection is reachable
var endOfSelectionReachable = IsEndOfSelectionReachable(model);
// collects various variable informations
// extracted code contains return value
var isInExpressionOrHasReturnStatement = IsInExpressionOrHasReturnStatement(model);
var signatureTuple = GetSignatureInformation(dataFlowAnalysisData, variableInfoMap, isInExpressionOrHasReturnStatement);
var parameters = signatureTuple.Item1;
var returnType = signatureTuple.Item2;
var variableToUseAsReturnValue = signatureTuple.Item3;
var unsafeAddressTakenUsed = signatureTuple.Item4;
var returnTypeTuple = AdjustReturnType(model, returnType);
returnType = returnTypeTuple.Item1;
bool returnTypeHasAnonymousType = returnTypeTuple.Item2;
bool awaitTaskReturn = returnTypeTuple.Item3;
// create new document
var newDocument = await CreateDocumentWithAnnotationsAsync(_semanticDocument, parameters, CancellationToken).ConfigureAwait(false);
// collect method type variable used in selected code
var sortedMap = new SortedDictionary<int, ITypeParameterSymbol>();
var typeParametersInConstraintList = GetMethodTypeParametersInConstraintList(model, variableInfoMap, symbolMap, sortedMap);
var typeParametersInDeclaration = GetMethodTypeParametersInDeclaration(returnType, sortedMap);
// check various error cases
var operationStatus = GetOperationStatus(model, symbolMap, parameters, unsafeAddressTakenUsed, returnTypeHasAnonymousType);
return new AnalyzerResult(
newDocument,
typeParametersInDeclaration, typeParametersInConstraintList,
parameters, variableToUseAsReturnValue, returnType, awaitTaskReturn,
instanceMemberIsUsed, endOfSelectionReachable, operationStatus);
}
private Tuple<ITypeSymbol, bool, bool> AdjustReturnType(SemanticModel model, ITypeSymbol returnType)
{
// check whether return type contains anonymous type and if it does, fix it up by making it object
var returnTypeHasAnonymousType = returnType.ContainsAnonymousType();
returnType = returnTypeHasAnonymousType ? returnType.RemoveAnonymousTypes(model.Compilation) : returnType;
// if selection contains await which is not under async lambda or anonymous delegate,
// change return type to be wrapped in Task
var shouldPutAsyncModifier = this.SelectionResult.ShouldPutAsyncModifier();
if (shouldPutAsyncModifier)
{
bool awaitTaskReturn;
WrapReturnTypeInTask(model, ref returnType, out awaitTaskReturn);
return Tuple.Create(returnType, returnTypeHasAnonymousType, awaitTaskReturn);
}
// unwrap task if needed
UnwrapTaskIfNeeded(model, ref returnType);
return Tuple.Create(returnType, returnTypeHasAnonymousType, false);
}
private void UnwrapTaskIfNeeded(SemanticModel model, ref ITypeSymbol returnType)
{
// nothing to unwrap
if (!this.SelectionResult.ContainingScopeHasAsyncKeyword() ||
!this.ContainsReturnStatementInSelectedCode(model))
{
return;
}
var originalDefinition = returnType.OriginalDefinition;
// see whether it needs to be unwrapped
var taskType = model.Compilation.TaskType();
if (originalDefinition.Equals(taskType))
{
returnType = model.Compilation.GetSpecialType(SpecialType.System_Void);
return;
}
var genericTaskType = model.Compilation.TaskOfTType();
if (originalDefinition.Equals(genericTaskType))
{
returnType = ((INamedTypeSymbol)returnType).TypeArguments[0];
return;
}
// nothing to unwrap
return;
}
private void WrapReturnTypeInTask(SemanticModel model, ref ITypeSymbol returnType, out bool awaitTaskReturn)
{
awaitTaskReturn = false;
var genericTaskType = model.Compilation.TaskOfTType();
var taskType = model.Compilation.TaskType();
if (returnType.Equals(model.Compilation.GetSpecialType(SpecialType.System_Void)))
{
// convert void to Task type
awaitTaskReturn = true;
returnType = taskType;
return;
}
if (this.SelectionResult.SelectionInExpression)
{
returnType = genericTaskType.Construct(returnType);
return;
}
if (ContainsReturnStatementInSelectedCode(model))
{
// check whether we will use return type as it is or not.
awaitTaskReturn = returnType.Equals(taskType);
return;
}
// okay, wrap the return type in Task<T>
returnType = genericTaskType.Construct(returnType);
}
private Tuple<IList<VariableInfo>, ITypeSymbol, VariableInfo, bool> GetSignatureInformation(
DataFlowAnalysis dataFlowAnalysisData,
IDictionary<ISymbol, VariableInfo> variableInfoMap,
bool isInExpressionOrHasReturnStatement)
{
var model = _semanticDocument.SemanticModel;
var compilation = model.Compilation;
if (isInExpressionOrHasReturnStatement)
{
// check whether current selection contains return statement
var parameters = GetMethodParameters(variableInfoMap.Values);
var returnType = SelectionResult.GetContainingScopeType() ?? compilation.GetSpecialType(SpecialType.System_Object);
var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys);
return Tuple.Create(parameters, returnType, default(VariableInfo), unsafeAddressTakenUsed);
}
else
{
// no return statement
var parameters = MarkVariableInfoToUseAsReturnValueIfPossible(GetMethodParameters(variableInfoMap.Values));
var variableToUseAsReturnValue = parameters.FirstOrDefault(v => v.UseAsReturnValue);
var returnType = variableToUseAsReturnValue != null
? variableToUseAsReturnValue.GetVariableType(_semanticDocument)
: compilation.GetSpecialType(SpecialType.System_Void);
var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys);
return Tuple.Create(parameters, returnType, variableToUseAsReturnValue, unsafeAddressTakenUsed);
}
}
private bool IsInExpressionOrHasReturnStatement(SemanticModel model)
{
var isInExpressionOrHasReturnStatement = this.SelectionResult.SelectionInExpression;
if (!isInExpressionOrHasReturnStatement)
{
var containsReturnStatement = ContainsReturnStatementInSelectedCode(model);
isInExpressionOrHasReturnStatement |= containsReturnStatement;
}
return isInExpressionOrHasReturnStatement;
}
private OperationStatus GetOperationStatus(
SemanticModel model, Dictionary<ISymbol, List<SyntaxToken>> symbolMap, IList<VariableInfo> parameters,
bool unsafeAddressTakenUsed, bool returnTypeHasAnonymousType)
{
var readonlyFieldStatus = CheckReadOnlyFields(model, symbolMap);
var namesWithAnonymousTypes = parameters.Where(v => v.OriginalTypeHadAnonymousTypeOrDelegate).Select(v => v.Name ?? string.Empty);
if (returnTypeHasAnonymousType)
{
namesWithAnonymousTypes = namesWithAnonymousTypes.Concat("return type");
}
var anonymousTypeStatus = namesWithAnonymousTypes.Any() ?
new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Parameters_type_or_return_type_cannot_be_an_anonymous_type_colon_bracket_0_bracket, string.Join(", ", namesWithAnonymousTypes))) :
OperationStatus.Succeeded;
var unsafeAddressStatus = unsafeAddressTakenUsed ? OperationStatus.UnsafeAddressTaken : OperationStatus.Succeeded;
var asyncRefOutParameterStatue = CheckAsyncMethodRefOutParameters(parameters);
return readonlyFieldStatus.With(anonymousTypeStatus).With(unsafeAddressStatus).With(asyncRefOutParameterStatue);
}
private OperationStatus CheckAsyncMethodRefOutParameters(IList<VariableInfo> parameters)
{
if (this.SelectionResult.ShouldPutAsyncModifier())
{
var names = parameters.Where(v => !v.UseAsReturnValue && (v.ParameterModifier == ParameterBehavior.Out || v.ParameterModifier == ParameterBehavior.Ref))
.Select(p => p.Name ?? string.Empty);
if (names.Any())
{
return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket, string.Join(", ", names)));
}
}
return OperationStatus.Succeeded;
}
private Task<SemanticDocument> CreateDocumentWithAnnotationsAsync(SemanticDocument document, IList<VariableInfo> variables, CancellationToken cancellationToken)
{
var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(variables.Count);
variables.Do(v => v.AddIdentifierTokenAnnotationPair(annotations, cancellationToken));
if (annotations.Count == 0)
{
return Task.FromResult(document);
}
return document.WithSyntaxRootAsync(document.Root.AddAnnotations(annotations), cancellationToken);
}
private Dictionary<ISymbol, List<SyntaxToken>> GetSymbolMap(SemanticModel model)
{
var syntaxFactsService = _semanticDocument.Document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var context = this.SelectionResult.GetContainingScope();
var symbolMap = SymbolMapBuilder.Build(syntaxFactsService, model, context, this.SelectionResult.FinalSpan, CancellationToken);
return symbolMap;
}
private bool ContainsVariableUnsafeAddressTaken(DataFlowAnalysis dataFlowAnalysisData, IEnumerable<ISymbol> symbols)
{
// check whether the selection contains "&" over a symbol exist
var map = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken);
return symbols.Any(s => map.Contains(s));
}
private DataFlowAnalysis GetDataFlowAnalysisData(SemanticModel model)
{
if (this.SelectionResult.SelectionInExpression)
{
return model.AnalyzeDataFlow(this.SelectionResult.GetContainingScope());
}
var pair = GetFlowAnalysisNodeRange();
return model.AnalyzeDataFlow(pair.Item1, pair.Item2);
}
private bool IsEndOfSelectionReachable(SemanticModel model)
{
if (this.SelectionResult.SelectionInExpression)
{
return true;
}
var pair = GetFlowAnalysisNodeRange();
var analysis = model.AnalyzeControlFlow(pair.Item1, pair.Item2);
return analysis.EndPointIsReachable;
}
private IList<VariableInfo> MarkVariableInfoToUseAsReturnValueIfPossible(IList<VariableInfo> variableInfo)
{
var variableToUseAsReturnValueIndex = GetIndexOfVariableInfoToUseAsReturnValue(variableInfo);
if (variableToUseAsReturnValueIndex >= 0)
{
variableInfo[variableToUseAsReturnValueIndex] = VariableInfo.CreateReturnValue(variableInfo[variableToUseAsReturnValueIndex]);
}
return variableInfo;
}
private IList<VariableInfo> GetMethodParameters(ICollection<VariableInfo> variableInfo)
{
var list = new List<VariableInfo>(variableInfo);
VariableInfo.SortVariables(_semanticDocument.SemanticModel.Compilation, list);
return list;
}
private IDictionary<ISymbol, VariableInfo> GenerateVariableInfoMap(
SemanticModel model, DataFlowAnalysis dataFlowAnalysisData, Dictionary<ISymbol, List<SyntaxToken>> symbolMap)
{
Contract.ThrowIfNull(model);
Contract.ThrowIfNull(dataFlowAnalysisData);
var variableInfoMap = new Dictionary<ISymbol, VariableInfo>();
// create map of each data
var capturedMap = new HashSet<ISymbol>(dataFlowAnalysisData.Captured);
var dataFlowInMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsIn);
var dataFlowOutMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsOut);
var alwaysAssignedMap = new HashSet<ISymbol>(dataFlowAnalysisData.AlwaysAssigned);
var variableDeclaredMap = new HashSet<ISymbol>(dataFlowAnalysisData.VariablesDeclared);
var readInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadInside);
var writtenInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenInside);
var readOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadOutside);
var writtenOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenOutside);
var unsafeAddressTakenMap = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken);
// gather all meaningful symbols for the span.
var candidates = new HashSet<ISymbol>(readInsideMap);
candidates.UnionWith(writtenInsideMap);
candidates.UnionWith(variableDeclaredMap);
foreach (var symbol in candidates)
{
if (IsThisParameter(symbol) ||
IsInteractiveSynthesizedParameter(symbol))
{
continue;
}
var captured = capturedMap.Contains(symbol);
var dataFlowIn = dataFlowInMap.Contains(symbol);
var dataFlowOut = dataFlowOutMap.Contains(symbol);
var alwaysAssigned = alwaysAssignedMap.Contains(symbol);
var variableDeclared = variableDeclaredMap.Contains(symbol);
var readInside = readInsideMap.Contains(symbol);
var writtenInside = writtenInsideMap.Contains(symbol);
var readOutside = readOutsideMap.Contains(symbol);
var writtenOutside = writtenOutsideMap.Contains(symbol);
var unsafeAddressTaken = unsafeAddressTakenMap.Contains(symbol);
// if it is static local, make sure it is not defined inside
if (symbol.IsStatic)
{
dataFlowIn = dataFlowIn && !variableDeclared;
}
// make sure readoutside is true when dataflowout is true (bug #3790)
// when a variable is only used inside of loop, a situation where dataflowout == true and readOutside == false
// can happen. but for extract method's point of view, this is not an information that would affect output.
// so, here we adjust flags to follow predefined assumption.
readOutside = readOutside || dataFlowOut;
// make sure data flow out is true when declared inside/written inside/read outside/not written outside are true (bug #6277)
dataFlowOut = dataFlowOut || (variableDeclared && writtenInside && readOutside && !writtenOutside);
// variable that is declared inside but never referenced outside. just ignore it and move to next one.
if (variableDeclared && !dataFlowOut && !readOutside && !writtenOutside)
{
continue;
}
// parameter defined inside of the selection (such as lambda parameter) will be ignored (bug # 10964)
if (symbol is IParameterSymbol && variableDeclared)
{
continue;
}
var type = GetSymbolType(model, symbol);
if (type == null)
{
continue;
}
var variableStyle = GetVariableStyle(symbolMap, symbol, model, type,
captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared,
readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken);
AddVariableToMap(variableInfoMap, symbol, CreateFromSymbol(model.Compilation, symbol, type, variableStyle, variableDeclared));
}
return variableInfoMap;
}
private void AddVariableToMap(IDictionary<ISymbol, VariableInfo> variableInfoMap, ISymbol localOrParameter, VariableInfo variableInfo)
{
variableInfoMap.Add(localOrParameter, variableInfo);
}
private VariableStyle GetVariableStyle(
Dictionary<ISymbol, List<SyntaxToken>> symbolMap,
ISymbol symbol,
SemanticModel model,
ITypeSymbol type,
bool captured,
bool dataFlowIn,
bool dataFlowOut,
bool alwaysAssigned,
bool variableDeclared,
bool readInside,
bool writtenInside,
bool readOutside,
bool writtenOutside,
bool unsafeAddressTaken)
{
Contract.ThrowIfNull(model);
Contract.ThrowIfNull(type);
var style = ExtractMethodMatrix.GetVariableStyle(captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared,
readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken);
if (SelectionContainsOnlyIdentifierWithSameType(type))
{
return style;
}
if (UserDefinedValueType(model.Compilation, type) && !this.SelectionResult.DontPutOutOrRefOnStruct)
{
return AlwaysReturn(style);
}
// for captured variable, never try to move the decl into extracted method
if (captured && (style == VariableStyle.MoveIn))
{
return VariableStyle.Out;
}
// check special value type cases
if (type.IsValueType && !IsWrittenInsideForFrameworkValueType(symbolMap, model, symbol, writtenInside))
{
return style;
}
// don't blindly always return. make sure there is a write inside of the selection
if (this.SelectionResult.AllowMovingDeclaration || !writtenInside)
{
return style;
}
return AlwaysReturn(style);
}
private bool IsWrittenInsideForFrameworkValueType(
Dictionary<ISymbol, List<SyntaxToken>> symbolMap, SemanticModel model, ISymbol symbol, bool writtenInside)
{
List<SyntaxToken> tokens;
if (!symbolMap.TryGetValue(symbol, out tokens))
{
return writtenInside;
}
// this relies on the fact that our IsWrittenTo only cares about syntax to figure out whether
// something is written to or not. but not semantic.
// we probably need to move the API to syntaxFact service not semanticFact.
//
// if one wants to get result that also considers semantic, he should use data control flow analysis API.
var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>();
return tokens.Any(t => semanticFacts.IsWrittenTo(model, t.Parent, CancellationToken.None));
}
private bool SelectionContainsOnlyIdentifierWithSameType(ITypeSymbol type)
{
if (!this.SelectionResult.SelectionInExpression)
{
return false;
}
var firstToken = this.SelectionResult.GetFirstTokenInSelection();
var lastToken = this.SelectionResult.GetLastTokenInSelection();
if (!firstToken.Equals(lastToken))
{
return false;
}
return type.Equals(this.SelectionResult.GetContainingScopeType());
}
private bool UserDefinedValueType(Compilation compilation, ITypeSymbol type)
{
if (!type.IsValueType || type.IsPointerType() || type.IsEnumType())
{
return false;
}
return type.OriginalDefinition.SpecialType == SpecialType.None && !WellKnownFrameworkValueType(compilation, type);
}
private bool WellKnownFrameworkValueType(Compilation compilation, ITypeSymbol type)
{
if (!type.IsValueType)
{
return false;
}
var cancellationTokenType = compilation.GetTypeByMetadataName("System.Threading.CancellationToken");
if (cancellationTokenType != null && cancellationTokenType.Equals(type))
{
return true;
}
return false;
}
private ITypeSymbol GetSymbolType(SemanticModel model, ISymbol symbol)
{
var local = symbol as ILocalSymbol;
if (local != null)
{
return local.Type;
}
var parameter = symbol as IParameterSymbol;
if (parameter != null)
{
return parameter.Type;
}
var rangeVariable = symbol as IRangeVariableSymbol;
if (rangeVariable != null)
{
return GetRangeVariableType(model, rangeVariable);
}
return Contract.FailWithReturn<ITypeSymbol>("Shouldn't reach here");
}
protected VariableStyle AlwaysReturn(VariableStyle style)
{
if (style == VariableStyle.InputOnly)
{
return VariableStyle.Ref;
}
if (style == VariableStyle.MoveIn)
{
return VariableStyle.Out;
}
if (style == VariableStyle.SplitIn)
{
return VariableStyle.Out;
}
if (style == VariableStyle.SplitOut)
{
return VariableStyle.OutWithMoveOut;
}
return style;
}
private bool IsParameterUsedOutside(ISymbol localOrParameter)
{
var parameter = localOrParameter as IParameterSymbol;
if (parameter == null)
{
return false;
}
return parameter.RefKind != RefKind.None;
}
private bool IsParameterAssigned(ISymbol localOrParameter)
{
// hack for now.
var parameter = localOrParameter as IParameterSymbol;
if (parameter == null)
{
return false;
}
return parameter.RefKind != RefKind.Out;
}
private bool IsThisParameter(ISymbol localOrParameter)
{
var parameter = localOrParameter as IParameterSymbol;
if (parameter == null)
{
return false;
}
return parameter.IsThis;
}
private bool IsInteractiveSynthesizedParameter(ISymbol localOrParameter)
{
var parameter = localOrParameter as IParameterSymbol;
if (parameter == null)
{
return false;
}
return parameter.IsImplicitlyDeclared &&
parameter.ContainingAssembly.IsInteractive &&
parameter.ContainingSymbol != null &&
parameter.ContainingSymbol.ContainingType != null &&
parameter.ContainingSymbol.ContainingType.IsScriptClass;
}
private bool ContainsReturnStatementInSelectedCode(SemanticModel model)
{
Contract.ThrowIfTrue(this.SelectionResult.SelectionInExpression);
var pair = GetFlowAnalysisNodeRange();
var controlFlowAnalysisData = model.AnalyzeControlFlow(pair.Item1, pair.Item2);
return ContainsReturnStatementInSelectedCode(controlFlowAnalysisData.ExitPoints);
}
private void AddTypeParametersToMap(IEnumerable<ITypeParameterSymbol> typeParameters, IDictionary<int, ITypeParameterSymbol> sortedMap)
{
foreach (var typeParameter in typeParameters)
{
AddTypeParameterToMap(typeParameter, sortedMap);
}
}
private void AddTypeParameterToMap(ITypeParameterSymbol typeParameter, IDictionary<int, ITypeParameterSymbol> sortedMap)
{
if (typeParameter == null ||
typeParameter.DeclaringMethod == null ||
sortedMap.ContainsKey(typeParameter.Ordinal))
{
return;
}
sortedMap[typeParameter.Ordinal] = typeParameter;
}
private void AppendMethodTypeVariableFromDataFlowAnalysis(
SemanticModel model,
IDictionary<ISymbol, VariableInfo> variableInfoMap,
IDictionary<int, ITypeParameterSymbol> sortedMap)
{
foreach (var symbol in variableInfoMap.Keys)
{
var parameter = symbol as IParameterSymbol;
if (parameter != null)
{
AddTypeParametersToMap(TypeParameterCollector.Collect(parameter.Type), sortedMap);
continue;
}
var local = symbol as ILocalSymbol;
if (local != null)
{
AddTypeParametersToMap(TypeParameterCollector.Collect(local.Type), sortedMap);
continue;
}
var rangeVariable = symbol as IRangeVariableSymbol;
if (rangeVariable != null)
{
var type = GetRangeVariableType(model, rangeVariable);
AddTypeParametersToMap(TypeParameterCollector.Collect(type), sortedMap);
continue;
}
Contract.Fail(FeaturesResources.Unknown_symbol_kind);
}
}
private void AppendMethodTypeParameterFromConstraint(SortedDictionary<int, ITypeParameterSymbol> sortedMap)
{
var typeParametersInConstraint = new List<ITypeParameterSymbol>();
// collect all type parameter appears in constraint
foreach (var typeParameter in sortedMap.Values)
{
var constraintTypes = typeParameter.ConstraintTypes;
if (constraintTypes.IsDefaultOrEmpty)
{
continue;
}
foreach (var type in constraintTypes)
{
// constraint itself is type parameter
typeParametersInConstraint.AddRange(TypeParameterCollector.Collect(type));
}
}
// pick up only valid type parameter and add them to the map
foreach (var typeParameter in typeParametersInConstraint)
{
AddTypeParameterToMap(typeParameter, sortedMap);
}
}
private void AppendMethodTypeParameterUsedDirectly(IDictionary<ISymbol, List<SyntaxToken>> symbolMap, IDictionary<int, ITypeParameterSymbol> sortedMap)
{
foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.TypeParameter))
{
var typeParameter = pair.Key as ITypeParameterSymbol;
if (typeParameter.DeclaringMethod == null ||
sortedMap.ContainsKey(typeParameter.Ordinal))
{
continue;
}
sortedMap[typeParameter.Ordinal] = typeParameter;
}
}
private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInConstraintList(
SemanticModel model,
IDictionary<ISymbol, VariableInfo> variableInfoMap,
IDictionary<ISymbol, List<SyntaxToken>> symbolMap,
SortedDictionary<int, ITypeParameterSymbol> sortedMap)
{
// find starting points
AppendMethodTypeVariableFromDataFlowAnalysis(model, variableInfoMap, sortedMap);
AppendMethodTypeParameterUsedDirectly(symbolMap, sortedMap);
// recursively dive into constraints to find all constraints needed
AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(sortedMap);
return sortedMap.Values.ToList();
}
private void AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(SortedDictionary<int, ITypeParameterSymbol> sortedMap)
{
var visited = new HashSet<ITypeSymbol>();
var candidates = SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
// collect all type parameter appears in constraint
foreach (var typeParameter in sortedMap.Values)
{
var constraintTypes = typeParameter.ConstraintTypes;
if (constraintTypes.IsDefaultOrEmpty)
{
continue;
}
foreach (var type in constraintTypes)
{
candidates = candidates.Concat(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(type, visited));
}
}
// pick up only valid type parameter and add them to the map
foreach (var typeParameter in candidates)
{
AddTypeParameterToMap(typeParameter, sortedMap);
}
}
private IEnumerable<ITypeParameterSymbol> AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(
ITypeSymbol type, HashSet<ITypeSymbol> visited)
{
if (visited.Contains(type))
{
return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
}
visited.Add(type);
if (type.OriginalDefinition.Equals(type))
{
return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
}
var constructedType = type as INamedTypeSymbol;
if (constructedType == null)
{
return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
}
var parameters = constructedType.GetAllTypeParameters().ToList();
var arguments = constructedType.GetAllTypeArguments().ToList();
Contract.ThrowIfFalse(parameters.Count == arguments.Count);
var typeParameters = new List<ITypeParameterSymbol>();
for (int i = 0; i < parameters.Count; i++)
{
var parameter = parameters[i];
var argument = arguments[i] as ITypeParameterSymbol;
if (argument != null)
{
// no constraint, nothing to do
if (!parameter.HasConstructorConstraint &&
!parameter.HasReferenceTypeConstraint &&
!parameter.HasValueTypeConstraint &&
parameter.ConstraintTypes.IsDefaultOrEmpty)
{
continue;
}
typeParameters.Add(argument);
continue;
}
var candidate = arguments[i] as INamedTypeSymbol;
if (candidate == null)
{
continue;
}
typeParameters.AddRange(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(candidate, visited));
}
return typeParameters;
}
private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInDeclaration(ITypeSymbol returnType, SortedDictionary<int, ITypeParameterSymbol> sortedMap)
{
// add return type to the map
AddTypeParametersToMap(TypeParameterCollector.Collect(returnType), sortedMap);
AppendMethodTypeParameterFromConstraint(sortedMap);
return sortedMap.Values.ToList();
}
private OperationStatus CheckReadOnlyFields(SemanticModel semanticModel, Dictionary<ISymbol, List<SyntaxToken>> symbolMap)
{
if (ReadOnlyFieldAllowed())
{
return OperationStatus.Succeeded;
}
List<string> names = null;
var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>();
foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.Field))
{
var field = (IFieldSymbol)pair.Key;
if (!field.IsReadOnly)
{
continue;
}
var tokens = pair.Value;
if (tokens.All(t => !semanticFacts.IsWrittenTo(semanticModel, t.Parent, CancellationToken)))
{
continue;
}
names = names ?? new List<string>();
names.Add(field.Name ?? string.Empty);
}
if (names != null)
{
return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Assigning_to_readonly_fields_must_be_done_in_a_constructor_colon_bracket_0_bracket, string.Join(", ", names)));
}
return OperationStatus.Succeeded;
}
private bool IsInstanceMemberUsedInSelectedCode(DataFlowAnalysis dataFlowAnalysisData)
{
Contract.ThrowIfNull(dataFlowAnalysisData);
// "this" can be used as a lvalue in a struct, check WrittenInside as well
return dataFlowAnalysisData.ReadInside.Any(s => IsThisParameter(s)) ||
dataFlowAnalysisData.WrittenInside.Any(s => IsThisParameter(s));
}
protected VariableInfo CreateFromSymbolCommon<T>(
Compilation compilation,
ISymbol symbol,
ITypeSymbol type,
VariableStyle style,
HashSet<int> nonNoisySyntaxKindSet) where T : SyntaxNode
{
var local = symbol as ILocalSymbol;
if (local != null)
{
return new VariableInfo(
new LocalVariableSymbol<T>(compilation, local, type, nonNoisySyntaxKindSet),
style);
}
var parameter = symbol as IParameterSymbol;
if (parameter != null)
{
return new VariableInfo(new ParameterVariableSymbol(compilation, parameter, type), style);
}
var rangeVariable = symbol as IRangeVariableSymbol;
if (rangeVariable != null)
{
return new VariableInfo(new QueryVariableSymbol(compilation, rangeVariable, type), style);
}
return Contract.FailWithReturn<VariableInfo>(FeaturesResources.Unknown);
}
}
}
}
| |
// 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;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SecurityProtocol.DefaultSecurityProtocols;
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = CredentialCache.DefaultCredentials;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _connectTimeout = TimeSpan.FromSeconds(60);
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = 64 * 1024;
private int _maxResponseDrainSize = 64 * 1024;
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: false);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan ConnectTimeout
{
get
{
return _connectTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_connectTimeout = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => ((WinHttpRequestState)s).Handler.StartRequest(s),
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (cookies != null)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (_sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(_sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(_sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
_sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
}
}
}
private async void StartRequest(object obj)
{
WinHttpRequestState state = (WinHttpRequestState)obj;
bool secureConnection = false;
HttpResponseMessage responseMessage = null;
Exception savedException = null;
SafeWinHttpHandle connectHandle = null;
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
try
{
EnsureSessionHandleExists(state);
SetSessionHandleOptions();
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
secureConnection = true;
}
else
{
secureConnection = false;
}
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state).ConfigureAwait(false);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false);
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
}
catch (Exception ex)
{
if (state.SavedException != null)
{
savedException = state.SavedException;
}
else
{
savedException = ex;
}
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
}
// Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting.
if (responseMessage != null)
{
state.Tcs.TrySetResult(responseMessage);
}
else
{
HandleAsyncException(state, savedException);
}
state.ClearSendRequestState();
}
private void SetSessionHandleOptions()
{
SetSessionHandleConnectionOptions();
SetSessionHandleTlsOptions();
SetSessionHandleTimeoutOptions();
}
private void SetSessionHandleConnectionOptions()
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions()
{
uint optionData = 0;
if ((_sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((_sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((_sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions()
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
_sessionHandle,
0,
(int)_connectTimeout.TotalMilliseconds,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = string.Format(
CultureInfo.InvariantCulture,
"{0}://{1}",
proxyUri.Scheme,
proxyUri.Authority);
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// Set WinHTTP to send/prevent default credentials for either proxy or server auth.
bool useDefaultCredentials = false;
if (state.ServerCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.WindowsProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
if (state.Proxy == null && _defaultProxyCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.Proxy != null && state.Proxy.Credentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
}
uint optionData = useDefaultCredentials ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY, ref optionData);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)_maxResponseHeadersLength;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
state.TcsReceiveResponseHeaders =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.TcsReceiveResponseHeaders.Task;
}
}
}
| |
// 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!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>ConversionValueRuleSet</c> resource.</summary>
public sealed partial class ConversionValueRuleSetName : gax::IResourceName, sys::IEquatable<ConversionValueRuleSetName>
{
/// <summary>The possible contents of <see cref="ConversionValueRuleSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
CustomerConversionValueRuleSet = 1,
}
private static gax::PathTemplate s_customerConversionValueRuleSet = new gax::PathTemplate("customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}");
/// <summary>Creates a <see cref="ConversionValueRuleSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ConversionValueRuleSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ConversionValueRuleSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ConversionValueRuleSetName"/> with the pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleSetName"/> constructed from the provided ids.
/// </returns>
public static ConversionValueRuleSetName FromCustomerConversionValueRuleSet(string customerId, string conversionValueRuleSetId) =>
new ConversionValueRuleSetName(ResourceNameType.CustomerConversionValueRuleSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </returns>
public static string Format(string customerId, string conversionValueRuleSetId) =>
FormatCustomerConversionValueRuleSet(customerId, conversionValueRuleSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </returns>
public static string FormatCustomerConversionValueRuleSet(string customerId, string conversionValueRuleSetId) =>
s_customerConversionValueRuleSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ConversionValueRuleSetName"/> if successful.</returns>
public static ConversionValueRuleSetName Parse(string conversionValueRuleSetName) =>
Parse(conversionValueRuleSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ConversionValueRuleSetName"/> if successful.</returns>
public static ConversionValueRuleSetName Parse(string conversionValueRuleSetName, bool allowUnparsed) =>
TryParse(conversionValueRuleSetName, allowUnparsed, out ConversionValueRuleSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleSetName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleSetName, out ConversionValueRuleSetName result) =>
TryParse(conversionValueRuleSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleSetName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleSetName, bool allowUnparsed, out ConversionValueRuleSetName result)
{
gax::GaxPreconditions.CheckNotNull(conversionValueRuleSetName, nameof(conversionValueRuleSetName));
gax::TemplatedResourceName resourceName;
if (s_customerConversionValueRuleSet.TryParseName(conversionValueRuleSetName, out resourceName))
{
result = FromCustomerConversionValueRuleSet(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(conversionValueRuleSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ConversionValueRuleSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversionValueRuleSetId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ConversionValueRuleSetId = conversionValueRuleSetId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ConversionValueRuleSetName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ConversionValueRuleSetName(string customerId, string conversionValueRuleSetId) : this(ResourceNameType.CustomerConversionValueRuleSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>ConversionValueRuleSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ConversionValueRuleSetId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerConversionValueRuleSet: return s_customerConversionValueRuleSet.Expand(CustomerId, ConversionValueRuleSetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ConversionValueRuleSetName);
/// <inheritdoc/>
public bool Equals(ConversionValueRuleSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ConversionValueRuleSetName a, ConversionValueRuleSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ConversionValueRuleSetName a, ConversionValueRuleSetName b) => !(a == b);
}
public partial class ConversionValueRuleSet
{
/// <summary>
/// <see cref="ConversionValueRuleSetName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ConversionValueRuleSetName ResourceNameAsConversionValueRuleSetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ConversionValueRuleSetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="ConversionValueRuleName"/>-typed view over the <see cref="ConversionValueRules"/> resource name
/// property.
/// </summary>
internal gax::ResourceNameList<ConversionValueRuleName> ConversionValueRulesAsConversionValueRuleNames
{
get => new gax::ResourceNameList<ConversionValueRuleName>(ConversionValueRules, s => string.IsNullOrEmpty(s) ? null : ConversionValueRuleName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="OwnerCustomer"/> resource name property.
/// </summary>
internal CustomerName OwnerCustomerAsCustomerName
{
get => string.IsNullOrEmpty(OwnerCustomer) ? null : CustomerName.Parse(OwnerCustomer, allowUnparsed: true);
set => OwnerCustomer = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using Etg.SimpleStubs;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Newtonsoft.Json;
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubIHttpClient : IHttpClient
{
private readonly StubContainer<StubIHttpClient> _stubs = new StubContainer<StubIHttpClient>();
string global::Sannel.House.ServerSDK.IHttpClient.GetCookieValue(global::System.Uri uri, string cookieName)
{
return _stubs.GetMethodStub<GetCookieValue_Uri_String_Delegate>("GetCookieValue").Invoke(uri, cookieName);
}
public delegate string GetCookieValue_Uri_String_Delegate(global::System.Uri uri, string cookieName);
public StubIHttpClient GetCookieValue(GetCookieValue_Uri_String_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.HttpClientResult> global::Sannel.House.ServerSDK.IHttpClient.GetAsync(global::System.Uri requestUri)
{
return _stubs.GetMethodStub<GetAsync_Uri_Delegate>("GetAsync").Invoke(requestUri);
}
public delegate global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.HttpClientResult> GetAsync_Uri_Delegate(global::System.Uri requestUri);
public StubIHttpClient GetAsync(GetAsync_Uri_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.HttpClientResult> global::Sannel.House.ServerSDK.IHttpClient.PostAsync(global::System.Uri requestUri, global::System.Collections.Generic.IDictionary<string, string> data)
{
return _stubs.GetMethodStub<PostAsync_Uri_IDictionaryOfStringString_Delegate>("PostAsync").Invoke(requestUri, data);
}
public delegate global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.HttpClientResult> PostAsync_Uri_IDictionaryOfStringString_Delegate(global::System.Uri requestUri, global::System.Collections.Generic.IDictionary<string, string> data);
public StubIHttpClient PostAsync(PostAsync_Uri_IDictionaryOfStringString_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
void global::System.IDisposable.Dispose()
{
_stubs.GetMethodStub<IDisposable_Dispose_Delegate>("Dispose").Invoke();
}
public delegate void IDisposable_Dispose_Delegate();
public StubIHttpClient Dispose(IDisposable_Dispose_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubIServerContext : IServerContext
{
private readonly StubContainer<StubIServerContext> _stubs = new StubContainer<StubIServerContext>();
bool global::Sannel.House.ServerSDK.IServerContext.IsAuthenticated
{
get
{
return _stubs.GetMethodStub<IsAuthenticated_Get_Delegate>("get_IsAuthenticated").Invoke();
}
}
global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.LoginResult> global::Sannel.House.ServerSDK.IServerContext.LoginAsync(string username, string password)
{
return _stubs.GetMethodStub<LoginAsync_String_String_Delegate>("LoginAsync").Invoke(username, password);
}
public delegate global::Windows.Foundation.IAsyncOperation<global::Sannel.House.ServerSDK.LoginResult> LoginAsync_String_String_Delegate(string username, string password);
public StubIServerContext LoginAsync(LoginAsync_String_String_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate bool IsAuthenticated_Get_Delegate();
public StubIServerContext IsAuthenticated_Get(IsAuthenticated_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
void global::System.IDisposable.Dispose()
{
_stubs.GetMethodStub<IDisposable_Dispose_Delegate>("Dispose").Invoke();
}
public delegate void IDisposable_Dispose_Delegate();
public StubIServerContext Dispose(IDisposable_Dispose_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubIServerSettings : IServerSettings
{
private readonly StubContainer<StubIServerSettings> _stubs = new StubContainer<StubIServerSettings>();
global::System.Uri global::Sannel.House.ServerSDK.IServerSettings.ServerUri
{
get
{
return _stubs.GetMethodStub<ServerUri_Get_Delegate>("get_ServerUri").Invoke();
}
set
{
_stubs.GetMethodStub<ServerUri_Set_Delegate>("put_ServerUri").Invoke(value);
}
}
public delegate global::System.Uri ServerUri_Get_Delegate();
public StubIServerSettings ServerUri_Get(ServerUri_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void ServerUri_Set_Delegate(global::System.Uri value);
public StubIServerSettings ServerUri_Set(ServerUri_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubIApplicationLogEntry : IApplicationLogEntry
{
private readonly StubContainer<StubIApplicationLogEntry> _stubs = new StubContainer<StubIApplicationLogEntry>();
global::System.Guid global::Sannel.House.ServerSDK.IApplicationLogEntry.Id
{
get
{
return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke();
}
set
{
_stubs.GetMethodStub<Id_Set_Delegate>("put_Id").Invoke(value);
}
}
int? global::Sannel.House.ServerSDK.IApplicationLogEntry.DeviceId
{
get
{
return _stubs.GetMethodStub<DeviceId_Get_Delegate>("get_DeviceId").Invoke();
}
set
{
_stubs.GetMethodStub<DeviceId_Set_Delegate>("put_DeviceId").Invoke(value);
}
}
string global::Sannel.House.ServerSDK.IApplicationLogEntry.ApplicationId
{
get
{
return _stubs.GetMethodStub<ApplicationId_Get_Delegate>("get_ApplicationId").Invoke();
}
set
{
_stubs.GetMethodStub<ApplicationId_Set_Delegate>("put_ApplicationId").Invoke(value);
}
}
string global::Sannel.House.ServerSDK.IApplicationLogEntry.Message
{
get
{
return _stubs.GetMethodStub<Message_Get_Delegate>("get_Message").Invoke();
}
set
{
_stubs.GetMethodStub<Message_Set_Delegate>("put_Message").Invoke(value);
}
}
string global::Sannel.House.ServerSDK.IApplicationLogEntry.Exception
{
get
{
return _stubs.GetMethodStub<Exception_Get_Delegate>("get_Exception").Invoke();
}
set
{
_stubs.GetMethodStub<Exception_Set_Delegate>("put_Exception").Invoke(value);
}
}
global::System.DateTimeOffset global::Sannel.House.ServerSDK.IApplicationLogEntry.CreatedDate
{
get
{
return _stubs.GetMethodStub<CreatedDate_Get_Delegate>("get_CreatedDate").Invoke();
}
set
{
_stubs.GetMethodStub<CreatedDate_Set_Delegate>("put_CreatedDate").Invoke(value);
}
}
public delegate global::System.Guid Id_Get_Delegate();
public StubIApplicationLogEntry Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Id_Set_Delegate(global::System.Guid value);
public StubIApplicationLogEntry Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate int? DeviceId_Get_Delegate();
public StubIApplicationLogEntry DeviceId_Get(DeviceId_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DeviceId_Set_Delegate(int? value);
public StubIApplicationLogEntry DeviceId_Set(DeviceId_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate string ApplicationId_Get_Delegate();
public StubIApplicationLogEntry ApplicationId_Get(ApplicationId_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void ApplicationId_Set_Delegate(string value);
public StubIApplicationLogEntry ApplicationId_Set(ApplicationId_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate string Message_Get_Delegate();
public StubIApplicationLogEntry Message_Get(Message_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Message_Set_Delegate(string value);
public StubIApplicationLogEntry Message_Set(Message_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate string Exception_Get_Delegate();
public StubIApplicationLogEntry Exception_Get(Exception_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Exception_Set_Delegate(string value);
public StubIApplicationLogEntry Exception_Set(Exception_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset CreatedDate_Get_Delegate();
public StubIApplicationLogEntry CreatedDate_Get(CreatedDate_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void CreatedDate_Set_Delegate(global::System.DateTimeOffset value);
public StubIApplicationLogEntry CreatedDate_Set(CreatedDate_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubICreateHelper : ICreateHelper
{
private readonly StubContainer<StubICreateHelper> _stubs = new StubContainer<StubICreateHelper>();
global::Sannel.House.ServerSDK.IDevice global::Sannel.House.ServerSDK.ICreateHelper.CreateDevice()
{
return _stubs.GetMethodStub<CreateDevice_Delegate>("CreateDevice").Invoke();
}
public delegate global::Sannel.House.ServerSDK.IDevice CreateDevice_Delegate();
public StubICreateHelper CreateDevice(CreateDevice_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
global::Sannel.House.ServerSDK.ITemperatureSetting global::Sannel.House.ServerSDK.ICreateHelper.CreateTemperatureSetting()
{
return _stubs.GetMethodStub<CreateTemperatureSetting_Delegate>("CreateTemperatureSetting").Invoke();
}
public delegate global::Sannel.House.ServerSDK.ITemperatureSetting CreateTemperatureSetting_Delegate();
public StubICreateHelper CreateTemperatureSetting(CreateTemperatureSetting_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
global::Sannel.House.ServerSDK.IApplicationLogEntry global::Sannel.House.ServerSDK.ICreateHelper.CreateApplicationLogEntry()
{
return _stubs.GetMethodStub<CreateApplicationLogEntry_Delegate>("CreateApplicationLogEntry").Invoke();
}
public delegate global::Sannel.House.ServerSDK.IApplicationLogEntry CreateApplicationLogEntry_Delegate();
public StubICreateHelper CreateApplicationLogEntry(CreateApplicationLogEntry_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
global::Sannel.House.ServerSDK.ITemperatureEntry global::Sannel.House.ServerSDK.ICreateHelper.CreateTemperatureEntry()
{
return _stubs.GetMethodStub<CreateTemperatureEntry_Delegate>("CreateTemperatureEntry").Invoke();
}
public delegate global::Sannel.House.ServerSDK.ITemperatureEntry CreateTemperatureEntry_Delegate();
public StubICreateHelper CreateTemperatureEntry(CreateTemperatureEntry_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubIDevice : IDevice
{
private readonly StubContainer<StubIDevice> _stubs = new StubContainer<StubIDevice>();
int global::Sannel.House.ServerSDK.IDevice.Id
{
get
{
return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke();
}
set
{
_stubs.GetMethodStub<Id_Set_Delegate>("put_Id").Invoke(value);
}
}
string global::Sannel.House.ServerSDK.IDevice.Name
{
get
{
return _stubs.GetMethodStub<Name_Get_Delegate>("get_Name").Invoke();
}
set
{
_stubs.GetMethodStub<Name_Set_Delegate>("put_Name").Invoke(value);
}
}
string global::Sannel.House.ServerSDK.IDevice.Description
{
get
{
return _stubs.GetMethodStub<Description_Get_Delegate>("get_Description").Invoke();
}
set
{
_stubs.GetMethodStub<Description_Set_Delegate>("put_Description").Invoke(value);
}
}
int global::Sannel.House.ServerSDK.IDevice.DisplayOrder
{
get
{
return _stubs.GetMethodStub<DisplayOrder_Get_Delegate>("get_DisplayOrder").Invoke();
}
set
{
_stubs.GetMethodStub<DisplayOrder_Set_Delegate>("put_DisplayOrder").Invoke(value);
}
}
global::System.DateTimeOffset global::Sannel.House.ServerSDK.IDevice.DateCreated
{
get
{
return _stubs.GetMethodStub<DateCreated_Get_Delegate>("get_DateCreated").Invoke();
}
set
{
_stubs.GetMethodStub<DateCreated_Set_Delegate>("put_DateCreated").Invoke(value);
}
}
bool global::Sannel.House.ServerSDK.IDevice.IsReadOnly
{
get
{
return _stubs.GetMethodStub<IsReadOnly_Get_Delegate>("get_IsReadOnly").Invoke();
}
set
{
_stubs.GetMethodStub<IsReadOnly_Set_Delegate>("put_IsReadOnly").Invoke(value);
}
}
public delegate int Id_Get_Delegate();
public StubIDevice Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Id_Set_Delegate(int value);
public StubIDevice Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate string Name_Get_Delegate();
public StubIDevice Name_Get(Name_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Name_Set_Delegate(string value);
public StubIDevice Name_Set(Name_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate string Description_Get_Delegate();
public StubIDevice Description_Get(Description_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Description_Set_Delegate(string value);
public StubIDevice Description_Set(Description_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate int DisplayOrder_Get_Delegate();
public StubIDevice DisplayOrder_Get(DisplayOrder_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DisplayOrder_Set_Delegate(int value);
public StubIDevice DisplayOrder_Set(DisplayOrder_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset DateCreated_Get_Delegate();
public StubIDevice DateCreated_Get(DateCreated_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DateCreated_Set_Delegate(global::System.DateTimeOffset value);
public StubIDevice DateCreated_Set(DateCreated_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate bool IsReadOnly_Get_Delegate();
public StubIDevice IsReadOnly_Get(IsReadOnly_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void IsReadOnly_Set_Delegate(bool value);
public StubIDevice IsReadOnly_Set(IsReadOnly_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubITemperatureEntry : ITemperatureEntry
{
private readonly StubContainer<StubITemperatureEntry> _stubs = new StubContainer<StubITemperatureEntry>();
global::System.Guid global::Sannel.House.ServerSDK.ITemperatureEntry.Id
{
get
{
return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke();
}
set
{
_stubs.GetMethodStub<Id_Set_Delegate>("put_Id").Invoke(value);
}
}
int global::Sannel.House.ServerSDK.ITemperatureEntry.DeviceId
{
get
{
return _stubs.GetMethodStub<DeviceId_Get_Delegate>("get_DeviceId").Invoke();
}
set
{
_stubs.GetMethodStub<DeviceId_Set_Delegate>("put_DeviceId").Invoke(value);
}
}
double global::Sannel.House.ServerSDK.ITemperatureEntry.TemperatureCelsius
{
get
{
return _stubs.GetMethodStub<TemperatureCelsius_Get_Delegate>("get_TemperatureCelsius").Invoke();
}
set
{
_stubs.GetMethodStub<TemperatureCelsius_Set_Delegate>("put_TemperatureCelsius").Invoke(value);
}
}
double global::Sannel.House.ServerSDK.ITemperatureEntry.Humidity
{
get
{
return _stubs.GetMethodStub<Humidity_Get_Delegate>("get_Humidity").Invoke();
}
set
{
_stubs.GetMethodStub<Humidity_Set_Delegate>("put_Humidity").Invoke(value);
}
}
double global::Sannel.House.ServerSDK.ITemperatureEntry.Pressure
{
get
{
return _stubs.GetMethodStub<Pressure_Get_Delegate>("get_Pressure").Invoke();
}
set
{
_stubs.GetMethodStub<Pressure_Set_Delegate>("put_Pressure").Invoke(value);
}
}
global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureEntry.CreatedDateTime
{
get
{
return _stubs.GetMethodStub<CreatedDateTime_Get_Delegate>("get_CreatedDateTime").Invoke();
}
set
{
_stubs.GetMethodStub<CreatedDateTime_Set_Delegate>("put_CreatedDateTime").Invoke(value);
}
}
public delegate global::System.Guid Id_Get_Delegate();
public StubITemperatureEntry Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Id_Set_Delegate(global::System.Guid value);
public StubITemperatureEntry Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate int DeviceId_Get_Delegate();
public StubITemperatureEntry DeviceId_Get(DeviceId_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DeviceId_Set_Delegate(int value);
public StubITemperatureEntry DeviceId_Set(DeviceId_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate double TemperatureCelsius_Get_Delegate();
public StubITemperatureEntry TemperatureCelsius_Get(TemperatureCelsius_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void TemperatureCelsius_Set_Delegate(double value);
public StubITemperatureEntry TemperatureCelsius_Set(TemperatureCelsius_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate double Humidity_Get_Delegate();
public StubITemperatureEntry Humidity_Get(Humidity_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Humidity_Set_Delegate(double value);
public StubITemperatureEntry Humidity_Set(Humidity_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate double Pressure_Get_Delegate();
public StubITemperatureEntry Pressure_Get(Pressure_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Pressure_Set_Delegate(double value);
public StubITemperatureEntry Pressure_Set(Pressure_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset CreatedDateTime_Get_Delegate();
public StubITemperatureEntry CreatedDateTime_Get(CreatedDateTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void CreatedDateTime_Set_Delegate(global::System.DateTimeOffset value);
public StubITemperatureEntry CreatedDateTime_Set(CreatedDateTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
namespace Sannel.House.ServerSDK
{
[CompilerGenerated]
public class StubITemperatureSetting : ITemperatureSetting
{
private readonly StubContainer<StubITemperatureSetting> _stubs = new StubContainer<StubITemperatureSetting>();
long global::Sannel.House.ServerSDK.ITemperatureSetting.Id
{
get
{
return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke();
}
set
{
_stubs.GetMethodStub<Id_Set_Delegate>("put_Id").Invoke(value);
}
}
int? global::Sannel.House.ServerSDK.ITemperatureSetting.DayOfWeek
{
get
{
return _stubs.GetMethodStub<DayOfWeek_Get_Delegate>("get_DayOfWeek").Invoke();
}
set
{
_stubs.GetMethodStub<DayOfWeek_Set_Delegate>("put_DayOfWeek").Invoke(value);
}
}
int? global::Sannel.House.ServerSDK.ITemperatureSetting.Month
{
get
{
return _stubs.GetMethodStub<Month_Get_Delegate>("get_Month").Invoke();
}
set
{
_stubs.GetMethodStub<Month_Set_Delegate>("put_Month").Invoke(value);
}
}
bool global::Sannel.House.ServerSDK.ITemperatureSetting.IsTimeOnly
{
get
{
return _stubs.GetMethodStub<IsTimeOnly_Get_Delegate>("get_IsTimeOnly").Invoke();
}
set
{
_stubs.GetMethodStub<IsTimeOnly_Set_Delegate>("put_IsTimeOnly").Invoke(value);
}
}
global::System.DateTimeOffset? global::Sannel.House.ServerSDK.ITemperatureSetting.StartTime
{
get
{
return _stubs.GetMethodStub<StartTime_Get_Delegate>("get_StartTime").Invoke();
}
set
{
_stubs.GetMethodStub<StartTime_Set_Delegate>("put_StartTime").Invoke(value);
}
}
global::System.DateTimeOffset? global::Sannel.House.ServerSDK.ITemperatureSetting.EndTime
{
get
{
return _stubs.GetMethodStub<EndTime_Get_Delegate>("get_EndTime").Invoke();
}
set
{
_stubs.GetMethodStub<EndTime_Set_Delegate>("put_EndTime").Invoke(value);
}
}
double global::Sannel.House.ServerSDK.ITemperatureSetting.HeatTemperatureC
{
get
{
return _stubs.GetMethodStub<HeatTemperatureC_Get_Delegate>("get_HeatTemperatureC").Invoke();
}
set
{
_stubs.GetMethodStub<HeatTemperatureC_Set_Delegate>("put_HeatTemperatureC").Invoke(value);
}
}
double global::Sannel.House.ServerSDK.ITemperatureSetting.CoolTemperatureC
{
get
{
return _stubs.GetMethodStub<CoolTemperatureC_Get_Delegate>("get_CoolTemperatureC").Invoke();
}
set
{
_stubs.GetMethodStub<CoolTemperatureC_Set_Delegate>("put_CoolTemperatureC").Invoke(value);
}
}
global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureSetting.DateCreated
{
get
{
return _stubs.GetMethodStub<DateCreated_Get_Delegate>("get_DateCreated").Invoke();
}
set
{
_stubs.GetMethodStub<DateCreated_Set_Delegate>("put_DateCreated").Invoke(value);
}
}
global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureSetting.DateModified
{
get
{
return _stubs.GetMethodStub<DateModified_Get_Delegate>("get_DateModified").Invoke();
}
set
{
_stubs.GetMethodStub<DateModified_Set_Delegate>("put_DateModified").Invoke(value);
}
}
public delegate long Id_Get_Delegate();
public StubITemperatureSetting Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Id_Set_Delegate(long value);
public StubITemperatureSetting Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate int? DayOfWeek_Get_Delegate();
public StubITemperatureSetting DayOfWeek_Get(DayOfWeek_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DayOfWeek_Set_Delegate(int? value);
public StubITemperatureSetting DayOfWeek_Set(DayOfWeek_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate int? Month_Get_Delegate();
public StubITemperatureSetting Month_Get(Month_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void Month_Set_Delegate(int? value);
public StubITemperatureSetting Month_Set(Month_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate bool IsTimeOnly_Get_Delegate();
public StubITemperatureSetting IsTimeOnly_Get(IsTimeOnly_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void IsTimeOnly_Set_Delegate(bool value);
public StubITemperatureSetting IsTimeOnly_Set(IsTimeOnly_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset? StartTime_Get_Delegate();
public StubITemperatureSetting StartTime_Get(StartTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void StartTime_Set_Delegate(global::System.DateTimeOffset? value);
public StubITemperatureSetting StartTime_Set(StartTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset? EndTime_Get_Delegate();
public StubITemperatureSetting EndTime_Get(EndTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void EndTime_Set_Delegate(global::System.DateTimeOffset? value);
public StubITemperatureSetting EndTime_Set(EndTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate double HeatTemperatureC_Get_Delegate();
public StubITemperatureSetting HeatTemperatureC_Get(HeatTemperatureC_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void HeatTemperatureC_Set_Delegate(double value);
public StubITemperatureSetting HeatTemperatureC_Set(HeatTemperatureC_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate double CoolTemperatureC_Get_Delegate();
public StubITemperatureSetting CoolTemperatureC_Get(CoolTemperatureC_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void CoolTemperatureC_Set_Delegate(double value);
public StubITemperatureSetting CoolTemperatureC_Set(CoolTemperatureC_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset DateCreated_Get_Delegate();
public StubITemperatureSetting DateCreated_Get(DateCreated_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DateCreated_Set_Delegate(global::System.DateTimeOffset value);
public StubITemperatureSetting DateCreated_Set(DateCreated_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate global::System.DateTimeOffset DateModified_Get_Delegate();
public StubITemperatureSetting DateModified_Get(DateModified_Get_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
public delegate void DateModified_Set_Delegate(global::System.DateTimeOffset value);
public StubITemperatureSetting DateModified_Set(DateModified_Set_Delegate del, int count = Times.Forever, bool overwrite = false)
{
_stubs.SetMethodStub(del, count, overwrite);
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
using WTM.Api.Areas.HelpPage.SampleGeneration;
namespace WTM.Api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
namespace Stripe
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Stripe.Infrastructure;
#if NET45 || NETSTANDARD2_0
using System.Configuration;
#endif
/// <summary>
/// Global configuration class for Stripe.net settings.
/// </summary>
public static class StripeConfiguration
{
private static string apiKey;
private static AppInfo appInfo;
private static string clientId;
private static int maxNetworkRetries;
private static IStripeClient stripeClient;
static StripeConfiguration()
{
StripeNetVersion = new AssemblyName(typeof(StripeConfiguration).GetTypeInfo().Assembly.FullName).Version.ToString(3);
}
/// <summary>API version used by Stripe.net.</summary>
public static string ApiVersion => "2019-05-16";
#if NET45 || NETSTANDARD2_0
/// <summary>Gets or sets the API key.</summary>
/// <remarks>
/// You can also set the API key using the <c>StripeApiKey</c> key in
/// <see cref="System.Configuration.ConfigurationManager.AppSettings"/>.
/// </remarks>
#else
/// <summary>Gets or sets the API key.</summary>
#endif
public static string ApiKey
{
get
{
#if NET45 || NETSTANDARD2_0
if (string.IsNullOrEmpty(apiKey) &&
!string.IsNullOrEmpty(ConfigurationManager.AppSettings["StripeApiKey"]))
{
apiKey = ConfigurationManager.AppSettings["StripeApiKey"];
}
#endif
return apiKey;
}
set
{
if (value != apiKey)
{
StripeClient = null;
}
apiKey = value;
}
}
#if NET45 || NETSTANDARD2_0
/// <summary>Gets or sets the client ID.</summary>
/// <remarks>
/// You can also set the client ID using the <c>StripeClientId</c> key in
/// <see cref="System.Configuration.ConfigurationManager.AppSettings"/>.
/// </remarks>
#else
/// <summary>Gets or sets the client ID.</summary>
#endif
public static string ClientId
{
get
{
#if NET45 || NETSTANDARD2_0
if (string.IsNullOrEmpty(apiKey) &&
!string.IsNullOrEmpty(ConfigurationManager.AppSettings["StripeClientId"]))
{
clientId = ConfigurationManager.AppSettings["StripeClientId"];
}
#endif
return clientId;
}
set
{
if (value != clientId)
{
StripeClient = null;
}
clientId = value;
}
}
/// <summary>
/// Gets or sets the settings used for deserializing JSON objects returned by Stripe's API.
/// It is highly recommended you do not change these settings, as doing so can produce
/// unexpected results. If you do change these settings, make sure that
/// <see cref="Stripe.Infrastructure.StripeObjectConverter"/> is among the converters,
/// otherwise Stripe.net will no longer be able to deserialize polymorphic resources
/// represented by interfaces (e.g. <see cref="IPaymentSource"/>).
/// </summary>
public static JsonSerializerSettings SerializerSettings { get; set; } = DefaultSerializerSettings();
/// <summary>
/// Gets or sets the maximum number of times that the library will retry requests that
/// appear to have failed due to an intermittent problem.
/// </summary>
public static int MaxNetworkRetries
{
get => maxNetworkRetries;
set
{
if (value != maxNetworkRetries)
{
StripeClient = null;
}
maxNetworkRetries = value;
}
}
/// <summary>
/// Gets or sets a custom <see cref="StripeClient"/> for sending requests to Stripe's
/// API. You can use this to use a custom message handler, set proxy parameters, etc.
/// </summary>
/// <example>
/// To use a custom message handler:
/// <code>
/// System.Net.Http.HttpMessageHandler messageHandler = ...;
/// var httpClient = new System.Net.HttpClient(messageHandler);
/// var stripeClient = new Stripe.StripeClient(
/// stripeApiKey,
/// httpClient: new Stripe.SystemNetHttpClient(httpClient));
/// Stripe.StripeConfiguration.StripeClient = stripeClient;
/// </code>
/// </example>
public static IStripeClient StripeClient
{
get
{
if (stripeClient == null)
{
stripeClient = BuildDefaultStripeClient();
}
return stripeClient;
}
set => stripeClient = value;
}
/// <summary>Gets the version of the Stripe.net client library.</summary>
public static string StripeNetVersion { get; }
/// <summary>
/// Sets information about the "app" which this integration belongs to. This should be
/// reserved for plugins that wish to identify themselves with Stripe.
/// </summary>
public static AppInfo AppInfo
{
internal get => appInfo;
set
{
if ((value != null) && string.IsNullOrEmpty(value.Name))
{
throw new ArgumentException("AppInfo.Name cannot be empty");
}
if (value != appInfo)
{
StripeClient = null;
}
appInfo = value;
}
}
/// <summary>
/// Returns a new instance of <see cref="Newtonsoft.Json.JsonSerializerSettings"/> with
/// the default settings used by Stripe.net.
/// </summary>
/// <returns>A <see cref="Newtonsoft.Json.JsonSerializerSettings"/> instance.</returns>
public static JsonSerializerSettings DefaultSerializerSettings()
{
return new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new StripeObjectConverter(),
},
DateParseHandling = DateParseHandling.None,
};
}
/// <summary>
/// Sets the API key.
/// This method is deprecated and will be removed in a future version, please use the
/// <see cref="ApiKey"/> property setter instead.
/// </summary>
/// <param name="newApiKey">API key.</param>
// TODO; remove this method in a future major version
[Obsolete("Use StripeConfiguration.ApiKey setter instead.")]
public static void SetApiKey(string newApiKey)
{
ApiKey = newApiKey;
}
private static StripeClient BuildDefaultStripeClient()
{
if (ApiKey != null && ApiKey.Length == 0)
{
var message = "Your API key is invalid, as it is an empty string. You can "
+ "double-check your API key from the Stripe Dashboard. See "
+ "https://stripe.com/docs/api/authentication for details or contact support "
+ "at https://support.stripe.com/email if you have any questions.";
throw new StripeException(message);
}
if (ApiKey != null && StringUtils.ContainsWhitespace(ApiKey))
{
var message = "Your API key is invalid, as it contains whitespace. You can "
+ "double-check your API key from the Stripe Dashboard. See "
+ "https://stripe.com/docs/api/authentication for details or contact support "
+ "at https://support.stripe.com/email if you have any questions.";
throw new StripeException(message);
}
var httpClient = new SystemNetHttpClient(
httpClient: null,
maxNetworkRetries: MaxNetworkRetries,
appInfo: AppInfo);
return new StripeClient(ApiKey, ClientId, httpClient: httpClient);
}
}
}
| |
// 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.ServerManagement
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for NodeOperations.
/// </summary>
public static partial class NodeOperationsExtensions
{
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
public static NodeResource Create(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string))
{
return Task.Factory.StartNew(s => ((INodeOperations)s).CreateAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NodeResource> CreateAsync(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
public static NodeResource BeginCreate(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string))
{
return Task.Factory.StartNew(s => ((INodeOperations)s).BeginCreateAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NodeResource> BeginCreateAsync(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
public static NodeResource Update(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string))
{
return Task.Factory.StartNew(s => ((INodeOperations)s).UpdateAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NodeResource> UpdateAsync(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
public static NodeResource BeginUpdate(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string))
{
return Task.Factory.StartNew(s => ((INodeOperations)s).BeginUpdateAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NodeResource> BeginUpdateAsync(this INodeOperations operations, string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// deletes a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
public static void Delete(this INodeOperations operations, string resourceGroupName, string nodeName)
{
Task.Factory.StartNew(s => ((INodeOperations)s).DeleteAsync(resourceGroupName, nodeName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// deletes a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INodeOperations operations, string resourceGroupName, string nodeName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, nodeName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// gets a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
public static NodeResource Get(this INodeOperations operations, string resourceGroupName, string nodeName)
{
return Task.Factory.StartNew(s => ((INodeOperations)s).GetAsync(resourceGroupName, nodeName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// gets a management node
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NodeResource> GetAsync(this INodeOperations operations, string resourceGroupName, string nodeName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, nodeName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns nodes in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NodeResource> List(this INodeOperations operations)
{
return Task.Factory.StartNew(s => ((INodeOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns nodes in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeResource>> ListAsync(this INodeOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns nodes in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
public static IPage<NodeResource> ListForResourceGroup(this INodeOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((INodeOperations)s).ListForResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns nodes in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeResource>> ListForResourceGroupAsync(this INodeOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns nodes in a subscription
/// </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<NodeResource> ListNext(this INodeOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INodeOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns nodes in a subscription
/// </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<NodeResource>> ListNextAsync(this INodeOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns nodes in a resource group
/// </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<NodeResource> ListForResourceGroupNext(this INodeOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INodeOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns nodes in a resource group
/// </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<NodeResource>> ListForResourceGroupNextAsync(this INodeOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using MagicOnion.GeneratorCore.Utils;
using MagicOnion.Utils;
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MagicOnion.CodeAnalysis
{
public class ReferenceSymbols
{
public readonly INamedTypeSymbol Void;
public readonly INamedTypeSymbol Task;
public readonly INamedTypeSymbol TaskOfT;
public readonly INamedTypeSymbol UnaryResult;
public readonly INamedTypeSymbol ClientStreamingResult;
public readonly INamedTypeSymbol ServerStreamingResult;
public readonly INamedTypeSymbol DuplexStreamingResult;
public readonly INamedTypeSymbol IServiceMarker;
public readonly INamedTypeSymbol IService;
public readonly INamedTypeSymbol IStreamingHubMarker;
public readonly INamedTypeSymbol IStreamingHub;
public readonly INamedTypeSymbol MethodIdAttribute;
public ReferenceSymbols(Compilation compilation, Action<string> logger)
{
Void = compilation.GetTypeByMetadataName("System.Void");
if (Void == null)
{
logger("failed to get metadata of System.Void.");
}
TaskOfT = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1");
if (TaskOfT == null)
{
logger("failed to get metadata of System.Threading.Tasks.Task`1.");
}
Task = compilation.GetTypeByMetadataName("System.Threading.Tasks.Task");
if (Task == null)
{
logger("failed to get metadata of System.Threading.Tasks.Task.");
}
INamedTypeSymbol GetTypeSymbolOrThrow(string name)
{
var symbol = compilation.GetTypeByMetadataName(name);
if (symbol == null)
{
throw new InvalidOperationException("failed to get metadata of " + name);
}
return symbol;
}
UnaryResult = GetTypeSymbolOrThrow("MagicOnion.UnaryResult`1");
ClientStreamingResult = GetTypeSymbolOrThrow("MagicOnion.ClientStreamingResult`2");
DuplexStreamingResult = GetTypeSymbolOrThrow("MagicOnion.DuplexStreamingResult`2");
ServerStreamingResult = GetTypeSymbolOrThrow("MagicOnion.ServerStreamingResult`1");
IStreamingHubMarker = GetTypeSymbolOrThrow("MagicOnion.IStreamingHubMarker");
IServiceMarker = GetTypeSymbolOrThrow("MagicOnion.IServiceMarker");
IStreamingHub = GetTypeSymbolOrThrow("MagicOnion.IStreamingHub`2");
IService = GetTypeSymbolOrThrow("MagicOnion.IService`1");
MethodIdAttribute = GetTypeSymbolOrThrow("MagicOnion.Server.Hubs.MethodIdAttribute");
}
}
public class MethodCollector
{
static readonly SymbolDisplayFormat binaryWriteFormat = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
static readonly SymbolDisplayFormat shortTypeNameFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
readonly string csProjPath;
readonly INamedTypeSymbol[] serviceInterfaces;
readonly INamedTypeSymbol[] hubInterfaces;
readonly ReferenceSymbols typeReferences;
public MethodCollector(string csProjPath, IEnumerable<string> conditinalSymbols, Action<string> logger)
{
this.csProjPath = csProjPath;
var compilation = PseudoCompilation.CreateFromProjectAsync(new[] { csProjPath }, conditinalSymbols.ToArray(), CancellationToken.None).GetAwaiter().GetResult();
this.typeReferences = new ReferenceSymbols(compilation, logger);
var bothInterfaces = compilation.GetNamedTypeSymbols()
.Where(x => x.TypeKind == TypeKind.Interface)
.Where(x =>
{
var all = x.AllInterfaces;
if (all.Any(y => y.ApproximatelyEqual(typeReferences.IServiceMarker)) || all.Any(y => y.ApproximatelyEqual(typeReferences.IStreamingHubMarker)))
{
return true;
}
return false;
})
.ToArray();
serviceInterfaces = bothInterfaces
.Where(x => x.AllInterfaces.Any(y => y.ApproximatelyEqual(typeReferences.IServiceMarker)) && x.AllInterfaces.All(y => !y.ApproximatelyEqual(typeReferences.IStreamingHubMarker)))
.Where(x => !x.ConstructedFrom.ApproximatelyEqual(this.typeReferences.IService))
.Distinct()
.ToArray();
hubInterfaces = bothInterfaces
.Where(x => x.AllInterfaces.Any(y => y.ApproximatelyEqual(typeReferences.IStreamingHubMarker)))
.Where(x => !x.ConstructedFrom.ApproximatelyEqual(this.typeReferences.IStreamingHub))
.Distinct()
.ToArray();
}
public InterfaceDefinition[] CollectServiceInterface()
{
return serviceInterfaces
.Select(x => new InterfaceDefinition()
{
Name = x.ToDisplayString(shortTypeNameFormat),
FullName = x.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
Namespace = x.ContainingNamespace.IsGlobalNamespace ? null : x.ContainingNamespace.ToDisplayString(),
IsServiceDefinition = true,
IsIfDebug = x.GetAttributes().FindAttributeShortName("GenerateDefineDebugAttribute") != null,
Methods = x.GetMembers()
.OfType<IMethodSymbol>()
.Select(CreateMethodDefinition)
.ToArray()
})
.OrderBy(x => x.FullName)
.ToArray();
}
public (InterfaceDefinition hubDefinition, InterfaceDefinition receiverDefintion)[] CollectHubInterface()
{
return hubInterfaces
.Select(x =>
{
var hubDefinition = new InterfaceDefinition()
{
Name = x.ToDisplayString(shortTypeNameFormat),
FullName = x.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
Namespace = x.ContainingNamespace.IsGlobalNamespace ? null : x.ContainingNamespace.ToDisplayString(),
IsIfDebug = x.GetAttributes().FindAttributeShortName("GenerateDefineDebugAttribute") != null,
Methods = x.GetMembers()
.OfType<IMethodSymbol>()
.Select(CreateMethodDefinition)
.ToArray()
};
var receiver = x.AllInterfaces.First(y => y.ConstructedFrom.ApproximatelyEqual(this.typeReferences.IStreamingHub)).TypeArguments[1];
var receiverDefinition = new InterfaceDefinition()
{
Name = receiver.ToDisplayString(shortTypeNameFormat),
FullName = receiver.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
Namespace = receiver.ContainingNamespace.IsGlobalNamespace ? null : receiver.ContainingNamespace.ToDisplayString(),
IsIfDebug = receiver.GetAttributes().FindAttributeShortName("GenerateDefineDebugAttribute") != null,
Methods = receiver.GetMembers()
.OfType<IMethodSymbol>()
.Select(CreateMethodDefinition)
.ToArray()
};
return (hubDefinition, receiverDefinition);
})
.OrderBy(x => x.hubDefinition.FullName)
.ThenBy(x => x.receiverDefinition.FullName)
.ToArray();
}
private class MethodNameComparer : IEqualityComparer<IMethodSymbol>
{
public static IEqualityComparer<IMethodSymbol> Instance { get; } = new MethodNameComparer();
public bool Equals(IMethodSymbol x, IMethodSymbol y)
{
return x.Name == y.Name;
}
public int GetHashCode(IMethodSymbol obj)
{
return obj.Name.GetHashCode();
}
}
private MethodDefinition CreateMethodDefinition(IMethodSymbol y)
{
MethodType t;
string requestType;
string responseType;
ITypeSymbol unwrappedOriginalResponseType;
ExtractRequestResponseType(y, out t, out requestType, out responseType, out unwrappedOriginalResponseType);
var id = FNV1A32.GetHashCode(y.Name);
var idAttr = y.GetAttributes().FindAttributeShortName("MethodIdAttribute");
if (idAttr != null)
{
id = (int)idAttr.ConstructorArguments[0].Value;
}
return new MethodDefinition(typeReferences)
{
Name = y.Name,
MethodType = t,
RequestType = requestType,
ResponseType = responseType,
UnwrappedOriginalResposneTypeSymbol = unwrappedOriginalResponseType,
OriginalResponseTypeSymbol = y.ReturnType,
IsIfDebug = y.GetAttributes().FindAttributeShortName("GenerateDefineDebugAttribute") != null,
HubId = id,
Parameters = y.Parameters.Select(p =>
{
return new ParameterDefinition
{
ParameterName = p.Name,
TypeName = p.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
HasDefaultValue = p.HasExplicitDefaultValue,
DefaultValue = GetDefaultValue(p),
OriginalSymbol = p
};
}).ToArray()
};
}
void ExtractRequestResponseType(IMethodSymbol method, out MethodType methodType, out string requestType, out string responseType, out ITypeSymbol unwrappedOriginalResponseType)
{
// Acceptable ReturnTypes:
// - Void
// - UnaryResult<T>
// - Task<ServerStreamingResult<TResponse>>
// - Task<ClientStreamingResult<TRequest, TResponse>>
// - Task<DuplexStreamingResult<TRequest, TResponse>>
// - Task (for StreamingHub)
// - Task<T> (for StreamingHub)
var retType = method.ReturnType as INamedTypeSymbol;
var isTaskResponse = false;
ITypeSymbol retType2 = null;
if (retType == null)
{
goto EMPTY;
}
if (!retType.IsGenericType && !retType.ApproximatelyEqual(typeReferences.Task) && !retType.ApproximatelyEqual(typeReferences.Void))
{
throw new InvalidOperationException($"A return type of a method must be 'void', 'UnaryResult<T>', 'Task<T>', 'Task'. (Method: {method.ToDisplayString()}, Return: {retType.ToDisplayString()})");
}
var constructedFrom = retType.ConstructedFrom;
// Task<T>
if (constructedFrom.ApproximatelyEqual(typeReferences.TaskOfT))
{
isTaskResponse = true;
retType2 = retType.TypeArguments[0];
retType = retType2 as INamedTypeSymbol;
constructedFrom = retType?.ConstructedFrom;
if (constructedFrom.ApproximatelyEqual(typeReferences.UnaryResult) ||
constructedFrom.ApproximatelyEqual(typeReferences.ServerStreamingResult) ||
constructedFrom.ApproximatelyEqual(typeReferences.ClientStreamingResult) ||
constructedFrom.ApproximatelyEqual(typeReferences.DuplexStreamingResult))
{
// Unwrap T (No-op)
}
else
{
// Task<T> (for StreamingHub method)
methodType = MethodType.Other;
requestType = null;
responseType = null;
unwrappedOriginalResponseType = retType2;
return;
}
}
// UnaryResult<T>
if (constructedFrom.ApproximatelyEqual(typeReferences.UnaryResult))
{
methodType = MethodType.Unary;
requestType = (method.Parameters.Length == 1) ? method.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) : null;
responseType = retType.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
unwrappedOriginalResponseType = retType.TypeArguments[0];
// Cannot allow to use StreamingResult as a type parameter of UnaryResult.
if (retType.TypeArguments[0] is INamedTypeSymbol retTypeTypeArg0 &&
(
retTypeTypeArg0.ConstructedFrom.ApproximatelyEqual(typeReferences.ServerStreamingResult) ||
retTypeTypeArg0.ConstructedFrom.ApproximatelyEqual(typeReferences.ClientStreamingResult) ||
retTypeTypeArg0.ConstructedFrom.ApproximatelyEqual(typeReferences.DuplexStreamingResult)
)
)
{
throw new InvalidOperationException($"Cannot allow to use StreamingResult as a type parameter of UnaryResult. (Method: {method.ToDisplayString()}, Return: {retType.ToDisplayString()})");
}
return;
}
// ServerStreamingResult<TResponse>
// ClientStreamingResult<TRequest, TResponse>
// DuplexStreamingResult<TRequest, TResponse>
if (constructedFrom.ApproximatelyEqual(typeReferences.ServerStreamingResult))
{
if (!isTaskResponse)
{
throw new InvalidOperationException($"CodeGenerator doesn't support generating non-asynchronous StreamingResult call. (Method: {method.ToDisplayString()}, Return: {retType.ToDisplayString()})");
}
methodType = MethodType.ServerStreaming;
requestType = (method.Parameters.Length == 1) ? method.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) : null;
responseType = retType.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
unwrappedOriginalResponseType = retType.TypeArguments[0];
return;
}
else if (constructedFrom.ApproximatelyEqual(typeReferences.ClientStreamingResult))
{
if (!isTaskResponse)
{
throw new InvalidOperationException($"CodeGenerator doesn't support generating non-asynchronous StreamingResult call. (Method: {method.ToDisplayString()}, Return: {retType.ToDisplayString()})");
}
methodType = MethodType.ClientStreaming;
requestType = retType.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
responseType = retType.TypeArguments[1].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
unwrappedOriginalResponseType = retType.TypeArguments[1];
return;
}
else if (constructedFrom.ApproximatelyEqual(typeReferences.DuplexStreamingResult))
{
if (!isTaskResponse)
{
throw new InvalidOperationException($"CodeGenerator doesn't support generating non-asynchronous StreamingResult call. (Method: {method.ToDisplayString()}, Return: {retType.ToDisplayString()})");
}
methodType = MethodType.DuplexStreaming;
requestType = retType.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
responseType = retType.TypeArguments[1].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
unwrappedOriginalResponseType = retType.TypeArguments[1];
return;
}
EMPTY:
// no validation
methodType = MethodType.Other;
requestType = null;
responseType = null;
unwrappedOriginalResponseType = (retType == null) ? retType2 : (retType.TypeArguments.Length != 0) ? retType.TypeArguments[0] : retType;
}
string GetDefaultValue(IParameterSymbol p)
{
if (p.HasExplicitDefaultValue)
{
var ppp = p.ToDisplayParts(new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue));
if (!ppp.Any(x => x.Kind == SymbolDisplayPartKind.Keyword && x.ToString() == "default"))
{
var l = ppp.Last();
if (l.Kind == SymbolDisplayPartKind.FieldName)
{
return l.Symbol.ToDisplayString();
}
else
{
return l.ToString();
}
}
}
return "default(" + p.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")";
}
}
}
namespace MagicOnion.Utils
{
public static class FNV1A32
{
public static int GetHashCode(string str)
{
return GetHashCode(Encoding.UTF8.GetBytes(str));
}
public static int GetHashCode(byte[] obj)
{
uint hash = 0;
if (obj != null)
{
hash = 2166136261;
for (int i = 0; i < obj.Length; i++)
{
hash = unchecked((obj[i] ^ hash) * 16777619);
}
}
return unchecked((int)hash);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace TestFlask.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UnitTestProject1.Domain;
namespace ExpressionEvaluator.Tests
{
[TestClass]
public class CodeBlockTests
{
[TestMethod]
public void LocalImplicitVariables()
{
var registry = new TypeRegistry();
object obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
var cc = new CompiledExpression() { StringToParse = "var x = new objHolder(); x.number = 3; x.number++; var varname = 23; varname++; obj.number = varname - x.number;", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
var result = cc.Eval();
}
[TestMethod]
public void WhileLoop()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
var cc = new CompiledExpression() { StringToParse = "while (obj.number < 10) { obj.number++; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(10, obj.number);
}
[TestMethod]
public void ForLoop()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
for (var i = 0; i < 10; i++) { obj.number2++; }
var cc = new CompiledExpression() { StringToParse = "for(var i = 0; i < 10; i++) { obj.number++; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(obj.number2, obj.number);
}
[TestMethod]
public void ForLoopWithMultipleIterators()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
for (int i = 0, j = 0; i < 10; i++, j++) { obj.number2 = j; }
var cc = new CompiledExpression() { StringToParse = "for(int i = 0, j = 0; i < 10; i++, j++) { obj.number = j; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(9, obj.number);
Assert.AreEqual(obj.number2, obj.number);
}
[TestMethod]
public void ForEachLoop()
{
var registry = new TypeRegistry();
var obj = new objHolder() { iterator = new List<string>() { "Hello", "there", "world" } };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("Debug", typeof(Debug));
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
//var iterator = new List<string>() { "Hello", "there", "world" };
//var enumerator = iterator.GetEnumerator();
//while (enumerator.MoveNext())
//{
// var word = enumerator.Current;
// Debug.WriteLine(word);
//}
var cc = new CompiledExpression() { StringToParse = "foreach(var word in obj.iterator) { Debug.WriteLine(word); }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
}
[TestMethod]
public void ForEachLoopNoBlock()
{
var registry = new TypeRegistry();
var obj = new objHolder() { iterator = new List<string>() { "Hello", "there", "world" } };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("Debug", typeof(Debug));
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
//var iterator = new List<string>() { "Hello", "there", "world" };
//var enumerator = iterator.GetEnumerator();
//while (enumerator.MoveNext())
//{
// var word = enumerator.Current;
// Debug.WriteLine(word);
//}
var cc = new CompiledExpression() { StringToParse = "foreach(var word in obj.iterator) Debug.WriteLine(word);", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
}
[TestMethod]
public void ForEachLoopArray()
{
var registry = new TypeRegistry();
var obj = new objHolder() { stringIterator = new[] { "Hello", "there", "world" } };
//foreach (var word in obj.stringIterator) { Debug.WriteLine(word); }
var enumerator = obj.stringIterator.GetEnumerator();
while (enumerator.MoveNext())
{
string word = (string)enumerator.Current;
Debug.WriteLine(word);
}
registry.RegisterSymbol("obj", obj);
registry.RegisterType("Debug", typeof(Debug));
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
var cc = new CompiledExpression() { StringToParse = "foreach(var word in obj.stringIterator) { Debug.WriteLine(word); }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
}
[TestMethod]
public void ForLoopWithContinue()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
var obj2 = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
for (var i = 0; i < 10; i++) { obj2.number++; if (i > 5) continue; obj2.number2++; }
var cc = new CompiledExpression() { StringToParse = "for(var i = 0; i < 10; i++) { obj.number++; if(i > 5) continue; obj.number2++; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(obj2.number, obj.number);
Assert.AreEqual(obj2.number2, obj.number2);
}
[TestMethod]
public void ForLoopWithBreak()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
var obj2 = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
for (var i = 0; i < 10; i++) { obj2.number++; if (i > 5) break; obj2.number2++; }
var cc = new CompiledExpression() { StringToParse = "for(var i = 0; i < 10; i++) { obj.number++; if(i > 5) break; obj.number2++; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(obj2.number, obj.number);
Assert.AreEqual(obj2.number2, obj.number2);
}
[TestMethod]
public void WhileLoopWithBreak()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
var cc = new CompiledExpression() { StringToParse = "while (obj.number < 10) { obj.number++; if(obj.number == 5) break; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(5, obj.number);
}
[TestMethod]
public void NestedWhileLoopWithBreak()
{
var registry = new TypeRegistry();
var obj = new objHolder() { result = false, value = NumEnum.Two };
registry.RegisterSymbol("obj", obj);
registry.RegisterType("Debug", typeof(Debug));
registry.RegisterType("objHolder", typeof(objHolder));
registry.RegisterDefaultTypes();
var cc = new CompiledExpression() { StringToParse = "while (obj.number < 10) { Debug.WriteLine(obj.number); obj.number++; while (obj.number2 < 10) { Debug.WriteLine(obj.number2); obj.number2++; if(obj.number2 == 5) break; } if(obj.number == 5) break; }", TypeRegistry = registry };
cc.ExpressionType = CompiledExpressionType.StatementList;
cc.Eval();
Assert.AreEqual(5, obj.number);
Assert.AreEqual(10, obj.number2);
}
[TestMethod]
public void IfThenElseStatementList()
{
var a = new ClassA() { x = 1 };
var t = new TypeRegistry();
t.RegisterSymbol("a", a);
var p = new CompiledExpression { StringToParse = "if (a.x == 1) a.y = 2; else { a.y = 3; } a.z = a.y;", TypeRegistry = t };
p.ExpressionType = CompiledExpressionType.StatementList;
var f = p.Eval();
Assert.AreEqual(a.y, 2);
Assert.AreEqual(a.y, a.z);
}
[TestMethod]
public void SwitchStatement()
{
var a = new ClassA() { x = 1 };
var t = new TypeRegistry();
for (a.x = 1; a.x < 7; a.x++)
{
switch (a.x)
{
case 1:
case 2:
Debug.WriteLine("Hello");
break;
case 3:
Debug.WriteLine("There");
break;
case 4:
Debug.WriteLine("World");
break;
default:
Debug.WriteLine("Undefined");
break;
}
}
t.RegisterSymbol("Debug", typeof(Debug));
var p = new CompiledExpression { StringToParse = "switch(x) { case 1: case 2: Debug.WriteLine('Hello'); break; case 3: Debug.WriteLine('There'); break; case 4: Debug.WriteLine('World'); break; default: Debug.WriteLine('Undefined'); break; }", TypeRegistry = t };
p.ExpressionType = CompiledExpressionType.StatementList;
var func = p.ScopeCompile<ClassA>();
for (a.x = 1; a.x < 7; a.x++)
{
func(a);
}
}
//[TestMethod]
//public void Return()
//{
// var t = new TypeRegistry();
// var p = new CompiledExpression<bool> { StringToParse = "return true;", TypeRegistry = t };
// p.ExpressionType = CompiledExpressionType.StatementList;
// Assert.AreEqual(true, p.Compile()());
// p.StringToParse = "var x = 3; if (x == 3) { return true; } return false;";
// Assert.AreEqual(true, p.Compile()());
// p.StringToParse = "var x = 2; if (x == 3) { return true; } ";
// Assert.AreEqual(true, p.Compile()());
// p.StringToParse = "var x = true; x;";
// Assert.AreEqual(true, p.Compile()());
//}
//[TestMethod]
//public void SwitchReturn()
//{
// var a = new ClassA() { x = 1 };
// var t = new TypeRegistry();
// var p = new CompiledExpression { StringToParse = "var retval = 'Exit'; switch(x) { case 1: case 2: return 'Hello'; case 3: return 'There'; case 4: return 'World'; default: return 'Undefined'; } return retval;", TypeRegistry = t };
// p.ExpressionType = CompiledExpressionType.StatementList;
// var func = p.ScopeCompile<ClassA>();
// for (a.x = 1; a.x < 7; a.x++)
// {
// Debug.WriteLine(func(a));
// }
//}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Cross.DbFactory;
namespace Cross.DbFactory.Migrations
{
[DbContext(typeof(CrossContext))]
partial class CrossContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("Cross.Entities.Task", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreateTime");
b.Property<int?>("CreateUserId");
b.Property<DateTime>("FinishedTime");
b.HasKey("Id");
});
modelBuilder.Entity("Cross.Entities.TaskSet", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CreateUserId");
b.Property<int>("ImageTaskCount");
b.Property<DateTime>("LastEditTime");
b.Property<int>("StoryTaskCount");
b.Property<int>("VideoTaskCount");
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "Role");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<int>("RoleId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "RoleClaim");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "User");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "UserClaim");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<int>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "UserLogin");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b =>
{
b.Property<int>("UserId");
b.Property<int>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "UserInRole");
});
modelBuilder.Entity("Cross.Entities.Task", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("CreateUserId");
});
modelBuilder.Entity("Cross.Entities.TaskSet", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("CreateUserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole<int>")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityUser<int>")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class CommonCommandLineParserTests : TestBase
{
private const int EN_US = 1033;
private void VerifyCommandLineSplitter(string commandLine, string[] expected)
{
string[] actual = CommandLineSplitter.SplitCommandLine(commandLine);
Assert.Equal(expected.Length, actual.Length);
for (int i = 0; i < actual.Length; ++i)
{
Assert.Equal(expected[i], actual[i]);
}
}
private RuleSet ParseRuleSet(string source, params string[] otherSources)
{
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
for (int i = 1; i <= otherSources.Length; i++)
{
var newFile = dir.CreateFile("file" + i + ".ruleset");
newFile.WriteAllText(otherSources[i - 1]);
}
if (otherSources.Length != 0)
{
return RuleSet.LoadEffectiveRuleSetFromFile(file.Path);
}
return RuleSetProcessor.LoadFromFile(file.Path);
}
private void VerifyRuleSetError(string source, string message, bool locSpecific = true, string locMessage = "", params string[] otherSources)
{
try
{
ParseRuleSet(source, otherSources);
}
catch (Exception e)
{
if (CultureInfo.CurrentCulture.LCID == EN_US || CultureInfo.CurrentUICulture.LCID == EN_US || CultureInfo.CurrentCulture == CultureInfo.InvariantCulture || CultureInfo.CurrentUICulture == CultureInfo.InvariantCulture)
{
Assert.Equal(message, e.Message);
}
else if (locSpecific)
{
if (locMessage != "")
Assert.Contains(locMessage, e.Message);
else
Assert.Equal(message, e.Message);
}
return;
}
Assert.True(false, "Didn't return an error");
}
[Fact]
public void TestCommandLineSplitter()
{
VerifyCommandLineSplitter("", new string[0]);
VerifyCommandLineSplitter(" \t ", new string[0]);
VerifyCommandLineSplitter(" abc\tdef baz quuz ", new string[] {"abc", "def", "baz", "quuz"});
VerifyCommandLineSplitter(@" ""abc def"" fi""ddle dee de""e ""hi there ""dude he""llo there"" ",
new string[] { @"abc def", @"fi""ddle dee de""e", @"""hi there ""dude", @"he""llo there""" });
VerifyCommandLineSplitter(@" ""abc def \"" baz quuz"" ""\""straw berry"" fi\""zz \""buzz fizzbuzz",
new string[] { @"abc def "" baz quuz", @"""straw berry", @"fi""zz", @"""buzz", @"fizzbuzz"});
VerifyCommandLineSplitter(@" \\""abc def"" \\\""abc def"" ",
new string[] { @"\""abc def""", @"\""abc", @"def""" });
VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" ",
new string[] { @"\\""abc def""", @"\\""abc", @"def""" });
}
[Fact]
public void TestRuleSetParsingDuplicateRule()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1012"" Action=""Warning"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>";
string paranment = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint.");
VerifyRuleSetError(source, () => parameter);
}
[Fact]
public void TestRuleSetParsingDuplicateRule2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>";
string paranment2 = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint.");
VerifyRuleSetError(source, () => parameter2);
}
[Fact]
public void TestRuleSetParsingDuplicateRule3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>";
var ruleSet = ParseRuleSet(source);
Assert.Equal(expected: ReportDiagnostic.Error, actual: ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetParsingDuplicateRuleSet()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
<RuleSet Name=""Ruleset2"" Description=""Test"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, "There are multiple root elements. Line 8, position 2.", false);
}
[Fact]
public void TestRuleSetParsingIncludeAll1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetParsingIncludeAll2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetParsingWithIncludeOfSameFile()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""a.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, new string[] { "" });
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(1, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingWithMutualIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""a.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(2, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingWithSiblingIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(3, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingIncludeAll3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TIncludeAllAction' - The Enumeration constraint failed."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Id' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Action' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'AnalyzerId' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute4()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'RuleNamespace' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute5()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'ToolsVersion' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute6()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Name' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRules()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
<Rule Id=""CA1015"" Action=""Info"" />
<Rule Id=""CA1016"" Action=""Hidden"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1012"], ReportDiagnostic.Error);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1013"], ReportDiagnostic.Warn);
Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1014"], ReportDiagnostic.Suppress);
Assert.Contains("CA1015", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1015"], ReportDiagnostic.Info);
Assert.Contains("CA1016", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1016"], ReportDiagnostic.Hidden);
}
[Fact]
public void TestRuleSetParsingRules2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Default"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TRuleAction' - The Enumeration constraint failed."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetInclude()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""foo.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.True(ruleSet.Includes.Count() == 1);
Assert.Equal(ruleSet.Includes.First().Action, ReportDiagnostic.Default);
Assert.Equal(ruleSet.Includes.First().IncludePath, "foo.ruleset");
}
[WorkItem(156)]
[Fact(Skip = "156")]
public void TestRuleSetInclude1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""foo.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.InvalidRuleSetInclude, "foo.ruleset", string.Format(CodeAnalysisResources.FailedToResolveRuleSetName, "foo.ruleset")), otherSources: new string[] {""});
}
[Fact]
public void TestRuleSetInclude2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Hidden"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Hidden, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Info"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Info, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeRecursiveIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1014"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1014"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
// CA1012's value in source wins.
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
// CA1012's value in source still wins.
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
// CA1013's value in source2 wins.
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeEffectiveAction()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""None"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.DoesNotContain("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
}
[Fact]
public void TestRuleSetIncludeEffectiveAction1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionGlobal1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionGlobal2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionSpecific1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionSpecific2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestAllCombinations()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
<Rule Id=""CA2119"" Action=""None"" />
<Rule Id=""CA2104"" Action=""Error"" />
<Rule Id=""CA2105"" Action=""Warning"" />
</Rules>
</RuleSet>";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1000"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1001"]);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA2100"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2104"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2105"]);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2111"]);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2119"]);
}
[Fact]
public void TestRuleSetIncludeError()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Default"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
var newFile = dir.CreateFile("file1.ruleset");
newFile.WriteAllText(source1);
try
{
RuleSet.LoadEffectiveRuleSetFromFile(file.Path);
Assert.True(false, "Didn't throw an exception");
}
catch (InvalidRuleSetException e)
{
Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "")), e.Message);
}
}
[Fact]
public void GetEffectiveIncludes_NoIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 1, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
}
[Fact]
public void GetEffectiveIncludes_OneLevel()
{
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(ruleSetSource);
var include = dir.CreateFile("file1.ruleset");
include.WriteAllText(includeSource);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 2, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
Assert.Equal(expected: include.Path, actual: includePaths[1]);
}
[Fact]
public void GetEffectiveIncludes_TwoLevels()
{
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string includeSource1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string includeSource2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
<Rule Id=""CA2119"" Action=""None"" />
<Rule Id=""CA2104"" Action=""Error"" />
<Rule Id=""CA2105"" Action=""Warning"" />
</Rules>
</RuleSet>";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(ruleSetSource);
var include1 = dir.CreateFile("file1.ruleset");
include1.WriteAllText(includeSource1);
var include2 = dir.CreateFile("file2.ruleset");
include2.WriteAllText(includeSource2);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 3, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
Assert.Equal(expected: include1.Path, actual: includePaths[1]);
Assert.Equal(expected: include2.Path, actual: includePaths[2]);
}
}
}
| |
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="Management.ProvisionBinding", Namespace="urn:iControl")]
public partial class ManagementProvision : iControlInterface {
public ManagementProvision() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// get_custom_cpu_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_custom_cpu_ratio(
CommonTMOSModule [] modules
) {
object [] results = this.Invoke("get_custom_cpu_ratio", new object [] {
modules});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_custom_cpu_ratio(CommonTMOSModule [] modules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_custom_cpu_ratio", new object[] {
modules}, callback, asyncState);
}
public long [] Endget_custom_cpu_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_custom_disk_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_custom_disk_ratio(
CommonTMOSModule [] modules
) {
object [] results = this.Invoke("get_custom_disk_ratio", new object [] {
modules});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_custom_disk_ratio(CommonTMOSModule [] modules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_custom_disk_ratio", new object[] {
modules}, callback, asyncState);
}
public long [] Endget_custom_disk_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_custom_memory_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_custom_memory_ratio(
CommonTMOSModule [] modules
) {
object [] results = this.Invoke("get_custom_memory_ratio", new object [] {
modules});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_custom_memory_ratio(CommonTMOSModule [] modules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_custom_memory_ratio", new object[] {
modules}, callback, asyncState);
}
public long [] Endget_custom_memory_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
CommonTMOSModule [] modules
) {
object [] results = this.Invoke("get_description", new object [] {
modules});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(CommonTMOSModule [] modules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
modules}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_level
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementProvisionProvisionLevel [] get_level(
CommonTMOSModule [] modules
) {
object [] results = this.Invoke("get_level", new object [] {
modules});
return ((ManagementProvisionProvisionLevel [])(results[0]));
}
public System.IAsyncResult Beginget_level(CommonTMOSModule [] modules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_level", new object[] {
modules}, callback, asyncState);
}
public ManagementProvisionProvisionLevel [] Endget_level(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementProvisionProvisionLevel [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTMOSModule [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((CommonTMOSModule [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public CommonTMOSModule [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTMOSModule [])(results[0]));
}
//-----------------------------------------------------------------------
// get_provisioned_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTMOSModule [] get_provisioned_list(
) {
object [] results = this.Invoke("get_provisioned_list", new object [0]);
return ((CommonTMOSModule [])(results[0]));
}
public System.IAsyncResult Beginget_provisioned_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_provisioned_list", new object[0], callback, asyncState);
}
public CommonTMOSModule [] Endget_provisioned_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTMOSModule [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
[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_custom_cpu_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
public void set_custom_cpu_ratio(
CommonTMOSModule [] modules,
long [] ratios
) {
this.Invoke("set_custom_cpu_ratio", new object [] {
modules,
ratios});
}
public System.IAsyncResult Beginset_custom_cpu_ratio(CommonTMOSModule [] modules,long [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_custom_cpu_ratio", new object[] {
modules,
ratios}, callback, asyncState);
}
public void Endset_custom_cpu_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_custom_disk_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
public void set_custom_disk_ratio(
CommonTMOSModule [] modules,
long [] ratios
) {
this.Invoke("set_custom_disk_ratio", new object [] {
modules,
ratios});
}
public System.IAsyncResult Beginset_custom_disk_ratio(CommonTMOSModule [] modules,long [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_custom_disk_ratio", new object[] {
modules,
ratios}, callback, asyncState);
}
public void Endset_custom_disk_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_custom_memory_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
public void set_custom_memory_ratio(
CommonTMOSModule [] modules,
long [] ratios
) {
this.Invoke("set_custom_memory_ratio", new object [] {
modules,
ratios});
}
public System.IAsyncResult Beginset_custom_memory_ratio(CommonTMOSModule [] modules,long [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_custom_memory_ratio", new object[] {
modules,
ratios}, callback, asyncState);
}
public void Endset_custom_memory_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
public void set_description(
CommonTMOSModule [] modules,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
modules,
descriptions});
}
public System.IAsyncResult Beginset_description(CommonTMOSModule [] modules,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
modules,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_level
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Provision",
RequestNamespace="urn:iControl:Management/Provision", ResponseNamespace="urn:iControl:Management/Provision")]
public void set_level(
CommonTMOSModule [] modules,
ManagementProvisionProvisionLevel [] levels
) {
this.Invoke("set_level", new object [] {
modules,
levels});
}
public System.IAsyncResult Beginset_level(CommonTMOSModule [] modules,ManagementProvisionProvisionLevel [] levels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_level", new object[] {
modules,
levels}, callback, asyncState);
}
public void Endset_level(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.Provision.ProvisionLevel", Namespace = "urn:iControl")]
public enum ManagementProvisionProvisionLevel
{
PROVISION_LEVEL_NONE,
PROVISION_LEVEL_MINIMUM,
PROVISION_LEVEL_NOMINAL,
PROVISION_LEVEL_DEDICATED,
PROVISION_LEVEL_CUSTOM,
PROVISION_LEVEL_UNKNOWN,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
#region License
// Copyright 2014 MorseCode Software
// 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
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading.Tasks;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
[Serializable]
internal class CancellableAsyncCalculatedProperty<TFirst, TSecond, TThird, TFourth, T> : CalculatedPropertyBase<T>,
ISerializable
{
#region Fields
private readonly IObservable<TFirst> firstProperty;
private readonly IObservable<TFourth> fourthProperty;
private readonly IObservable<TSecond> secondProperty;
private readonly IObservable<TThird> thirdProperty;
private readonly TimeSpan throttleTime;
private readonly Func<AsyncCalculationHelper, TFirst, TSecond, TThird, TFourth, Task<T>> calculateValue;
private readonly bool isLongRunningCalculation;
private IDisposable scheduledTask;
#endregion
#region Constructors and Destructors
internal CancellableAsyncCalculatedProperty(
IObservable<TFirst> firstProperty,
IObservable<TSecond> secondProperty,
IObservable<TThird> thirdProperty,
IObservable<TFourth> fourthProperty,
TimeSpan throttleTime,
Func<AsyncCalculationHelper, TFirst, TSecond, TThird, TFourth, Task<T>> calculateValue,
bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty");
Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty");
Contract.Requires<ArgumentNullException>(thirdProperty != null, "thirdProperty");
Contract.Requires<ArgumentNullException>(fourthProperty != null, "fourthProperty");
Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue");
Contract.Ensures(this.firstProperty != null);
Contract.Ensures(this.secondProperty != null);
Contract.Ensures(this.thirdProperty != null);
Contract.Ensures(this.fourthProperty != null);
Contract.Ensures(this.calculateValue != null);
RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue);
this.firstProperty = firstProperty;
this.secondProperty = secondProperty;
this.thirdProperty = thirdProperty;
this.fourthProperty = fourthProperty;
this.throttleTime = throttleTime;
this.calculateValue = calculateValue;
this.isLongRunningCalculation = isLongRunningCalculation;
Func
<AsyncCalculationHelper, TFirst, TSecond, TThird, TFourth,
Task<IDiscriminatedUnion<object, T, Exception>>> calculate =
async (helper, first, second, third, fourth) =>
{
IDiscriminatedUnion<object, T, Exception> discriminatedUnion;
try
{
discriminatedUnion =
DiscriminatedUnion.First<object, T, Exception>(
await calculateValue(helper, first, second, third, fourth).ConfigureAwait(true));
}
catch (Exception e)
{
discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e);
}
return discriminatedUnion;
};
this.SetHelper(
new CalculatedPropertyHelper(
(resultSubject, isCalculatingSubject) =>
{
CompositeDisposable d = new CompositeDisposable();
IScheduler scheduler = isLongRunningCalculation
? RxMvvmConfiguration.GetLongRunningCalculationScheduler()
: RxMvvmConfiguration.GetCalculationScheduler();
IObservable<Tuple<TFirst, TSecond, TThird, TFourth>> o =
firstProperty.CombineLatest(secondProperty, thirdProperty, fourthProperty, Tuple.Create);
o = throttleTime > TimeSpan.Zero
? o.Throttle(throttleTime, scheduler)
: o.ObserveOn(scheduler);
d.Add(
o.Subscribe(
v =>
{
using (this.scheduledTask)
{
}
isCalculatingSubject.OnNext(true);
this.scheduledTask = scheduler.ScheduleAsync(
async (s, t) =>
{
try
{
await s.Yield().ConfigureAwait(true);
IDiscriminatedUnion<object, T, Exception> result =
await
calculate(
new AsyncCalculationHelper(s, t),
v.Item1,
v.Item2,
v.Item3,
v.Item4).ConfigureAwait(true);
await s.Yield().ConfigureAwait(true);
resultSubject.OnNext(result);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
resultSubject.OnNext(
DiscriminatedUnion.Second<object, T, Exception>(e));
}
isCalculatingSubject.OnNext(false);
});
}));
return d;
}));
}
/// <summary>
/// Initializes a new instance of the <see cref="CancellableAsyncCalculatedProperty{TFirst,TSecond,TThird,TFourth,T}"/> class.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected CancellableAsyncCalculatedProperty(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
: this(
(IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)),
(IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)),
(IObservable<TThird>)info.GetValue("p3", typeof(IObservable<TThird>)),
(IObservable<TFourth>)info.GetValue("p4", typeof(IObservable<TFourth>)),
(TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)),
(Func<AsyncCalculationHelper, TFirst, TSecond, TThird, TFourth, Task<T>>)
info.GetValue("f", typeof(Func<AsyncCalculationHelper, TFirst, TSecond, TThird, TFourth, Task<T>>)),
(bool)info.GetValue("l", typeof(bool)))
{
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("p1", this.firstProperty);
info.AddValue("p2", this.secondProperty);
info.AddValue("p3", this.thirdProperty);
info.AddValue("p4", this.fourthProperty);
info.AddValue("t", this.throttleTime);
info.AddValue("f", this.calculateValue);
info.AddValue("l", this.isLongRunningCalculation);
}
#endregion
#region Methods
/// <summary>
/// Disposes of the property.
/// </summary>
protected override void Dispose()
{
base.Dispose();
using (this.scheduledTask)
{
}
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.firstProperty != null);
Contract.Invariant(this.secondProperty != null);
Contract.Invariant(this.thirdProperty != null);
Contract.Invariant(this.fourthProperty != null);
Contract.Invariant(this.calculateValue != null);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ISLA2.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using NBTExplorer.Mac;
using System.IO;
using NBTExplorer.Model;
using Substrate.Nbt;
using System.Threading;
namespace NBTExplorer
{
public partial class MainWindow : MonoMac.AppKit.NSWindow
{
#region Constructors
// Called when created from unmanaged code
public MainWindow (IntPtr handle) : base (handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export ("initWithCoder:")]
public MainWindow (NSCoder coder) : base (coder)
{
Initialize ();
}
// Shared initialization code
void Initialize ()
{
Delegate = new WindowDelegate(this);
InitializeIconRegistry();
FormHandlers.Register();
NbtClipboardController.Initialize(new NbtClipboardControllerMac());
}
private AppDelegate _appDelegate;
private NBTExplorer.Mac.IconRegistry _iconRegistry;
private void InitializeIconRegistry ()
{
_iconRegistry = new NBTExplorer.Mac.IconRegistry();
_iconRegistry.DefaultIcon = NSImage.ImageNamed("question-white.png");
_iconRegistry.Register(typeof(TagByteDataNode), NSImage.ImageNamed("document-attribute-b.png"));
_iconRegistry.Register(typeof(TagShortDataNode), NSImage.ImageNamed("document-attribute-s.png"));
_iconRegistry.Register(typeof(TagIntDataNode), NSImage.ImageNamed("document-attribute-i.png"));
_iconRegistry.Register(typeof(TagLongDataNode), NSImage.ImageNamed("document-attribute-l.png"));
_iconRegistry.Register(typeof(TagFloatDataNode), NSImage.ImageNamed("document-attribute-f.png"));
_iconRegistry.Register(typeof(TagDoubleDataNode), NSImage.ImageNamed("document-attribute-d.png"));
_iconRegistry.Register(typeof(TagByteArrayDataNode), NSImage.ImageNamed("edit-code.png"));
_iconRegistry.Register(typeof(TagStringDataNode), NSImage.ImageNamed("edit-small-caps.png"));
_iconRegistry.Register(typeof(TagListDataNode), NSImage.ImageNamed("edit-list.png"));
_iconRegistry.Register(typeof(TagCompoundDataNode), NSImage.ImageNamed("box.png"));
_iconRegistry.Register(typeof(RegionChunkDataNode), NSImage.ImageNamed("wooden-box.png"));
_iconRegistry.Register(typeof(DirectoryDataNode), NSImage.ImageNamed("folder-open"));
_iconRegistry.Register(typeof(RegionFileDataNode), NSImage.ImageNamed("block.png"));
_iconRegistry.Register(typeof(CubicRegionDataNode), NSImage.ImageNamed("block.png"));
_iconRegistry.Register(typeof(NbtFileDataNode), NSImage.ImageNamed("wooden-box.png"));
_iconRegistry.Register(typeof(TagIntArrayDataNode), NSImage.ImageNamed("edit-code-i.png"));
}
public AppDelegate AppDelegate
{
get { return _appDelegate; }
set
{
_appDelegate = value;
UpdateUI ();
}
}
#endregion
private TreeDataSource _dataSource;
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
NSApplication.SharedApplication.MainMenu.AutoEnablesItems = false;
_dataSource = new TreeDataSource();
_mainOutlineView.DataSource = _dataSource;
_mainOutlineView.Delegate = new MyDelegate(this);
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 2) {
string[] paths = new string[args.Length - 1];
Array.Copy(args, 1, paths, 0, paths.Length);
OpenPaths(paths);
}
else {
OpenMinecraftDirectory();
}
}
public class WindowDelegate : NSWindowDelegate
{
private MainWindow _main;
public WindowDelegate (MainWindow main) {
_main = main;
}
public override bool WindowShouldClose (NSObject sender)
{
//Settings.Default.RecentFiles = Settings.Default.RecentFiles;
//Settings.Default.Save();
return _main.ConfirmExit();
}
}
public class MyDelegate : NSOutlineViewDelegate
{
private MainWindow _main;
public MyDelegate (MainWindow main)
{
_main = main;
}
public override void SelectionDidChange (NSNotification notification)
{
TreeDataNode node = _main.SelectedNode;
if (node != null)
_main.UpdateUI(node.Data);
}
public override void ItemWillExpand (NSNotification notification)
{
TreeDataNode node = notification.UserInfo ["NSObject"] as TreeDataNode;
if (node != null) {
//Console.WriteLine ("Preparing to expand: " + node.Data.NodeDisplay);
_main.ExpandNode(node);
}
}
public override void ItemDidExpand (NSNotification notification)
{
TreeDataNode node = notification.UserInfo ["NSObject"] as TreeDataNode;
if (node != null) {
//Console.WriteLine("Finished Expanding: " + node.Data.NodeDisplay);
}
}
public override void ItemWillCollapse (NSNotification notification)
{
TreeDataNode node = notification.UserInfo ["NSObject"] as TreeDataNode;
if (node != null) {
//if (node.Data.NodeDisplay == "saves") // The root node
//Console.WriteLine ("Uh-oh...");
//Console.WriteLine("Preparing to collapse: " + node.Data.NodeDisplay);
}
}
public override void ItemDidCollapse (NSNotification notification)
{
TreeDataNode node = notification.UserInfo ["NSObject"] as TreeDataNode;
if (node != null) {
_main.CollapseNode(node);
}
}
public override void WillDisplayCell (NSOutlineView outlineView, NSObject cell, NSTableColumn tableColumn, NSObject item)
{
ImageAndTextCell c = cell as ImageAndTextCell;
TreeDataNode node = item as TreeDataNode;
c.Title = node.CombinedName;
c.Image = _main._iconRegistry.Lookup(node.Data.GetType());
//c.StringValue = node.Name;
//throw new System.NotImplementedException ();
}
}
#region Actions
partial void ActionOpenFolder (NSObject sender)
{
OpenFolder ();
}
partial void ActionSave (NSObject sender)
{
ActionSave ();
}
partial void ActionRename (MonoMac.Foundation.NSObject sender)
{
ActionRenameValue();
}
partial void ActionEdit (MonoMac.Foundation.NSObject sender)
{
ActionEditValue();
}
partial void ActionDelete (MonoMac.Foundation.NSObject sender)
{
ActionDeleteValue();
}
partial void ActionInsertByte (MonoMac.Foundation.NSObject sender)
{
ActionInsertByteTag();
}
partial void ActionInsertShort (MonoMac.Foundation.NSObject sender)
{
ActionInsertShortTag();
}
partial void ActionInsertInt (MonoMac.Foundation.NSObject sender)
{
ActionInsertIntTag();
}
partial void ActionInsertLong (MonoMac.Foundation.NSObject sender)
{
ActionInsertLongTag();
}
partial void ActionInsertFloat (MonoMac.Foundation.NSObject sender)
{
ActionInsertFloatTag();
}
partial void ActionInsertDouble (MonoMac.Foundation.NSObject sender)
{
ActionInsertDoubleTag();
}
partial void ActionInsertByteArray (MonoMac.Foundation.NSObject sender)
{
ActionInsertByteArrayTag();
}
partial void ActionInsertIntArray (MonoMac.Foundation.NSObject sender)
{
ActionInsertIntArrayTag();
}
partial void ActionInsertString (MonoMac.Foundation.NSObject sender)
{
ActionInsertStringTag();
}
partial void ActionInsertList (MonoMac.Foundation.NSObject sender)
{
ActionInsertListTag();
}
partial void ActionInsertCompound (MonoMac.Foundation.NSObject sender)
{
ActionInsertCompoundTag();
}
#endregion
private string _openFolderPath = null;
private void OpenFolder ()
{
NSOpenPanel opanel = new NSOpenPanel ();
opanel.CanChooseDirectories = true;
opanel.CanChooseFiles = false;
if (_openFolderPath != null)
opanel.DirectoryUrl = new NSUrl (_openFolderPath, true);
if (opanel.RunModal () == (int)NSPanelButtonType.Ok) {
_openFolderPath = opanel.DirectoryUrl.AbsoluteString;
OpenPaths(new string[] { opanel.DirectoryUrl.Path });
}
UpdateUI();
}
private void OpenFile ()
{
NSOpenPanel opanel = new NSOpenPanel ();
opanel.CanChooseDirectories = false;
opanel.CanChooseFiles = true;
//opanel.AllowsMultipleSelection = true;
if (opanel.RunModal() == (int)NSPanelButtonType.Ok) {
List<string> paths = new List<string>();
foreach (var url in opanel.Urls)
paths.Add(url.Path);
OpenPaths(paths);
}
UpdateUI();
}
private void OpenMinecraftDirectory ()
{
try {
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, "Library", "Application Support");
path = Path.Combine(path, "minecraft", "saves");
if (!Directory.Exists(path)) {
path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
}
OpenPaths(new string[] { path });
}
catch (Exception e) {
NSAlert.WithMessage("Operation Failed", "OK", null, null, "Could not open default Minecraft save directory").RunModal();
Console.WriteLine(e.Message);
try {
OpenPaths(new string[] { Directory.GetCurrentDirectory() });
}
catch (Exception) {
//MessageBox.Show("Could not open current directory, this tool is probably not compatible with your platform.");
Console.WriteLine(e.Message);
NSApplication.SharedApplication.Terminate(this);
}
}
UpdateUI();
}
private void OpenPaths (IEnumerable<string> paths)
{
_dataSource.Nodes.Clear ();
_mainOutlineView.ReloadData ();
foreach (string path in paths) {
if (Directory.Exists (path)) {
DirectoryDataNode node = new DirectoryDataNode (path);
_dataSource.Nodes.Add (new TreeDataNode (node));
// AddPathToHistory(Settings.Default.RecentDirectories, path);
} else if (File.Exists (path)) {
DataNode node = null;
foreach (var item in FileTypeRegistry.RegisteredTypes) {
if (item.Value.NamePatternTest(path))
node = item.Value.NodeCreate(path);
}
if (node != null) {
_dataSource.Nodes.Add(new TreeDataNode(node));
//AddPathToHistory(Settings.Default.RecentFiles, path);
}
}
}
if (_dataSource.Nodes.Count > 0) {
_mainOutlineView.ExpandItem(_dataSource.Nodes[0]);
}
_mainOutlineView.ReloadData();
UpdateUI();
}
private void ExpandNode (TreeDataNode node)
{
if (node == null || node.IsExpanded)
return;
//Console.WriteLine ("Expand Node: " + node.Data.NodeDisplay);
node.IsExpanded = true;
node.Nodes.Clear ();
DataNode backNode = node.Data;
if (!backNode.IsExpanded) {
backNode.Expand ();
}
foreach (DataNode child in backNode.Nodes) {
if (child != null) {
node.AddNode (new TreeDataNode (child));
}
}
}
private void CollapseNode (TreeDataNode node)
{
if (node == null || !node.IsExpanded)
return;
//Console.WriteLine("Collapse Node: " + node.Data.NodeDisplay);
DataNode backNode = node.Data;
if (backNode.IsModified)
return;
backNode.Collapse();
node.IsExpanded = false;
node.Nodes.Clear();
}
private void RefreshChildNodes (TreeDataNode node, DataNode dataNode)
{
Dictionary<DataNode, TreeDataNode> currentNodes = new Dictionary<DataNode, TreeDataNode>();
foreach (TreeDataNode child in node.Nodes) {
currentNodes.Add(child.Data, child);
}
node.Nodes.Clear();
foreach (DataNode child in dataNode.Nodes) {
if (!currentNodes.ContainsKey(child))
node.Nodes.Add(new TreeDataNode(child));
else
node.Nodes.Add(currentNodes[child]);
}
//foreach (TreeDataNode child in node.Nodes)
// child.ContextMenuStrip = BuildNodeContextMenu(child.Tag as DataNode);
if (node.Nodes.Count == 0 && dataNode.HasUnexpandedChildren) {
ExpandNode(node);
_mainOutlineView.ExpandItem(node);
//node.Expand();
}
_mainOutlineView.ReloadItem(node, true);
}
private void CreateNode (TreeDataNode node, TagType type)
{
if (node == null)
return;
if (!node.Data.CanCreateTag(type))
return;
if (node.Data.CreateNode(type)) {
//node.Text = dataNode.NodeDisplay;
RefreshChildNodes(node, node.Data);
UpdateUI(node.Data);
}
}
private TreeDataNode SelectedNode
{
get { return _mainOutlineView.ItemAtRow (_mainOutlineView.SelectedRow) as TreeDataNode; }
}
public void ActionOpen ()
{
if (ConfirmOpen())
OpenFile();
}
public void ActionOpenFolder ()
{
if (ConfirmOpen ())
OpenFolder ();
}
public void ActionOpenMinecraft ()
{
if (ConfirmOpen ())
OpenMinecraftDirectory();
}
public void ActionSave ()
{
Save ();
}
public void ActionCopy ()
{
CopyNode (SelectedNode);
}
public void ActionCut ()
{
CutNode (SelectedNode);
}
public void ActionPaste ()
{
PasteNode (SelectedNode);
}
public void ActionEditValue ()
{
EditNode(SelectedNode);
}
public void ActionRenameValue ()
{
RenameNode(SelectedNode);
}
public void ActionDeleteValue ()
{
DeleteNode(SelectedNode);
}
public void ActionMoveNodeUp ()
{
MoveNodeUp(SelectedNode);
}
public void ActionMoveNodeDown ()
{
MoveNodeDown (SelectedNode);
}
public void ActionFind ()
{
SearchNode (SelectedNode);
}
public void ActionFindNext ()
{
SearchNextNode();
}
public void ActionInsertByteTag ()
{
CreateNode (SelectedNode, TagType.TAG_BYTE);
}
public void ActionInsertShortTag ()
{
CreateNode (SelectedNode, TagType.TAG_SHORT);
}
public void ActionInsertIntTag ()
{
CreateNode (SelectedNode, TagType.TAG_INT);
}
public void ActionInsertLongTag ()
{
CreateNode (SelectedNode, TagType.TAG_LONG);
}
public void ActionInsertFloatTag ()
{
CreateNode (SelectedNode, TagType.TAG_FLOAT);
}
public void ActionInsertDoubleTag ()
{
CreateNode (SelectedNode, TagType.TAG_DOUBLE);
}
public void ActionInsertByteArrayTag ()
{
CreateNode (SelectedNode, TagType.TAG_BYTE_ARRAY);
}
public void ActionInsertIntArrayTag ()
{
CreateNode (SelectedNode, TagType.TAG_INT_ARRAY);
}
public void ActionInsertStringTag ()
{
CreateNode (SelectedNode, TagType.TAG_STRING);
}
public void ActionInsertListTag ()
{
CreateNode (SelectedNode, TagType.TAG_LIST);
}
public void ActionInsertCompoundTag ()
{
CreateNode (SelectedNode, TagType.TAG_COMPOUND);
}
private void CopyNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanCopyNode)
return;
node.Data.CopyNode();
}
private void CutNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanCutNode)
return;
if (node.Data.CutNode()) {
TreeDataNode parent = node.Parent;
UpdateUI(parent.Data);
node.Remove();
_mainOutlineView.ReloadItem(parent, true);
}
}
private void PasteNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanPasteIntoNode)
return;
if (node.Data.PasteNode()) {
//node.Text = dataNode.NodeDisplay;
RefreshChildNodes(node, node.Data);
UpdateUI(node.Data);
}
}
private void EditNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanEditNode)
return;
if (node.Data.EditNode()) {
//node.Text = node.Data.NodeDisplay;
UpdateUI(node.Data);
}
}
private void RenameNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanRenameNode)
return;
if (node.Data.RenameNode()) {
//node.Text = dataNode.NodeDisplay;
UpdateUI(node.Data);
}
}
private void DeleteNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanDeleteNode)
return;
if (node.Data.DeleteNode()) {
UpdateUI(node.Parent.Data);
//UpdateNodeText(node.Parent);
TreeDataNode parent = node.Parent;
node.Remove();
_mainOutlineView.ReloadItem(parent, true);
}
}
private void MoveNodeUp (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanMoveNodeUp)
return;
node.Data.ChangeRelativePosition(-1);
RefreshChildNodes(node.Parent, node.Data.Parent);
}
private void MoveNodeDown (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanMoveNodeDown)
return;
node.Data.ChangeRelativePosition(1);
RefreshChildNodes(node.Parent, node.Data.Parent);
}
private void Save ()
{
foreach (TreeDataNode node in _dataSource.Nodes) {
if (node.Data != null)
node.Data.Save();
}
UpdateUI();
}
private static ModalResult RunWindow (NSWindowController controller)
{
int response = NSApplication.SharedApplication.RunModalForWindow (controller.Window);
controller.Window.Close();
controller.Window.OrderOut(null);
if (!Enum.IsDefined(typeof(ModalResult), response))
response = 0;
return (ModalResult)response;
}
private CancelFindWindowController _searchForm;
private SearchStateMac _searchState;
private void SearchNode (TreeDataNode node)
{
if (node == null)
return;
if (!node.Data.CanSearchNode)
return;
FindWindowController form = new FindWindowController();
if (RunWindow (form) != ModalResult.OK)
return;
_searchState = new SearchStateMac(this) {
RootNode = node.Data,
SearchName = form.NameToken,
SearchValue = form.ValueToken,
DiscoverCallback = SearchDiscoveryCallback,
CollapseCallback = SearchCollapseCallback,
EndCallback = SearchEndCallback,
};
SearchNextNode();
}
private void SearchNextNode ()
{
if (_searchState == null)
return;
SearchWorker worker = new SearchWorker (_searchState);
Thread t = new Thread (new ThreadStart (worker.Run));
t.IsBackground = true;
t.Start ();
_searchForm = new CancelFindWindowController ();
if (RunWindow (_searchForm) == ModalResult.Cancel) {
worker.Cancel();
_searchState = null;
}
t.Join();
}
private void SearchDiscoveryCallback (DataNode node)
{
Console.WriteLine ("Discovery: " + node.NodeDisplay);
TreeDataNode frontNode = FindFrontNode(node);
Console.WriteLine (" Front Node: " + frontNode.Data.NodeDisplay);
_mainOutlineView.SelectRow (_mainOutlineView.RowForItem(frontNode), false);
_mainOutlineView.ScrollRowToVisible(_mainOutlineView.RowForItem(frontNode));
//_nodeTree.SelectedNode = FindFrontNode(node);
if (_searchForm != null) {
_searchForm.Accept();
_searchForm = null;
}
}
private void SearchCollapseCallback (DataNode node)
{
CollapseBelow(node);
}
private void SearchEndCallback (DataNode node)
{
_searchForm.Cancel();
_searchForm = null;
NSAlert.WithMessage("End of Results", "OK", null, null, "").RunModal();
}
private TreeDataNode GetRootFromDataNodePath (DataNode node, out Stack<DataNode> hierarchy)
{
hierarchy = new Stack<DataNode>();
while (node != null) {
hierarchy.Push(node);
node = node.Parent;
}
DataNode rootDataNode = hierarchy.Pop();
TreeDataNode frontNode = null;
foreach (TreeDataNode child in _dataSource.Nodes) {
if (child.Data == rootDataNode)
frontNode = child;
}
return frontNode;
}
private TreeDataNode FindFrontNode (DataNode node)
{
Stack<DataNode> hierarchy;
TreeDataNode frontNode = GetRootFromDataNodePath(node, out hierarchy);
if (frontNode == null)
return null;
while (hierarchy.Count > 0) {
if (!frontNode.IsExpanded) {
_mainOutlineView.ExpandItem(frontNode);
_mainOutlineView.ReloadItem(frontNode);
}
DataNode childData = hierarchy.Pop();
foreach (TreeDataNode childFront in frontNode.Nodes) {
if (childFront.Data == childData) {
frontNode = childFront;
break;
}
}
}
return frontNode;
}
private void CollapseBelow (DataNode node)
{
Stack<DataNode> hierarchy;
TreeDataNode frontNode = GetRootFromDataNodePath (node, out hierarchy);
if (frontNode == null)
return;
while (hierarchy.Count > 0) {
if (!frontNode.IsExpanded)
return;
DataNode childData = hierarchy.Pop ();
foreach (TreeDataNode childFront in frontNode.Nodes) {
if (childFront.Data == childData) {
frontNode = childFront;
break;
}
}
}
if (frontNode.IsExpanded) {
_mainOutlineView.CollapseItem (frontNode);
frontNode.IsExpanded = false;
}
}
private bool ConfirmExit ()
{
if (CheckModifications()) {
int id = NSAlert.WithMessage("Unsaved Changes", "OK", "Cancel", "", "You currently have unsaved changes. Close anyway?").RunModal();
if (id != 1)
return false;
}
return true;
}
private bool ConfirmOpen ()
{
if (CheckModifications()) {
int id = NSAlert.WithMessage("Unsaved Changes", "OK", "Cancel", "", "You currently have unsaved changes. Open new location anyway?").RunModal();
if (id != 1)
return false;
}
return true;
}
private bool CheckModifications ()
{
foreach (TreeDataNode node in _dataSource.Nodes) {
if (node.Data != null && node.Data.IsModified)
return true;
}
return false;
}
private void UpdateUI ()
{
if (_appDelegate == null)
return;
TreeDataNode selected = _mainOutlineView.ItemAtRow(_mainOutlineView.SelectedRow) as TreeDataNode;
if (selected != null) {
UpdateUI(selected.Data);
}
else {
UpdateUI(new DataNode());
_appDelegate.MenuSave.Enabled = CheckModifications();
_appDelegate.MenuFind.Enabled = false;
_appDelegate.MenuFindNext.Enabled = _searchState != null;
_toolbarSave.Enabled = _appDelegate.MenuSave.Enabled;
}
}
private void UpdateUI (DataNode node)
{
if (_appDelegate == null || node == null)
return;
_appDelegate.MenuInsertByte.Enabled = node.CanCreateTag(TagType.TAG_BYTE);
_appDelegate.MenuInsertShort.Enabled = node.CanCreateTag(TagType.TAG_SHORT);
_appDelegate.MenuInsertInt.Enabled = node.CanCreateTag(TagType.TAG_INT);
_appDelegate.MenuInsertLong.Enabled = node.CanCreateTag(TagType.TAG_LONG);
_appDelegate.MenuInsertFloat.Enabled = node.CanCreateTag(TagType.TAG_FLOAT);
_appDelegate.MenuInsertDouble.Enabled = node.CanCreateTag(TagType.TAG_DOUBLE);
_appDelegate.MenuInsertByteArray.Enabled = node.CanCreateTag(TagType.TAG_BYTE_ARRAY);
_appDelegate.MenuInsertIntArray.Enabled = node.CanCreateTag(TagType.TAG_INT_ARRAY);
_appDelegate.MenuInsertString.Enabled = node.CanCreateTag(TagType.TAG_STRING);
_appDelegate.MenuInsertList.Enabled = node.CanCreateTag(TagType.TAG_LIST);
_appDelegate.MenuInsertCompound.Enabled = node.CanCreateTag(TagType.TAG_COMPOUND);
_appDelegate.MenuSave.Enabled = CheckModifications();
_appDelegate.MenuCopy.Enabled = node.CanCopyNode && NbtClipboardController.IsInitialized;
_appDelegate.MenuCut.Enabled = node.CanCutNode && NbtClipboardController.IsInitialized;
_appDelegate.MenuPaste.Enabled = node.CanPasteIntoNode && NbtClipboardController.IsInitialized;
_appDelegate.MenuDelete.Enabled = node.CanDeleteNode;
_appDelegate.MenuEditValue.Enabled = node.CanEditNode;
_appDelegate.MenuRename.Enabled = node.CanRenameNode;
_appDelegate.MenuMoveUp.Enabled = node.CanMoveNodeUp;
_appDelegate.MenuMoveDown.Enabled = node.CanMoveNodeDown;
_appDelegate.MenuFind.Enabled = node.CanSearchNode;
_appDelegate.MenuFindNext.Enabled = _searchState != null;
_toolbarByte.Enabled = _appDelegate.MenuInsertByte.Enabled;
_toolbarShort.Enabled = _appDelegate.MenuInsertShort.Enabled;
_toolbarInt.Enabled = _appDelegate.MenuInsertInt.Enabled;
_toolbarLong.Enabled = _appDelegate.MenuInsertLong.Enabled;
_toolbarFloat.Enabled = _appDelegate.MenuInsertFloat.Enabled;
_toolbarDouble.Enabled = _appDelegate.MenuInsertDouble.Enabled;
_toolbarByteArray.Enabled = _appDelegate.MenuInsertByteArray.Enabled;
_toolbarIntArray.Enabled = _appDelegate.MenuInsertIntArray.Enabled;
_toolbarString.Enabled = _appDelegate.MenuInsertString.Enabled;
_toolbarList.Enabled = _appDelegate.MenuInsertList.Enabled;
_toolbarCompound.Enabled = _appDelegate.MenuInsertCompound.Enabled;
_toolbarSave.Enabled = _appDelegate.MenuSave.Enabled;
_toolbarDelete.Enabled = _appDelegate.MenuDelete.Enabled;
_toolbarEdit.Enabled = _appDelegate.MenuEditValue.Enabled;
_toolbarRename.Enabled = _appDelegate.MenuRename.Enabled;
}
/*private void UpdateOpenMenu ()
{
try {
if (Settings.Default.RecentDirectories == null)
Settings.Default.RecentDirectories = new StringCollection();
if (Settings.Default.RecentFiles == null)
Settings.Default.RecentFiles = new StringCollection();
}
catch {
return;
}
_menuItemRecentFolders.DropDown = BuildRecentEntriesDropDown(Settings.Default.RecentDirectories);
_menuItemRecentFiles.DropDown = BuildRecentEntriesDropDown(Settings.Default.RecentFiles);
}
private ToolStripDropDown BuildRecentEntriesDropDown (StringCollection list)
{
if (list == null || list.Count == 0)
return new ToolStripDropDown();
ToolStripDropDown menu = new ToolStripDropDown();
foreach (string entry in list) {
ToolStripMenuItem item = new ToolStripMenuItem("&" + (menu.Items.Count + 1) + " " + entry);
item.Tag = entry;
item.Click += _menuItemRecentPaths_Click;
menu.Items.Add(item);
}
return menu;
}
private void AddPathToHistory (StringCollection list, string entry)
{
foreach (string item in list) {
if (item == entry) {
list.Remove(item);
break;
}
}
while (list.Count >= 5)
list.RemoveAt(list.Count - 1);
list.Insert(0, entry);
}*/
}
}
| |
using System;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.CoreGraphics;
namespace XamarinCustomBadge
{
public class CustomBadge:UIView
{
const float M_PI = (float)Math.PI;
public CustomBadge (string badgeText,
UIColor textColor,
UIFont font,
UIColor frameColor,
UIColor insetColor,
float scaleFactor,
bool frame,
bool shining)
{
Frame = new System.Drawing.RectangleF (0, 0, 25, 25);
ContentScaleFactor = UIScreen.MainScreen.Scale;
BackgroundColor = UIColor.Clear;
BadgeCornerRoundness = 0.4f;
this.BadgeTextColor = textColor;
this.BadgeFont = font;
this.BadgeFrame = frame;
this.BadgeFrameColor = frameColor;
this.BadgeInsetColor = insetColor;
this.BadgeCornerRoundness = 0.4f;
this.BadgeScaleFactor = scaleFactor;
this.BadgeShining = shining;
AutoBadgeSizeWithString (badgeText);
}
public CustomBadge (string badgeText) : this (badgeText,
UIColor.White,
UIFont.BoldSystemFontOfSize (12),
UIColor.White,
UIColor.Red,
1f,
true,
true)
{
}
public string BadgeText {
get;
private set;
}
public UIFont BadgeFont {
get;
private set;
}
public UIColor BadgeTextColor {
get;
private set;
}
public UIColor BadgeInsetColor {
get;
private set;
}
public UIColor BadgeFrameColor {
get;
private set;
}
public bool BadgeFrame {
get;
private set;
}
public bool BadgeShining {
get;
private set;
}
public float BadgeCornerRoundness {
get;
private set;
}
public float BadgeScaleFactor {
get;
private set;
}
public void AutoBadgeSizeWithString (string badgeString)
{
SizeF retValue;
float rectWidth, rectHeight;
SizeF stringSize = new NSString (badgeString).GetSizeUsingAttributes (new UIStringAttributes{ Font = BadgeFont });
float flexSpace;
if (badgeString.Length >= 2) {
flexSpace = badgeString.Length;
rectWidth = 25 + (stringSize.Width + flexSpace);
rectHeight = 25;
retValue = new SizeF (rectWidth * BadgeScaleFactor, rectHeight * BadgeScaleFactor);
} else {
retValue = new SizeF (25 * BadgeScaleFactor, 25 * BadgeScaleFactor);
}
Frame = new RectangleF (Frame.X, Frame.Y, retValue.Width, retValue.Height);
BadgeText = badgeString;
SetNeedsDisplay ();
}
public override void Draw (RectangleF rect)
{
base.Draw (rect);
using (var context = UIGraphics.GetCurrentContext ()) {
DrawRoundedRect (rect, context);
if (BadgeShining) {
DrawShine (rect, context);
}
if (BadgeFrame) {
DrawFrame (rect, context);
}
if (!string.IsNullOrWhiteSpace (BadgeText)) {
float sizeOfFont = 13.5f * BadgeScaleFactor;
if (BadgeText.Length < 2) {
sizeOfFont += sizeOfFont * 0.20f;
}
var nsText = new NSString (BadgeText);
var textFont = BadgeFont.WithSize (sizeOfFont);
var textSize = nsText.GetSizeUsingAttributes (new UIStringAttributes{ Font = textFont });
nsText.DrawString (new PointF (rect.Width / 2 - textSize.Width / 2,
rect.Height / 2 - textSize.Height / 2),
new UIStringAttributes{ Font = textFont, ForegroundColor = BadgeTextColor });
}
}
}
void DrawRoundedRect (RectangleF rect, CGContext context)
{
context.SaveState ();
float radius = rect.GetMaxY () * BadgeCornerRoundness;
float puffer = rect.GetMaxY () * 0.10f;
float maxX = rect.GetMaxX () - puffer;
float maxY = rect.GetMaxY () - puffer;
float minX = rect.GetMinX () + puffer;
float minY = rect.GetMinY () + puffer;
context.BeginPath ();
context.SetFillColor (BadgeInsetColor.CGColor);
context.AddArc (maxX - radius, minY + radius, radius, M_PI + (M_PI / 2f), 0f, false);
context.AddArc (maxX - radius, maxY - radius, radius, 0, M_PI / 2f, false);
context.AddArc (minX + radius, maxY - radius, radius, M_PI / 2f, M_PI, false);
context.AddArc (minX + radius, minY + radius, radius, M_PI, M_PI + (M_PI / 2f), false);
context.SetShadowWithColor (new SizeF (1, 1), 3, UIColor.Black.CGColor);
context.FillPath ();
context.RestoreState ();
}
void DrawShine (RectangleF rect, CGContext context)
{
context.SaveState ();
float radius = rect.GetMaxY () * BadgeCornerRoundness;
float puffer = rect.GetMaxY () * 0.10f;
float maxX = rect.GetMaxX () - puffer;
float maxY = rect.GetMaxY () - puffer;
float minX = rect.GetMinX () + puffer;
float minY = rect.GetMinY () + puffer;
context.BeginPath ();
context.AddArc (maxX - radius, minY + radius, radius, M_PI + (M_PI / 2f), 0f, false);
context.AddArc (maxX - radius, maxY - radius, radius, 0, M_PI / 2f, false);
context.AddArc (minX + radius, maxY - radius, radius, M_PI / 2f, M_PI, false);
context.AddArc (minX + radius, minY + radius, radius, M_PI, M_PI + (M_PI / 2f), false);
context.Clip ();
var locations = new []{ 0f, 0.4f };
var components = new []{ 0.92f, 0.92f, 0.92f, 1.0f, 0.82f, 0.82f, 0.82f, 0.4f };
using (var cspace = CGColorSpace.CreateDeviceRGB ())
using (var gradient = new CGGradient (cspace, components, locations)) {
var sPoint = new PointF (0, 0);
var ePoint = new PointF (0, maxY);
context.DrawLinearGradient (gradient, sPoint, ePoint, (CGGradientDrawingOptions)0);
}
context.RestoreState ();
}
void DrawFrame (RectangleF rect, CGContext context)
{
float radius = rect.GetMaxY () * BadgeCornerRoundness;
float puffer = rect.GetMaxY () * 0.10f;
float maxX = rect.GetMaxX () - puffer;
float maxY = rect.GetMaxY () - puffer;
float minX = rect.GetMinX () + puffer;
float minY = rect.GetMinY () + puffer;
context.BeginPath ();
float lineSize = 2;
if (BadgeScaleFactor > 1) {
lineSize += BadgeScaleFactor * 0.25f;
}
context.SetLineWidth (lineSize);
context.SetStrokeColor (BadgeFrameColor.CGColor);
context.AddArc (maxX - radius, minY + radius, radius, M_PI + (M_PI / 2f), 0f, false);
context.AddArc (maxX - radius, maxY - radius, radius, 0, M_PI / 2f, false);
context.AddArc (minX + radius, maxY - radius, radius, M_PI / 2f, M_PI, false);
context.AddArc (minX + radius, minY + radius, radius, M_PI, M_PI + (M_PI / 2f), false);
context.ClosePath ();
context.StrokePath ();
}
}
}
| |
//#define ASTAR_NoTagPenalty
using UnityEngine;
using Pathfinding;
using Pathfinding.Serialization;
namespace Pathfinding {
public interface INavmeshHolder {
Int3 GetVertex (int i);
int GetVertexArrayIndex(int index);
void GetTileCoordinates (int tileIndex, out int x, out int z);
}
/** Node represented by a triangle */
public class TriangleMeshNode : MeshNode {
public TriangleMeshNode (AstarPath astar) : base(astar) {}
public int v0, v1, v2;
protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0];
public static INavmeshHolder GetNavmeshHolder (uint graphIndex) {
return _navmeshHolders[(int)graphIndex];
}
public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) {
if (_navmeshHolders.Length <= graphIndex) {
INavmeshHolder[] gg = new INavmeshHolder[graphIndex+1];
for (int i=0;i<_navmeshHolders.Length;i++) gg[i] = _navmeshHolders[i];
_navmeshHolders = gg;
}
_navmeshHolders[graphIndex] = graph;
}
public void UpdatePositionFromVertices () {
INavmeshHolder g = GetNavmeshHolder(GraphIndex);
position = (g.GetVertex(v0) + g.GetVertex(v1) + g.GetVertex(v2)) * 0.333333f;
}
/** Return a number identifying a vertex.
* This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should
* not have the same vertex numbers.
*/
public int GetVertexIndex (int i) {
return i == 0 ? v0 : (i == 1 ? v1 : v2);
}
/** Return a number specifying an index in the source vertex array.
* The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant.
* This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex.
*/
public int GetVertexArrayIndex (int i) {
return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex (i == 0 ? v0 : (i == 1 ? v1 : v2));
}
public override Int3 GetVertex (int i) {
return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i));
}
public override int GetVertexCount () {
return 3;
}
public override Vector3 ClosestPointOnNode (Vector3 p) {
INavmeshHolder g = GetNavmeshHolder(GraphIndex);
return Pathfinding.Polygon.ClosestPointOnTriangle ((Vector3)g.GetVertex(v0), (Vector3)g.GetVertex(v1), (Vector3)g.GetVertex(v2), p);
}
public override Vector3 ClosestPointOnNodeXZ (Vector3 _p) {
INavmeshHolder g = GetNavmeshHolder(GraphIndex);
Int3 tp1 = g.GetVertex(v0);
Int3 tp2 = g.GetVertex(v1);
Int3 tp3 = g.GetVertex(v2);
Int3 p = (Int3)_p;
int oy = p.y;
// Assumes the triangle vertices are laid out in (counter?)clockwise order
tp1.y = 0;
tp2.y = 0;
tp3.y = 0;
p.y = 0;
if ((long)(tp2.x - tp1.x) * (long)(p.z - tp1.z) - (long)(p.x - tp1.x) * (long)(tp2.z - tp1.z) > 0) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp1, tp2, p));
return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor;
} else if ((long)(tp3.x - tp2.x) * (long)(p.z - tp2.z) - (long)(p.x - tp2.x) * (long)(tp3.z - tp2.z) > 0) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp2, tp3, p));
return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor;
} else if ((long)(tp1.x - tp3.x) * (long)(p.z - tp3.z) - (long)(p.x - tp3.x) * (long)(tp1.z - tp3.z) > 0) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp3, tp1, p));
return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor;
} else {
return _p;
}
/*
* Equivalent to the above, but the above uses manual inlining
if (!Polygon.Left (tp1, tp2, p)) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp1, tp2, p));
return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor;
} else if (!Polygon.Left (tp2, tp3, p)) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp2, tp3, p));
return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor;
} else if (!Polygon.Left (tp3, tp1, p)) {
float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp3, tp1, p));
return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor;
} else {
return _p;
}*/
/* Almost equivalent to the above, but this is slower
Vector3 tp1 = (Vector3)g.GetVertex(v0);
Vector3 tp2 = (Vector3)g.GetVertex(v1);
Vector3 tp3 = (Vector3)g.GetVertex(v2);
tp1.y = 0;
tp2.y = 0;
tp3.y = 0;
_p.y = 0;
return Pathfinding.Polygon.ClosestPointOnTriangle (tp1,tp2,tp3,_p);*/
}
public override bool ContainsPoint (Int3 p) {
INavmeshHolder g = GetNavmeshHolder(GraphIndex);
Int3 a = g.GetVertex(v0);
Int3 b = g.GetVertex(v1);
Int3 c = g.GetVertex(v2);
if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false;
if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false;
if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false;
return true;
//return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p);
//return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p);
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
UpdateG (path,pathNode);
handler.PushNode (pathNode);
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler);
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
if (connections == null) return;
bool flag2 = pathNode.flag2;
for (int i=connections.Length-1;i >= 0;i--) {
GraphNode other = connections[i];
if (path.CanTraverse (other)) {
PathNode pathOther = handler.GetPathNode (other);
//Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3
if (pathOther == pathNode.parent) {
continue;
}
uint cost = connectionCosts[i];
if (flag2 || pathOther.flag2) {
cost = path.GetConnectionSpecialCost (this,other,cost);
}
if (pathOther.pathID != handler.PathID) {
//Might not be assigned
pathOther.node = other;
pathOther.parent = pathNode;
pathOther.pathID = handler.PathID;
pathOther.cost = cost;
pathOther.H = path.CalculateHScore (other);
other.UpdateG (path, pathOther);
handler.PushNode (pathOther);
} else {
//If not we can test if the path from this node to the other one is a better one than the one already used
if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) {
pathOther.cost = cost;
pathOther.parent = pathNode;
other.UpdateRecursiveG (path, pathOther,handler);
//handler.PushNode (pathOther);
}
else if (pathOther.G+cost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) {
//Or if the path from the other node to this one is better
pathNode.parent = pathOther;
pathNode.cost = cost;
UpdateRecursiveG (path, pathNode,handler);
//handler.PushNode (pathNode);
}
}
}
}
}
/** Returns the edge which is shared with \a other.
* If no edge is shared, -1 is returned.
* The edge is GetVertex(result) - GetVertex((result+1) % GetVertexCount()).
* See GetPortal for the exact segment shared.
* \note Might return that an edge is shared when the two nodes are in different tiles and adjacent on the XZ plane, but on the Y-axis.
* Therefore it is recommended that you only test for neighbours of this node or do additional checking afterwards.
*/
public int SharedEdge (GraphNode other) {
//Debug.Log ("SHARED");
int a, b;
GetPortal(other, null, null, false, out a, out b);
//Debug.Log ("/SHARED");
return a;
}
public override bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) {
int aIndex, bIndex;
return GetPortal (_other,left,right,backwards, out aIndex, out bIndex);
}
public bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex)
{
aIndex = -1;
bIndex = -1;
//If the nodes are in different graphs, this function has no idea on how to find a shared edge.
if (_other.GraphIndex != GraphIndex) return false;
TriangleMeshNode other = _other as TriangleMeshNode;
if (!backwards) {
int first = -1;
int second = -1;
int av = GetVertexCount ();
int bv = other.GetVertexCount ();
/** \todo Maybe optimize with pa=av-1 instead of modulus... */
for (int a=0;a<av;a++) {
int va = GetVertexIndex(a);
for (int b=0;b<bv;b++) {
if (va == other.GetVertexIndex((b+1)%bv) && GetVertexIndex((a+1) % av) == other.GetVertexIndex(b)) {
first = a;
second = b;
a = av;
break;
}
}
}
aIndex = first;
bIndex = second;
if (first != -1) {
if (left != null) {
//All triangles should be clockwise so second is the rightmost vertex (seen from this node)
left.Add ((Vector3)GetVertex(first));
right.Add ((Vector3)GetVertex((first+1)%av));
}
} else {
for ( int i=0;i<connections.Length;i++) {
if ( connections[i].GraphIndex != GraphIndex ) {
NodeLink3Node mid = connections[i] as NodeLink3Node;
if ( mid != null && mid.GetOther (this) == other ) {
// We have found a node which is connected through a NodeLink3Node
if ( left != null ) {
mid.GetPortal ( other, left, right, false );
return true;
}
}
}
}
return false;
}
}
return true;
}
public override void SerializeNode (GraphSerializationContext ctx)
{
base.SerializeNode (ctx);
ctx.writer.Write(v0);
ctx.writer.Write(v1);
ctx.writer.Write(v2);
}
public override void DeserializeNode (GraphSerializationContext ctx)
{
base.DeserializeNode (ctx);
v0 = ctx.reader.ReadInt32();
v1 = ctx.reader.ReadInt32();
v2 = ctx.reader.ReadInt32();
}
}
public class ConvexMeshNode : MeshNode {
public ConvexMeshNode (AstarPath astar) : base(astar) {
indices = new int[0];//\todo Set indices to some reasonable value
}
private int[] indices;
//private new Int3 position;
static ConvexMeshNode () {
//Should register to a delegate to receive updates whenever graph lists are changed
}
protected static INavmeshHolder[] navmeshHolders = new INavmeshHolder[0];
protected static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return navmeshHolders[(int)graphIndex]; }
/*public override Int3 Position {
get {
return position;
}
}*/
public void SetPosition (Int3 p) {
position = p;
}
public int GetVertexIndex (int i) {
return indices[i];
}
public override Int3 GetVertex (int i) {
return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i));
}
public override int GetVertexCount () {
return indices.Length;
}
public override Vector3 ClosestPointOnNode (Vector3 p)
{
throw new System.NotImplementedException ();
}
public override Vector3 ClosestPointOnNodeXZ (Vector3 p)
{
throw new System.NotImplementedException ();
}
public override void GetConnections (GraphNodeDelegate del) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) del (connections[i]);
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (path.CanTraverse (other)) {
PathNode pathOther = handler.GetPathNode (other);
if (pathOther.pathID != handler.PathID) {
pathOther.parent = pathNode;
pathOther.pathID = handler.PathID;
pathOther.cost = connectionCosts[i];
pathOther.H = path.CalculateHScore (other);
other.UpdateG (path, pathOther);
handler.PushNode (pathOther);
} else {
//If not we can test if the path from this node to the other one is a better one then the one already used
uint tmpCost = connectionCosts[i];
if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) {
pathOther.cost = tmpCost;
pathOther.parent = pathNode;
other.UpdateRecursiveG (path, pathOther,handler);
//handler.PushNode (pathOther);
}
else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) {
//Or if the path from the other node to this one is better
pathNode.parent = pathOther;
pathNode.cost = tmpCost;
UpdateRecursiveG (path, pathNode,handler);
//handler.PushNode (pathNode);
}
}
}
}
}
}
/*public class ConvexMeshNode : GraphNode {
//Vertices
public int v1;
public int v2;
public int v3;
public int GetVertexIndex (int i) {
if (i == 0) {
return v1;
} else if (i == 1) {
return v2;
} else if (i == 2) {
return v3;
} else {
throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices");
}
}
public int this[int i]
{
get
{
if (i == 0) {
return v1;
} else if (i == 1) {
return v2;
} else if (i == 2) {
return v3;
} else {
throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices");
}
}
}
public Vector3 ClosestPoint (Vector3 p, Int3[] vertices) {
return Polygon.ClosestPointOnTriangle ((Vector3)vertices[v1],(Vector3)vertices[v2],(Vector3)vertices[v3],p);
}
}*/
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osuTK;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders
{
public class SliderPlacementBlueprint : PlacementBlueprint
{
public new Objects.Slider HitObject => (Objects.Slider)base.HitObject;
private SliderBodyPiece bodyPiece;
private HitCirclePiece headCirclePiece;
private HitCirclePiece tailCirclePiece;
private PathControlPointVisualiser controlPointVisualiser;
private InputManager inputManager;
private SliderPlacementState state;
private PathControlPoint segmentStart;
private PathControlPoint cursor;
private int currentSegmentLength;
[Resolved(CanBeNull = true)]
private HitObjectComposer composer { get; set; }
public SliderPlacementBlueprint()
: base(new Objects.Slider())
{
RelativeSizeAxes = Axes.Both;
HitObject.Path.ControlPoints.Add(segmentStart = new PathControlPoint(Vector2.Zero, PathType.Linear));
currentSegmentLength = 1;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChildren = new Drawable[]
{
bodyPiece = new SliderBodyPiece(),
headCirclePiece = new HitCirclePiece(),
tailCirclePiece = new HitCirclePiece(),
controlPointVisualiser = new PathControlPointVisualiser(HitObject, false)
};
setState(SliderPlacementState.Initial);
}
protected override void LoadComplete()
{
base.LoadComplete();
inputManager = GetContainingInputManager();
}
public override void UpdateTimeAndPosition(SnapResult result)
{
base.UpdateTimeAndPosition(result);
switch (state)
{
case SliderPlacementState.Initial:
BeginPlacement();
HitObject.Position = ToLocalSpace(result.ScreenSpacePosition);
break;
case SliderPlacementState.Body:
updateCursor();
break;
}
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (e.Button != MouseButton.Left)
return base.OnMouseDown(e);
switch (state)
{
case SliderPlacementState.Initial:
beginCurve();
break;
case SliderPlacementState.Body:
if (canPlaceNewControlPoint(out var lastPoint))
{
// Place a new point by detatching the current cursor.
updateCursor();
cursor = null;
}
else
{
// Transform the last point into a new segment.
Debug.Assert(lastPoint != null);
segmentStart = lastPoint;
segmentStart.Type.Value = PathType.Linear;
currentSegmentLength = 1;
}
break;
}
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
if (state == SliderPlacementState.Body && e.Button == MouseButton.Right)
endCurve();
base.OnMouseUp(e);
}
private void beginCurve()
{
BeginPlacement(commitStart: true);
setState(SliderPlacementState.Body);
}
private void endCurve()
{
updateSlider();
EndPlacement(HitObject.Path.HasValidLength);
}
protected override void Update()
{
base.Update();
updateSlider();
// Maintain the path type in case it got defaulted to bezier at some point during the drag.
updatePathType();
}
private void updatePathType()
{
switch (currentSegmentLength)
{
case 1:
case 2:
segmentStart.Type.Value = PathType.Linear;
break;
case 3:
segmentStart.Type.Value = PathType.PerfectCurve;
break;
default:
segmentStart.Type.Value = PathType.Bezier;
break;
}
}
private void updateCursor()
{
if (canPlaceNewControlPoint(out _))
{
// The cursor does not overlap a previous control point, so it can be added if not already existing.
if (cursor == null)
{
HitObject.Path.ControlPoints.Add(cursor = new PathControlPoint { Position = { Value = Vector2.Zero } });
// The path type should be adjusted in the progression of updatePathType() (Linear -> PC -> Bezier).
currentSegmentLength++;
updatePathType();
}
// Update the cursor position.
cursor.Position.Value = ToLocalSpace(inputManager.CurrentState.Mouse.Position) - HitObject.Position;
}
else if (cursor != null)
{
// The cursor overlaps a previous control point, so it's removed.
HitObject.Path.ControlPoints.Remove(cursor);
cursor = null;
// The path type should be adjusted in the reverse progression of updatePathType() (Bezier -> PC -> Linear).
currentSegmentLength--;
updatePathType();
}
}
/// <summary>
/// Whether a new control point can be placed at the current mouse position.
/// </summary>
/// <param name="lastPoint">The last-placed control point. May be null, but is not null if <c>false</c> is returned.</param>
/// <returns>Whether a new control point can be placed at the current position.</returns>
private bool canPlaceNewControlPoint([CanBeNull] out PathControlPoint lastPoint)
{
// We cannot rely on the ordering of drawable pieces, so find the respective drawable piece by searching for the last non-cursor control point.
var last = HitObject.Path.ControlPoints.LastOrDefault(p => p != cursor);
var lastPiece = controlPointVisualiser.Pieces.Single(p => p.ControlPoint == last);
lastPoint = last;
return lastPiece.IsHovered != true;
}
private void updateSlider()
{
HitObject.Path.ExpectedDistance.Value = composer?.GetSnappedDistanceFromDistance(HitObject.StartTime, (float)HitObject.Path.CalculatedDistance) ?? (float)HitObject.Path.CalculatedDistance;
bodyPiece.UpdateFrom(HitObject);
headCirclePiece.UpdateFrom(HitObject.HeadCircle);
tailCirclePiece.UpdateFrom(HitObject.TailCircle);
}
private void setState(SliderPlacementState newState)
{
state = newState;
}
private enum SliderPlacementState
{
Initial,
Body,
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.SIP.Message
{
/// <summary>
/// Implements SIP message. This is base class for SIP_Request and SIP_Response. Defined in RFC 3261.
/// </summary>
public abstract class SIP_Message
{
private SIP_HeaderFieldCollection m_pHeader = null;
private byte[] m_Data = null;
/// <summary>
/// Default constuctor.
/// </summary>
public SIP_Message()
{
m_pHeader = new SIP_HeaderFieldCollection();
}
#region method InternalParse
/// <summary>
/// Parses SIP message from specified byte array.
/// </summary>
/// <param name="data">SIP message data.</param>
protected void InternalParse(byte[] data)
{
InternalParse(new MemoryStream(data));
}
/// <summary>
/// Parses SIP message from specified stream.
/// </summary>
/// <param name="stream">SIP message stream.</param>
protected void InternalParse(Stream stream)
{
/* SIP message syntax:
header-line<CRFL>
....
<CRFL>
data size of Content-Length header field.
*/
// Parse header
this.Header.Parse(stream);
// Parse data
int contentLength = 0;
try{
contentLength = Convert.ToInt32(m_pHeader.GetFirst("Content-Length:").Value);
}
catch{
}
if(contentLength > 0){
byte[] data = new byte[contentLength];
stream.Read(data,0,data.Length);
this.Data = data;
}
}
#endregion
#region mehtod InternalToStream
/// <summary>
/// Stores SIP_Message to specified stream.
/// </summary>
/// <param name="stream">Stream where to store SIP_Message.</param>
protected void InternalToStream(Stream stream)
{
// Ensure that we add right Contnet-Length.
m_pHeader.RemoveAll("Content-Length:");
if(m_Data != null){
m_pHeader.Add("Content-Length:",Convert.ToString(m_Data.Length));
}
else{
m_pHeader.Add("Content-Length:",Convert.ToString(0));
}
// Store header
byte[] header = Encoding.UTF8.GetBytes(m_pHeader.ToHeaderString());
stream.Write(header,0,header.Length);
// Store data
if(m_Data != null && m_Data.Length > 0){
stream.Write(m_Data,0,m_Data.Length);
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets direct access to header.
/// </summary>
public SIP_HeaderFieldCollection Header
{
get{ return m_pHeader; }
}
/// <summary>
/// Gets or sets what features end point supports.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AcceptRange> Accept
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AcceptRange>(this,"Accept:"); }
}
/// <summary>
/// Gets or sets Accept-Contact header value. Defined in RFC 3841.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ACValue> AcceptContact
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ACValue>(this,"Accept-Contact:"); }
}
/// <summary>
/// Gets encodings what end point supports. Example: Accept-Encoding: gzip.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_Encoding> AcceptEncoding
{
get{ return new SIP_MVGroupHFCollection<SIP_t_Encoding>(this,"Accept-Encoding:"); }
}
/// <summary>
/// Gets preferred languages for reason phrases, session descriptions, or
/// status responses carried as message bodies in the response. If no Accept-Language
/// header field is present, the server SHOULD assume all languages are acceptable to the client.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_Language> AcceptLanguage
{
get{ return new SIP_MVGroupHFCollection<SIP_t_Language>(this,"Accept-Language:"); }
}
/// <summary>
/// Gets Accept-Resource-Priority headers. Defined in RFC 4412.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_RValue> AcceptResourcePriority
{
get{ return new SIP_MVGroupHFCollection<SIP_t_RValue>(this,"Accept-Resource-Priority:"); }
}
/// <summary>
/// Gets AlertInfo values collection. When present in an INVITE request, the Alert-Info header
/// field specifies an alternative ring tone to the UAS. When present in a 180 (Ringing) response,
/// the Alert-Info header field specifies an alternative ringback tone to the UAC.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AlertParam> AlertInfo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AlertParam>(this,"Alert-Info:"); }
}
/// <summary>
/// Gets methods collection which is supported by the UA which generated the message.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_Method> Allow
{
get{ return new SIP_MVGroupHFCollection<SIP_t_Method>(this,"Allow:"); }
}
/// <summary>
/// Gets Allow-Events header which indicates the event packages supported by the client. Defined in rfc 3265.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_EventType> AllowEvents
{
get{ return new SIP_MVGroupHFCollection<SIP_t_EventType>(this,"Allow-Events:"); }
}
/// <summary>
/// Gets the Authentication-Info header fields which provides for mutual authentication
/// with HTTP Digest.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_AuthenticationInfo> AuthenticationInfo
{
get{ return new SIP_SVGroupHFCollection<SIP_t_AuthenticationInfo>(this,"Authentication-Info:"); }
}
/// <summary>
/// Gets the Authorization header fields which contains authentication credentials of a UA.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_Credentials> Authorization
{
get{ return new SIP_SVGroupHFCollection<SIP_t_Credentials>(this,"Authorization:"); }
}
/// <summary>
/// Gets or sets the Call-ID header field which uniquely identifies a particular invitation or all
/// registrations of a particular client.
/// Value null means not specified.
/// </summary>
public string CallID
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Call-ID:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Call-ID:");
}
else{
m_pHeader.Set("Call-ID:",value);
}
}
}
/// <summary>
/// Gets the Call-Info header field which provides additional information about the
/// caller or callee, depending on whether it is found in a request or response.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_Info> CallInfo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_Info>(this,"Call-Info:"); }
}
/// <summary>
/// Gets contact header fields. The Contact header field provides a SIP or SIPS URI that can be used
/// to contact that specific instance of the UA for subsequent requests.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ContactParam> Contact
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ContactParam>(this,"Contact:"); }
}
/// <summary>
/// Gets or sets the Content-Disposition header field which describes how the message body
/// or, for multipart messages, a message body part is to be interpreted by the UAC or UAS.
/// Value null means not specified.
/// </summary>
public SIP_t_ContentDisposition ContentDisposition
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Content-Disposition:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_ContentDisposition>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Content-Disposition:");
}
else{
m_pHeader.Set("Content-Disposition:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets the Content-Encodings which is used as a modifier to the "media-type". When present,
/// its value indicates what additional content codings have been applied to the entity-body,
/// and thus what decoding mechanisms MUST be applied in order to obtain the media-type referenced
/// by the Content-Type header field.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ContentCoding> ContentEncoding
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ContentCoding>(this,"Content-Encoding:"); }
}
/// <summary>
/// Gets content languages.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_LanguageTag> ContentLanguage
{
get{ return new SIP_MVGroupHFCollection<SIP_t_LanguageTag>(this,"Content-Language:"); }
}
/// <summary>
/// Gets SIP request content data size in bytes.
/// </summary>
public int ContentLength
{
get{
if(m_Data == null){
return 0;
}
else{
return m_Data.Length;
}
}
}
/// <summary>
/// Gets or sets the Content-Type header field which indicates the media type of the
/// message-body sent to the recipient.
/// Value null means not specified.
/// </summary>
public string ContentType
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Content-Type:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Content-Type:");
}
else{
m_pHeader.Set("Content-Type:",value);
}
}
}
/// <summary>
/// Gets or sets command sequence number and the request method.
/// Value null means not specified.
/// </summary>
public SIP_t_CSeq CSeq
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("CSeq:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_CSeq>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("CSeq:");
}
else{
m_pHeader.Set("CSeq:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets or sets date and time. Value DateTime.MinValue means that value not specified.
/// </summary>
public DateTime Date
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Date:");
if(h != null){
return DateTime.ParseExact(h.Value,"r",System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
else{
return DateTime.MinValue;
}
}
set{
if(value == DateTime.MinValue){
m_pHeader.RemoveFirst("Date:");
}
else{
m_pHeader.Set("Date:",value.ToString("r"));
}
}
}
/// <summary>
/// Gets the Error-Info header field which provides a pointer to additional
/// information about the error status response.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ErrorUri> ErrorInfo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ErrorUri>(this,"Error-Info:"); }
}
/// <summary>
/// Gets or sets Event header. Defined in RFC 3265.
/// </summary>
public SIP_t_Event Event
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Event:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_Event>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Event:");
}
else{
m_pHeader.Set("Event:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets or sets relative time after which the message (or content) expires.
/// Value -1 means that value not specified.
/// </summary>
public int Expires
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Expires:");
if(h != null){
return Convert.ToInt32(h.Value);
}
else{
return -1;
}
}
set{
if(value < 0){
m_pHeader.RemoveFirst("Expires:");
}
else{
m_pHeader.Set("Expires:",value.ToString());
}
}
}
/// <summary>
/// Gets or sets initiator of the request.
/// Value null means not specified.
/// </summary>
public SIP_t_From From
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("From:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_From>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("From:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_From>("From:",value));
}
}
}
/// <summary>
/// Gets History-Info headers. Defined in RFC 4244.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_HiEntry> HistoryInfo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_HiEntry>(this,"History-Info:"); }
}
/// <summary>
/// Identity header value. Value null means not specified. Defined in RFC 4474.
/// </summary>
public string Identity
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Identity:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Identity:");
}
else{
m_pHeader.Set("Identity:",value);
}
}
}
/// <summary>
/// Gets or sets Identity-Info header value. Value null means not specified.
/// Defined in RFC 4474.
/// </summary>
public SIP_t_IdentityInfo IdentityInfo
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Identity-Info:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_IdentityInfo>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Identity-Info:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_IdentityInfo>("Identity-Info:",value));
}
}
}
/// <summary>
/// Gets the In-Reply-To header fields which enumerates the Call-IDs that this call
/// references or returns.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_CallID> InReplyTo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_CallID>(this,"In-Reply-To:"); }
}
/// <summary>
/// Gets or sets Join header which indicates that a new dialog (created by the INVITE in which
/// the Join header field in contained) should be joined with a dialog identified by the header
/// field, and any associated dialogs or conferences. Defined in 3911. Value null means not specified.
/// </summary>
public SIP_t_Join Join
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Join:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_Join>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Join:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Join>("Join:",value));
}
}
}
/// <summary>
/// Gets or sets limit the number of proxies or gateways that can forward the request
/// to the next downstream server.
/// Value -1 means that value not specified.
/// </summary>
public int MaxForwards
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Max-Forwards:");
if(h != null){
return Convert.ToInt32(h.Value);
}
else{
return -1;
}
}
set{
if(value < 0){
m_pHeader.RemoveFirst("Max-Forwards:");
}
else{
m_pHeader.Set("Max-Forwards:",value.ToString());
}
}
}
/// <summary>
/// Gets or sets mime version. Currently 1.0 is only defined value.
/// Value null means not specified.
/// </summary>
public string MimeVersion
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Mime-Version:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Mime-Version:");
}
else{
m_pHeader.Set("Mime-Version:",value);
}
}
}
/// <summary>
/// Gets or sets minimum refresh interval supported for soft-state elements managed by that server.
/// Value -1 means that value not specified.
/// </summary>
public int MinExpires
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Min-Expires:");
if(h != null){
return Convert.ToInt32(h.Value);
}
else{
return -1;
}
}
set{
if(value < 0){
m_pHeader.RemoveFirst("Min-Expires:");
}
else{
m_pHeader.Set("Min-Expires:",value.ToString());
}
}
}
/// <summary>
/// Gets or sets Min-SE header which indicates the minimum value for the session interval,
/// in units of delta-seconds. Defined in 4028. Value null means not specified.
/// </summary>
public SIP_t_MinSE MinSE
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Min-SE:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_MinSE>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Min-SE:");
}
else{
m_pHeader.Set("Min-SE:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets or sets organization name which the SIP element issuing the request or response belongs.
/// Value null means not specified.
/// </summary>
public string Organization
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Organization:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Organization:");
}
else{
m_pHeader.Set("Organization:",value);
}
}
}
/// <summary>
/// Gets an Path header. It is used in conjunction with SIP REGISTER requests and with 200
/// class messages in response to REGISTER (REGISTER responses). Defined in rfc 3327.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_AddressParam> Path
{
get{ return new SIP_SVGroupHFCollection<SIP_t_AddressParam>(this,"Path:"); }
}
/// <summary>
/// Gest or sets priority that the SIP request should have to the receiving human or its agent.
/// Value null means not specified.
/// </summary>
public string Priority
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Priority:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Priority:");
}
else{
m_pHeader.Set("Priority:",value);
}
}
}
// Privacy [RFC3323]
/// <summary>
/// Gets an proxy authentication challenge.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_Challenge> ProxyAuthenticate
{
get{ return new SIP_SVGroupHFCollection<SIP_t_Challenge>(this,"Proxy-Authenticate:"); }
}
/// <summary>
/// Gest credentials containing the authentication information of the user agent
/// for the proxy and/or realm of the resource being requested.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_Credentials> ProxyAuthorization
{
get{ return new SIP_SVGroupHFCollection<SIP_t_Credentials>(this,"Proxy-Authorization:"); }
}
/// <summary>
/// Gets proxy-sensitive features that must be supported by the proxy.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_OptionTag> ProxyRequire
{
get{ return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this,"Proxy-Require:"); }
}
/// <summary>
/// Gets or sets RAck header. Defined in 3262. Value null means not specified.
/// </summary>
public SIP_t_RAck RAck
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("RAck:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_RAck>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("RAck:");
}
else{
m_pHeader.Set("RAck:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets the Reason header. Defined in rfc 3326.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ReasonValue> Reason
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ReasonValue>(this,"Reason:"); }
}
/// <summary>
/// Gets the Record-Route header fields what is inserted by proxies in a request to
/// force future requests in the dialog to be routed through the proxy.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AddressParam> RecordRoute
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this,"Record-Route:"); }
}
/// <summary>
/// Gets or sets Refer-Sub header. Defined in rfc 4488. Value null means not specified.
/// </summary>
public SIP_t_ReferSub ReferSub
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Refer-Sub:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_ReferSub>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Refer-Sub:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_ReferSub>("Refer-Sub:",value));
}
}
}
/// <summary>
/// Gets or sets Refer-To header. Defined in rfc 3515. Value null means not specified.
/// </summary>
public SIP_t_AddressParam ReferTo
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Refer-To:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_AddressParam>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Refer-To:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_AddressParam>("Refer-To:",value));
}
}
}
/// <summary>
/// Gets or sets Referred-By header. Defined in rfc 3892. Value null means not specified.
/// </summary>
public SIP_t_ReferredBy ReferredBy
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Referred-By:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_ReferredBy>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Referred-By:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_ReferredBy>("Referred-By:",value));
}
}
}
/// <summary>
/// Gets Reject-Contact headers. Defined in RFC 3841.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_RCValue> RejectContact
{
get{ return new SIP_MVGroupHFCollection<SIP_t_RCValue>(this,"Reject-Contact:"); }
}
/// <summary>
/// Gets or sets Replaces header. Defined in rfc 3891. Value null means not specified.
/// </summary>
public SIP_t_Replaces Replaces
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Replaces:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_Replaces>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Replaces:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Replaces>("Replaces:",value));
}
}
}
/// <summary>
/// Gets logical return URI that may be different from the From header field.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AddressParam> ReplyTo
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this,"Reply-To:"); }
}
/// <summary>
/// Gets or sets Request-Disposition header. The Request-Disposition header field specifies caller preferences for
/// how a server should process a request. Defined in rfc 3841.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_Directive> RequestDisposition
{
get{ return new SIP_MVGroupHFCollection<SIP_t_Directive>(this,"Request-Disposition:"); }
}
/// <summary>
/// Gets options that the UAC expects the UAS to support in order to process the request.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_OptionTag> Require
{
get{ return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this,"Require:"); }
}
/// <summary>
/// Gets Resource-Priority headers. Defined in RFC 4412.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_RValue> ResourcePriority
{
get{ return new SIP_MVGroupHFCollection<SIP_t_RValue>(this,"Resource-Priority:"); }
}
/// <summary>
/// Gets or sets how many seconds the service is expected to be unavailable to the requesting client.
/// Value null means that value not specified.
/// </summary>
public SIP_t_RetryAfter RetryAfter
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Retry-After:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_RetryAfter>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Retry-After:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_RetryAfter>("Retry-After:",value));
}
}
}
/// <summary>
/// Gets force routing for a request through the listed set of proxies.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AddressParam> Route
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this,"Route:"); }
}
/// <summary>
/// Gets or sets RSeq header. Value -1 means that value not specified. Defined in rfc 3262.
/// </summary>
public int RSeq
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("RSeq:");
if(h != null){
return Convert.ToInt32(h.Value);
}
else{
return -1;
}
}
set{
if(value < 0){
m_pHeader.RemoveFirst("RSeq:");
}
else{
m_pHeader.Set("RSeq:",value.ToString());
}
}
}
/// <summary>
/// Gets Security-Client headers. Defined in RFC 3329.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityClient
{
get{ return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this,"Security-Client:"); }
}
/// <summary>
/// Gets Security-Server headers. Defined in RFC 3329.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityServer
{
get{ return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this,"Security-Server:"); }
}
/// <summary>
/// Gets Security-Verify headers. Defined in RFC 3329.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityVerify
{
get{ return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this,"Security-Verify:"); }
}
/// <summary>
/// Gets or sets the software used by the UAS to handle the request.
/// Value null means not specified.
/// </summary>
public string Server
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Server:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Server:");
}
else{
m_pHeader.Set("Server:",value);
}
}
}
/// <summary>
/// Gets the Service-Route header. Defined in rfc 3608.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_AddressParam> ServiceRoute
{
get{ return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this,"Service-Route:"); }
}
/// <summary>
/// Gets or sets Session-Expires expires header. Value null means that value not specified.
/// Defined in rfc 4028.
/// </summary>
public SIP_t_SessionExpires SessionExpires
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Session-Expires:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_SessionExpires>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Session-Expires:");
}
else{
m_pHeader.Set("Session-Expires:",value.ToStringValue());
}
}
}
/// <summary>
/// Gets or sets SIP-ETag header value. Value null means not specified. Defined in RFC 3903.
/// </summary>
public string SIPETag
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("SIP-ETag:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("SIP-ETag:");
}
else{
m_pHeader.Set("SIP-ETag:",value);
}
}
}
/// <summary>
/// Gets or sets SIP-ETag header value. Value null means not specified. Defined in RFC 3903.
/// </summary>
public string SIPIfMatch
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("SIP-If-Match:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("SIP-If-Match:");
}
else{
m_pHeader.Set("SIP-If-Match:",value);
}
}
}
/// <summary>
/// Gets or sets call subject text.
/// Value null means not specified.
/// </summary>
public string Subject
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Subject:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Subject:");
}
else{
m_pHeader.Set("Subject:",value);
}
}
}
/// <summary>
/// Gets or sets Subscription-State header value. Value null means that value not specified.
/// Defined in RFC 3265.
/// </summary>
public SIP_t_SubscriptionState SubscriptionState
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Subscription-State:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_SubscriptionState>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Subscription-State:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_SubscriptionState>("Subscription-State:",value));
}
}
}
/// <summary>
/// Gets extensions supported by the UAC or UAS. Known values are defined in SIP_OptionTags class.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_OptionTag> Supported
{
get{ return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this,"Supported:"); }
}
/// <summary>
/// Gets or sets Target-Dialog header value. Value null means that value not specified.
/// Defined in RFC 4538.
/// </summary>
public SIP_t_TargetDialog TargetDialog
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Target-Dialog:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_TargetDialog>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Target-Dialog:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_TargetDialog>("Target-Dialog:",value));
}
}
}
/// <summary>
/// Gets or sets when the UAC sent the request to the UAS.
/// Value null means that value not specified.
/// </summary>
public SIP_t_Timestamp Timestamp
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("Timestamp:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_Timestamp>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("Timestamp:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Timestamp>("Timestamp:",value));
}
}
}
/// <summary>
/// Gets or sets logical recipient of the request.
/// Value null means not specified.
/// </summary>
public SIP_t_To To
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("To:");
if(h != null){
return ((SIP_SingleValueHF<SIP_t_To>)h).ValueX;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("To:");
}
else{
m_pHeader.Add(new SIP_SingleValueHF<SIP_t_To>("To:",value));
}
}
}
/// <summary>
/// Gets features not supported by the UAS.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_OptionTag> Unsupported
{
get{ return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this,"Unsupported:"); }
}
/// <summary>
/// Gets or sets information about the UAC originating the request.
/// Value null means not specified.
/// </summary>
public string UserAgent
{
get{
SIP_HeaderField h = m_pHeader.GetFirst("User-Agent:");
if(h != null){
return h.Value;
}
else{
return null;
}
}
set{
if(value == null){
m_pHeader.RemoveFirst("User-Agent:");
}
else{
m_pHeader.Set("User-Agent:",value);
}
}
}
/// <summary>
/// Gets Via header fields.The Via header field indicates the transport used for the transaction
/// and identifies the location where the response is to be sent.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_ViaParm> Via
{
get{ return new SIP_MVGroupHFCollection<SIP_t_ViaParm>(this,"Via:"); }
}
/// <summary>
/// Gets additional information about the status of a response.
/// </summary>
public SIP_MVGroupHFCollection<SIP_t_WarningValue> Warning
{
get{ return new SIP_MVGroupHFCollection<SIP_t_WarningValue>(this,"Warning:"); }
}
/// <summary>
/// Gets or authentication challenge.
/// </summary>
public SIP_SVGroupHFCollection<SIP_t_Challenge> WWWAuthenticate
{
get{ return new SIP_SVGroupHFCollection<SIP_t_Challenge>(this,"WWW-Authenticate:"); }
}
/// <summary>
/// Gets or sets content data.
/// </summary>
public byte[] Data
{
get{ return m_Data; }
set{ m_Data = value; }
}
#endregion
}
}
| |
namespace Sitecore.FakeDb.Data.Engines
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.FakeDb.Data.Items;
using Sitecore.FakeDb.Pipelines;
using Sitecore.FakeDb.Pipelines.AddDbItem;
using Sitecore.Globalization;
using Sitecore.Pipelines;
using ItemIDs = Sitecore.ItemIDs;
using Version = Sitecore.Data.Version;
public class DataStorage
{
private static readonly ID TemplateIdSitecore = new ID("{C6576836-910C-4A3D-BA03-C277DBD3B827}");
private static readonly ID SourceFieldId = new ID("{1B86697D-60CA-4D80-83FB-7555A2E6CE1C}");
private readonly Database database;
private readonly IDictionary<ID, DbItem> fakeItems;
private readonly IDictionary<Guid, Stream> blobs;
public DataStorage(Database database)
{
this.database = database;
this.fakeItems = new Dictionary<ID, DbItem>();
this.blobs = new Dictionary<Guid, Stream>();
this.FillDefaultFakeTemplates();
this.FillDefaultFakeItems();
}
public Database Database
{
get { return this.database; }
}
protected IDictionary<ID, DbItem> FakeItems
{
get { return this.fakeItems; }
}
protected IDictionary<Guid, Stream> Blobs
{
get { return this.blobs; }
}
public virtual void AddFakeItem(DbItem item)
{
this.AddFakeItem(item, Language.Current);
}
public virtual void AddFakeItem(DbItem item, Language language)
{
Assert.ArgumentNotNull(item, "item");
var loading = item is IDsDbItem;
if (item as DbTemplate != null)
{
var template = (DbTemplate)item;
if (!loading)
{
this.AssertDoesNotExists(template);
}
if (template is IDsDbItem)
{
CorePipeline.Run("loadDsDbTemplate", new DsItemLoadingArgs(template as IDsDbItem, this));
}
}
if (loading)
{
CorePipeline.Run("loadDsDbItem", new DsItemLoadingArgs(item as IDsDbItem, this));
}
CorePipeline.Run("addDbItem", new AddDbItemArgs(item, this, language));
if (!loading)
{
this.AssertDoesNotExists(item);
}
this.FakeItems[item.ID] = item;
if (item as DbTemplate != null)
{
this.Database.Engines.TemplateEngine.Reset();
}
foreach (var child in item.Children)
{
this.AddFakeItem(child);
}
}
public virtual DbItem GetFakeItem(ID itemId)
{
Assert.ArgumentCondition(!ID.IsNullOrEmpty(itemId), "itemId", "Value cannot be null.");
return this.FakeItems.ContainsKey(itemId) ? this.FakeItems[itemId] : null;
}
public virtual DbTemplate GetFakeTemplate(ID templateId)
{
return this.FakeItems.ContainsKey(templateId) ? this.FakeItems[templateId] as DbTemplate : null;
}
public virtual IEnumerable<DbTemplate> GetFakeTemplates()
{
return this.FakeItems.Values.OfType<DbTemplate>();
}
public virtual Item GetSitecoreItem(ID itemId)
{
return this.GetSitecoreItem(itemId, Language.Current);
}
public virtual Item GetSitecoreItem(ID itemId, Language language)
{
return this.GetSitecoreItem(itemId, language, Version.First);
}
public virtual Item GetSitecoreItem(ID itemId, Language language, Version version)
{
Assert.ArgumentNotNull(itemId, "itemId");
Assert.ArgumentNotNull(language, "language");
Assert.ArgumentNotNull(version, "version");
if (!this.FakeItems.ContainsKey(itemId))
{
return null;
}
// TODO:[High] Avoid the templates resetting. Required to avoid sharing templates between unit tests.
this.Database.Engines.TemplateEngine.Reset();
var fakeItem = this.FakeItems[itemId];
if (version == Version.Latest)
{
version = Version.Parse(fakeItem.GetVersionCount(language.Name));
if (version == Version.Latest)
{
version = Version.First;
}
}
var fields = this.BuildItemFieldList(fakeItem, fakeItem.TemplateID, language, version);
return ItemHelper.CreateInstance(this.database, fakeItem.Name, fakeItem.ID, fakeItem.TemplateID, fakeItem.BranchId, fields, language, version);
}
public virtual IEnumerable<DbItem> GetFakeItems()
{
return this.FakeItems.Values;
}
public virtual bool RemoveFakeItem(ID itemId)
{
return this.FakeItems.Remove(itemId);
}
public virtual void SetBlobStream(Guid blobId, Stream stream)
{
Assert.ArgumentNotNull(stream, "stream");
this.Blobs[blobId] = stream;
}
public virtual Stream GetBlobStream(Guid blobId)
{
return this.Blobs.ContainsKey(blobId) ? this.Blobs[blobId] : null;
}
public FieldList BuildItemFieldList(DbItem fakeItem, ID templateId, Language language, Version version)
{
// build a sequence of templates that the item inherits from
var templates = this.ExpandTemplatesSequence(templateId);
var fields = new FieldList();
foreach (var template in templates)
{
this.AddFieldsFromTemplate(fields, fakeItem, template, language, version);
}
// If the item is a Template item we also need to add the BaseTemplate field
var fakeItemAsTemplate = fakeItem as DbTemplate;
if (fakeItemAsTemplate != null && fakeItemAsTemplate.BaseIDs != null)
{
fields.Add(FieldIDs.BaseTemplate, string.Join("|", fakeItemAsTemplate.BaseIDs.ToList()));
}
return fields;
}
/// <summary>
/// Similar to Template.GetBaseTemplates() the method expands the template inheritance hierarchy
/// </summary>
/// <param name="templateId">The template id.</param>
/// <returns>The list of tempaltes.</returns>
protected List<DbTemplate> ExpandTemplatesSequence(ID templateId)
{
var fakeTemplate = this.GetFakeTemplate(templateId);
if (fakeTemplate == null)
{
return new List<DbTemplate>();
}
var sequence = new List<DbTemplate> { fakeTemplate };
if (fakeTemplate.BaseIDs != null)
{
foreach (var baseId in fakeTemplate.BaseIDs)
{
sequence.AddRange(this.ExpandTemplatesSequence(baseId));
}
}
sequence.Reverse();
return sequence;
}
protected void AddFieldsFromTemplate(FieldList allFields, DbItem fakeItem, DbTemplate fakeTemplate, Language language, Version version)
{
var sourceItem = this.GetSourceItem(fakeItem);
foreach (var templateField in fakeTemplate.Fields)
{
var fieldId = templateField.ID;
var itemField = this.FindItemDbField(fakeItem, templateField);
if (itemField == null)
{
continue;
}
var value = itemField.GetValue(language.Name, version.Number);
if (sourceItem != null && string.IsNullOrWhiteSpace(value))
{
continue;
}
if (value != null)
{
allFields.Add(fieldId, value);
}
}
foreach (var template in fakeTemplate.BaseIDs.Select(this.GetFakeTemplate).Where(t => t != null))
{
this.AddFieldsFromTemplate(allFields, fakeItem, template, language, version);
}
if (fakeTemplate.BaseIDs.Any() || fakeTemplate.ID == TemplateIDs.StandardTemplate)
{
return;
}
var standardTemplate = this.GetFakeTemplate(TemplateIDs.StandardTemplate);
this.AddFieldsFromTemplate(allFields, fakeItem, standardTemplate, language, version);
}
protected DbField FindItemDbField(DbItem fakeItem, DbField templateField)
{
Assert.IsNotNull(fakeItem, "fakeItem");
Assert.IsNotNull(templateField, "templateField");
// The item has fields with the IDs matching the fields in the template it directly inherits from
if (fakeItem.Fields.ContainsKey(templateField.ID))
{
return fakeItem.Fields[templateField.ID];
}
return fakeItem.Fields.SingleOrDefault(f => string.Equals(f.Name, templateField.Name));
}
protected void FillDefaultFakeTemplates()
{
this.FakeItems.Add(TemplateIdSitecore, new DbTemplate("Sitecore", new TemplateID(TemplateIdSitecore)) { new DbField(FieldIDs.Security) });
this.FakeItems.Add(TemplateIDs.MainSection, new DbTemplate("Main Section", TemplateIDs.MainSection));
this.FakeItems.Add(
TemplateIDs.Template,
new DbTemplate(ItemNames.Template, TemplateIDs.Template)
{
ParentID = ItemIDs.TemplateRoot,
FullPath = "/sitecore/templates/template",
Fields = { new DbField(FieldIDs.BaseTemplate) }
});
this.FakeItems.Add(TemplateIDs.Folder, new DbTemplate(ItemNames.Folder, TemplateIDs.Folder));
this.FakeItems.Add(
TemplateIDs.StandardTemplate,
new DbTemplate(TemplateIDs.StandardTemplate)
{
new DbField("__Base template"),
// Advanced
new DbField("__Source"),
new DbField("__Source Item"),
new DbField("__Enable item fallback"),
new DbField("__Enforce version presence"),
new DbField("__Standard values"),
new DbField("__Tracking"),
// Appearance
new DbField("__Context Menu"),
new DbField("__Display name"),
new DbField("__Editor"),
new DbField("__Editors"),
new DbField("__Hidden"),
new DbField("__Icon"),
new DbField("__Read Only"),
new DbField("__Ribbon"),
new DbField("__Skin"),
new DbField("__Sortorder"),
new DbField("__Style"),
new DbField("__Subitems Sorting"),
new DbField("__Thumbnail"),
new DbField("__Originator"),
new DbField("__Preview"),
// Help
new DbField("__Help link"),
new DbField("__Long description"),
new DbField("__Short description"),
// Layout
new DbField("__Renderings"),
new DbField("__Final Renderings"),
new DbField("__Renderers"),
new DbField("__Controller"),
new DbField("__Controller Action"),
new DbField("__Presets"),
new DbField("__Page Level Test Set Definition"),
new DbField("__Content Test"),
// Lifetime
new DbField("__Valid to"),
new DbField("__Hide version"),
new DbField("__Valid from"),
// Indexing
new DbField("__Boost"),
new DbField("__Boosting Rules"),
new DbField("__Facets"),
// Insert Options
new DbField("__Insert Rules"),
new DbField("__Masters"),
// Item Buckets
new DbField("__Bucket Parent Reference"),
new DbField("__Is Bucket"),
new DbField("__Bucketable"),
new DbField("__Should Not Organize In Bucket"),
new DbField("__Default Bucket Query"),
new DbField("__Persistent Bucket Filter"),
new DbField("__Enabled Views"),
new DbField("__Default View"),
new DbField("__Quick Actions"),
// Publishing
new DbField("__Publish"),
new DbField("__Unpublish"),
new DbField("__Publishing groups"),
new DbField("__Never publish"),
// Security
new DbField("__Owner"),
new DbField("__Security"),
// Statistics
new DbField("__Created"),
new DbField("__Created by"),
new DbField("__Revision"),
new DbField("__Updated"),
new DbField("__Updated by"),
// Tagging
new DbField("__Semantics"),
// Tasks
new DbField("__Archive date"),
new DbField("__Archive Version date"),
new DbField("__Reminder date"),
new DbField("__Reminder recipients"),
new DbField("__Reminder text"),
// Validation Rules
new DbField("__Quick Action Bar Validation Rules"),
new DbField("__Validate Button Validation Rules"),
new DbField("__Validator Bar Validation Rules"),
new DbField("__Workflow Validation Rules"),
new DbField("__Suppressed Validation Rules"),
// Workflow
new DbField("__Workflow"),
new DbField("__Workflow state"),
new DbField("__Lock"),
new DbField("__Default workflow"),
});
this.FakeItems.Add(
TemplateIDs.TemplateField,
new DbTemplate(ItemNames.TemplateField, TemplateIDs.TemplateField, TemplateIDs.TemplateField)
{
ParentID = ItemIDs.TemplateRoot,
FullPath = "/sitecore/templates/template field",
Fields =
{
new DbField(TemplateFieldIDs.Type),
new DbField(TemplateFieldIDs.Shared),
new DbField(TemplateFieldIDs.Source)
}
});
}
protected void FillDefaultFakeItems()
{
var field = new DbField("__Security") { Value = "ar|Everyone|p*|+*|" };
this.FakeItems.Add(ItemIDs.RootID, new DbItem(ItemNames.Sitecore, ItemIDs.RootID, TemplateIdSitecore) { ParentID = ID.Null, FullPath = "/sitecore", Fields = { field } });
this.FakeItems.Add(ItemIDs.ContentRoot, new DbItem(ItemNames.Content, ItemIDs.ContentRoot, TemplateIDs.MainSection) { ParentID = ItemIDs.RootID, FullPath = "/sitecore/content" });
this.FakeItems.Add(ItemIDs.TemplateRoot, new DbItem(ItemNames.Templates, ItemIDs.TemplateRoot, TemplateIDs.MainSection) { ParentID = ItemIDs.RootID, FullPath = "/sitecore/templates" });
this.FakeItems.Add(ItemIDs.BranchesRoot, new DbItem(ItemNames.Branches, ItemIDs.BranchesRoot, TemplateIDs.BranchTemplateFolder) { ParentID = ItemIDs.TemplateRoot, FullPath = "/sitecore/templates/Branches" });
this.FakeItems.Add(ItemIDs.SystemRoot, new DbItem(ItemNames.System, ItemIDs.SystemRoot, TemplateIDs.MainSection) { ParentID = ItemIDs.RootID, FullPath = "/sitecore/system" });
this.FakeItems.Add(ItemIDs.MediaLibraryRoot, new DbItem(ItemNames.MediaLibrary, ItemIDs.MediaLibraryRoot, TemplateIDs.MainSection) { ParentID = ItemIDs.RootID, FullPath = "/sitecore/media library" });
this.FakeItems[ItemIDs.RootID].Add(this.FakeItems[ItemIDs.ContentRoot]);
this.FakeItems[ItemIDs.RootID].Add(this.FakeItems[ItemIDs.TemplateRoot]);
this.FakeItems[ItemIDs.RootID].Add(this.FakeItems[ItemIDs.SystemRoot]);
this.FakeItems[ItemIDs.RootID].Add(this.FakeItems[ItemIDs.MediaLibraryRoot]);
// TODO: Move 'Template' item to proper directory to correspond Sitecore structure.
this.FakeItems.Add(TemplateIDs.TemplateSection, new DbTemplate(ItemNames.TemplateSection, TemplateIDs.TemplateSection, TemplateIDs.TemplateSection) { ParentID = ItemIDs.TemplateRoot, FullPath = "/sitecore/templates/template section" });
this.FakeItems.Add(TemplateIDs.BranchTemplate, new DbItem(ItemNames.Branch, TemplateIDs.BranchTemplate, TemplateIDs.Template) { ParentID = ItemIDs.TemplateRoot, FullPath = "/sitecore/templates/branch" });
this.AddFakeItem(new DbItem(ItemNames.DefinitionsRoot, ItemIDs.Analytics.MarketingCenterItem, TemplateIDs.Folder) { ParentID = ItemIDs.SystemRoot, FullPath = "/sitecore/system/Marketing Control Panel" });
this.AddFakeItem(new DbItem(ItemNames.Profiles, ItemIDs.Analytics.Profiles, TemplateIDs.Folder) { ParentID = ItemIDs.Analytics.MarketingCenterItem, FullPath = "/sitecore/system/Marketing Control Panel/Profiles" });
if (this.Database.Name == "core")
{
this.AddFakeItem(
new DbItem(ItemNames.FieldTypes, new ID("{76E6D8C7-1F93-4712-872B-DA3C96B808F2}"), TemplateIDs.Node)
{
ParentID = ItemIDs.SystemRoot,
Children = { new DbItem("text") { { "Control", "Text" } } }
});
}
}
private void AssertDoesNotExists(DbItem item)
{
if (!this.FakeItems.ContainsKey(item.ID))
{
return;
}
var existingItem = this.FakeItems[item.ID];
string message;
if (existingItem is DbTemplate)
{
message = string.Format("A template with the same id has already been added ('{0}', '{1}').", item.ID, item.FullPath ?? item.Name);
}
else if (existingItem.GetType() == typeof(DbItem) && item is DbTemplate)
{
message = string.Format("Unable to create the item based on the template '{0}'. An item with the same id has already been added ('{1}').", item.ID, existingItem.FullPath);
}
else
{
message = string.Format("An item with the same id has already been added ('{0}', '{1}').", item.ID, item.FullPath);
}
throw new InvalidOperationException(message);
}
private DbItem GetSourceItem(DbItem fakeItem)
{
if (!fakeItem.Fields.ContainsKey(SourceFieldId))
{
return null;
}
var sourceUri = fakeItem.Fields[SourceFieldId].Value;
if (!ItemUri.IsItemUri(sourceUri))
{
return null;
}
return this.GetFakeItem(new ItemUri(sourceUri).ItemID);
}
}
}
| |
namespace Epi.Windows.MakeView.Forms
{
partial class Canvas
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Canvas));
this.pagePanel = new System.Windows.Forms.Panel();
this.imgCanvas = new System.Windows.Forms.ImageList(this.components);
this.txtMsgTrace = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
this.baseImageList.Images.SetKeyName(87, "");
this.baseImageList.Images.SetKeyName(88, "");
this.baseImageList.Images.SetKeyName(89, "");
this.baseImageList.Images.SetKeyName(90, "");
this.baseImageList.Images.SetKeyName(91, "");
this.baseImageList.Images.SetKeyName(92, "");
this.baseImageList.Images.SetKeyName(93, "");
this.baseImageList.Images.SetKeyName(94, "");
this.baseImageList.Images.SetKeyName(95, "");
this.baseImageList.Images.SetKeyName(96, "");
//
// pagePanel
//
pagePanel.AllowDrop = true;
resources.ApplyResources(this.pagePanel, "pagePanel");
pagePanel.BackColor = System.Drawing.Color.Transparent;
pagePanel.Name = "pagePanel";
pagePanel.DragDrop += new System.Windows.Forms.DragEventHandler(this.PagePanel_DragDrop);
pagePanel.DragOver += new System.Windows.Forms.DragEventHandler(this.PagePanel_DragOver);
pagePanel.Paint += new System.Windows.Forms.PaintEventHandler(this.PagePanel_Paint);
pagePanel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panel_MouseDown);
pagePanel.MouseUp += new System.Windows.Forms.MouseEventHandler(panel_MouseUp);
pagePanel.Resize += new System.EventHandler(PagePanel_Resize);
pagePanel.MouseMove += new System.Windows.Forms.MouseEventHandler(panel_MouseMove);
pagePanel.MouseEnter += new System.EventHandler(pagePanel_MouseEnter);
pagePanel.Dock = System.Windows.Forms.DockStyle.None;
pagePanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
pagePanel.Visible = false;
pagePanel.Tag = "PagePanel";
//
// imgCanvas
//
this.imgCanvas.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgCanvas.ImageStream")));
this.imgCanvas.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(0)))), ((int)(((byte)(255)))));
this.imgCanvas.Images.SetKeyName(0, "button.bmp");
this.imgCanvas.Images.SetKeyName(1, "checkbox.bmp");
this.imgCanvas.Images.SetKeyName(2, "date.bmp");
this.imgCanvas.Images.SetKeyName(3, "dropdown.bmp");
this.imgCanvas.Images.SetKeyName(4, "grid.bmp");
this.imgCanvas.Images.SetKeyName(5, "group.bmp");
this.imgCanvas.Images.SetKeyName(6, "image.bmp");
this.imgCanvas.Images.SetKeyName(7, "label.bmp");
this.imgCanvas.Images.SetKeyName(8, "mirror.bmp");
this.imgCanvas.Images.SetKeyName(9, "numeric.bmp");
this.imgCanvas.Images.SetKeyName(10, "openfields.bmp");
this.imgCanvas.Images.SetKeyName(11, "radiobutton.bmp");
this.imgCanvas.Images.SetKeyName(12, "text.bmp");
this.imgCanvas.Images.SetKeyName(13, "uppercase.bmp");
this.imgCanvas.Images.SetKeyName(14, "ProgramLarge.bmp");
this.imgCanvas.Images.SetKeyName(15, "delete.bmp");
this.imgCanvas.Images.SetKeyName(16, "properties.bmp");
this.imgCanvas.Images.SetKeyName(17, "taborder.bmp");
this.imgCanvas.Images.SetKeyName(18, "undo.bmp");
//
// txtMsgTrace
//
resources.ApplyResources(this.txtMsgTrace, "txtMsgTrace");
this.txtMsgTrace.Name = "txtMsgTrace";
//
// Canvas
//
this.AllowDock = false;
this.AllowUnDock = false;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ControlBox = false;
this.Controls.Add(this.pagePanel);
this.DockType = Epi.Windows.Docking.DockContainerType.Document;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.IsVisible = true;
this.Name = "Canvas";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel pagePanel;
private System.Windows.Forms.ImageList imgCanvas;
private System.Windows.Forms.TextBox txtMsgTrace;
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// PrimitivesSampleGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
#endregion
namespace PrimitivesSample
{
// This sample illustrates the use of PrimitiveBatch to draw lines and points
// on the screen. Lines and points are used to recreate the Spacewars starter kit's
// retro mode.
public class PrimitivesSampleGame : Microsoft.Xna.Framework.Game
{
#region Constants
// this constant controls the number of stars that will be created when the game
// starts up.
const int NumStars = 500;
// what percentage of those stars will be "big" stars? the default is 20%.
const float PercentBigStars = .2f;
// how bright will stars be? somewhere between these two values.
const byte MinimumStarBrightness = 56;
const byte MaximumStarBrightness = 255;
// how big is the ship?
const float ShipSizeX = 10f;
const float ShipSizeY = 15f;
const float ShipCutoutSize = 5f;
// the radius of the sun.
const float SunSize = 30f;
#endregion
#region Fields
GraphicsDeviceManager graphics;
// PrimitiveBatch is the new class introduced in this sample. We'll use it to
// draw everything in this sample, including the stars, ships, and sun.
PrimitiveBatch primitiveBatch;
// these two lists, stars, and starColors, keep track of the positions and
// colors of all the stars that we will randomly generate during the initialize
// phase.
List<Vector2> stars = new List<Vector2>();
List<Color> starColors = new List<Color>();
#endregion
#region Initialization
public PrimitivesSampleGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if WINDOWS_PHONE
TargetElapsedTime = TimeSpan.FromTicks(333333);
graphics.PreferredBackBufferWidth = 480;
graphics.PreferredBackBufferHeight = 800;
graphics.IsFullScreen = true;
#else
// set the backbuffer size to something that will work well on both xbox
// and windows.
graphics.PreferredBackBufferWidth = 853;
graphics.PreferredBackBufferHeight = 480;
#endif
}
protected override void Initialize()
{
base.Initialize();
// CreateStars needs to know how big the GraphicsDevice's viewport is, so
// once base.Initialize has been called, we can call this.
CreateStars();
}
private void CreateStars()
{
// since every star will be put in a random place and have a random color,
// a random number generator might come in handy.
Random random = new Random();
// where can we put the stars?
int screenWidth = graphics.GraphicsDevice.Viewport.Width;
int screenHeight = graphics.GraphicsDevice.Viewport.Height;
for (int i = 0; i < NumStars; i++)
{
// pick a random spot...
Vector2 where = new Vector2(
random.Next(0, screenWidth),
random.Next(0, screenHeight));
// ...and a random color. it's safe to cast random.Next to a byte,
// because MinimumStarBrightness and MaximumStarBrightness are both
// bytes.
byte greyValue =
(byte)random.Next(MinimumStarBrightness, MaximumStarBrightness);
Color color = new Color(greyValue, greyValue, greyValue);
// if the random number was greater than the percentage chance for a big
// star, this is just a normal star.
if ((float)random.NextDouble() > PercentBigStars)
{
starColors.Add(color);
stars.Add(where);
}
else
{
// if this star is randomly selected to be a "big" star, we actually
// add four points and colors to stars and starColors. big stars are
// a block of four points, instead of just one point.
for (int j = 0; j < 4; j++)
{
starColors.Add(color);
}
stars.Add(where);
stars.Add(where + Vector2.UnitX);
stars.Add(where + Vector2.UnitY);
stars.Add(where + Vector2.One);
}
}
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
primitiveBatch = new PrimitiveBatch(graphics.GraphicsDevice);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
|| Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
// how big is the screen? we'll use that information to center the sun
// and place the ships.
int screenWidth = graphics.GraphicsDevice.Viewport.Width;
int screenHeight = graphics.GraphicsDevice.Viewport.Height;
// draw the sun in the center
DrawSun(new Vector2(screenWidth / 2, screenHeight / 2));
// draw the left hand ship
DrawShip(new Vector2(100, screenHeight / 2));
// and the right hand ship
DrawShip(new Vector2(screenWidth - 100, screenHeight / 2));
DrawStars();
base.Draw(gameTime);
}
// DrawStars is called to do exactly what its name says: draw the stars.
private void DrawStars()
{
// stars are drawn as a list of points, so begin the primitiveBatch.
primitiveBatch.Begin(PrimitiveType.TriangleList);
// loop through all of the stars, and tell primitive batch to draw them.
// each star is a very small triangle.
for (int i = 0; i < stars.Count; i++)
{
primitiveBatch.AddVertex(stars[i], starColors[i]);
primitiveBatch.AddVertex(stars[i] + Vector2.UnitX, starColors[i]);
primitiveBatch.AddVertex(stars[i] + Vector2.UnitY, starColors[i]);
}
// and then tell it that we're done.
primitiveBatch.End();
}
// called to draw the spacewars ship at a point on the screen.
private void DrawShip(Vector2 where)
{
// tell the primitive batch to start drawing lines
primitiveBatch.Begin(PrimitiveType.LineList);
// from the nose, down the left hand side
primitiveBatch.AddVertex(
where + new Vector2(0f, -ShipSizeY), Color.White);
primitiveBatch.AddVertex(
where + new Vector2(-ShipSizeX, ShipSizeY), Color.White);
// to the right and up, into the cutout
primitiveBatch.AddVertex(
where + new Vector2(-ShipSizeX, ShipSizeY), Color.White);
primitiveBatch.AddVertex(
where + new Vector2(0f, ShipSizeY - ShipCutoutSize), Color.White);
// to the right and down, out of the cutout
primitiveBatch.AddVertex(
where + new Vector2(0f, ShipSizeY - ShipCutoutSize), Color.White);
primitiveBatch.AddVertex(
where + new Vector2(ShipSizeX, ShipSizeY), Color.White);
// and back up to the nose, where we started.
primitiveBatch.AddVertex(
where + new Vector2(ShipSizeX, ShipSizeY), Color.White);
primitiveBatch.AddVertex(
where + new Vector2(0f, -ShipSizeY), Color.White);
// and we're done.
primitiveBatch.End();
}
// called to draw the spacewars sun.
private void DrawSun(Vector2 where)
{
// the sun is made from 4 lines in a circle.
primitiveBatch.Begin(PrimitiveType.LineList);
// draw the vertical and horizontal lines
primitiveBatch.AddVertex(where + new Vector2(0, SunSize), Color.White);
primitiveBatch.AddVertex(where + new Vector2(0, -SunSize), Color.White);
primitiveBatch.AddVertex(where + new Vector2(SunSize, 0), Color.White);
primitiveBatch.AddVertex(where + new Vector2(-SunSize, 0), Color.White);
// to know where to draw the diagonal lines, we need to use trig.
// cosine of pi / 4 tells us what the x coordinate of a circle's radius is
// at 45 degrees. the y coordinate normally would come from sin, but sin and
// cos 45 are the same, so we can reuse cos for both x and y.
float sunSizeDiagonal = (float)Math.Cos(MathHelper.PiOver4);
// since that trig tells us the x and y for a unit circle, which has a
// radius of 1, we need scale that result by the sun's radius.
sunSizeDiagonal *= SunSize;
primitiveBatch.AddVertex(
where + new Vector2(-sunSizeDiagonal, sunSizeDiagonal), Color.Gray);
primitiveBatch.AddVertex(
where + new Vector2(sunSizeDiagonal, -sunSizeDiagonal), Color.Gray);
primitiveBatch.AddVertex(
where + new Vector2(sunSizeDiagonal, sunSizeDiagonal), Color.Gray);
primitiveBatch.AddVertex(
where + new Vector2(-sunSizeDiagonal, -sunSizeDiagonal), Color.Gray);
primitiveBatch.End();
}
#endregion
#region Entry point
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (PrimitivesSampleGame game = new PrimitivesSampleGame())
{
game.Run();
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderedHashRepartitionEnumerator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator handles the actual coordination among partitions required to
/// accomplish the repartitioning operation, as explained above. In addition to that,
/// it tracks order keys so that order preservation can flow through the enumerator.
/// </summary>
/// <typeparam name="TInputOutput">The kind of elements.</typeparam>
/// <typeparam name="THashKey">The key used to distribute elements.</typeparam>
/// <typeparam name="TOrderKey">The kind of keys found in the source.</typeparam>
internal class OrderedHashRepartitionEnumerator<TInputOutput, THashKey, TOrderKey> : QueryOperatorEnumerator<Pair<TInputOutput, THashKey>, TOrderKey>
{
private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet.
private readonly int m_partitionCount; // The number of partitions.
private readonly int m_partitionIndex; // Our unique partition index.
private readonly Func<TInputOutput, THashKey> m_keySelector; // A key-selector function.
private readonly HashRepartitionStream<TInputOutput, THashKey, TOrderKey> m_repartitionStream; // A repartitioning stream.
private readonly ListChunk<Pair<TInputOutput, THashKey>>[,] m_valueExchangeMatrix; // Matrix to do inter-task communication of values.
private readonly ListChunk<TOrderKey>[,] m_keyExchangeMatrix; // Matrix to do inter-task communication of order keys.
private readonly QueryOperatorEnumerator<TInputOutput, TOrderKey> m_source; // The immediate source of data.
private CountdownEvent m_barrier; // Used to signal and wait for repartitions to complete.
private readonly CancellationToken m_cancellationToken; // A token for canceling the process.
private Mutables m_mutables; // Mutable fields for this enumerator.
class Mutables
{
internal int m_currentBufferIndex; // Current buffer index.
internal ListChunk<Pair<TInputOutput, THashKey>> m_currentBuffer; // The buffer we're currently enumerating.
internal ListChunk<TOrderKey> m_currentKeyBuffer; // The buffer we're currently enumerating.
internal int m_currentIndex; // Current index into the buffer.
internal Mutables()
{
m_currentBufferIndex = ENUMERATION_NOT_STARTED;
}
}
//---------------------------------------------------------------------------------------
// Creates a new repartitioning enumerator.
//
// Arguments:
// source - the data stream from which to pull elements
// useOrdinalOrderPreservation - whether order preservation is required
// partitionCount - total number of partitions
// partitionIndex - this operator's unique partition index
// repartitionStream - the stream object to use for partition selection
// barrier - a latch used to signal task completion
// buffers - a set of buffers for inter-task communication
//
internal OrderedHashRepartitionEnumerator(
QueryOperatorEnumerator<TInputOutput, TOrderKey> source, int partitionCount, int partitionIndex,
Func<TInputOutput, THashKey> keySelector, OrderedHashRepartitionStream<TInputOutput, THashKey, TOrderKey> repartitionStream, CountdownEvent barrier,
ListChunk<Pair<TInputOutput, THashKey>>[,] valueExchangeMatrix, ListChunk<TOrderKey>[,] keyExchangeMatrix, CancellationToken cancellationToken)
{
Contract.Assert(source != null);
Contract.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired));
Contract.Assert(repartitionStream != null);
Contract.Assert(barrier != null);
Contract.Assert(valueExchangeMatrix != null);
Contract.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)");
Contract.Assert(valueExchangeMatrix.GetLength(1) == partitionCount, "expected square matrix of buffers (NxN)");
Contract.Assert(0 <= partitionIndex && partitionIndex < partitionCount);
m_source = source;
m_partitionCount = partitionCount;
m_partitionIndex = partitionIndex;
m_keySelector = keySelector;
m_repartitionStream = repartitionStream;
m_barrier = barrier;
m_valueExchangeMatrix = valueExchangeMatrix;
m_keyExchangeMatrix = keyExchangeMatrix;
m_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Retrieves the next element from this partition. All repartitioning operators across
// all partitions cooperate in a barrier-style algorithm. The first time an element is
// requested, the repartitioning operator will enter the 1st phase: during this phase, it
// scans its entire input and compute the destination partition for each element. During
// the 2nd phase, each partition scans the elements found by all other partitions for
// it, and yield this to callers. The only synchronization required is the barrier itself
// -- all other parts of this algorithm are synchronization-free.
//
// Notes: One rather large penalty that this algorithm incurs is higher memory usage and a
// larger time-to-first-element latency, at least compared with our old implementation; this
// happens because all input elements must be fetched before we can produce a single output
// element. In many cases this isn't too terrible: e.g. a GroupBy requires this to occur
// anyway, so having the repartitioning operator do so isn't complicating matters much at all.
//
internal override bool MoveNext(ref Pair<TInputOutput, THashKey> currentElement, ref TOrderKey currentKey)
{
if (m_partitionCount == 1)
{
TInputOutput current = default(TInputOutput);
// If there's only one partition, no need to do any sort of exchanges.
if (m_source.MoveNext(ref current, ref currentKey))
{
currentElement = new Pair<TInputOutput, THashKey>(
current, m_keySelector == null ? default(THashKey) : m_keySelector(current));
return true;
}
return false;
}
Mutables mutables = m_mutables;
if (mutables == null)
mutables = m_mutables = new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
if (mutables.m_currentBufferIndex == ENUMERATION_NOT_STARTED)
{
EnumerateAndRedistributeElements();
Contract.Assert(mutables.m_currentBufferIndex != ENUMERATION_NOT_STARTED);
}
// Once we've enumerated our contents, we can then go back and walk the buffers that belong
// to the current partition. This is phase two. Note that we slyly move on to the first step
// of phase two before actually waiting for other partitions. That's because we can enumerate
// the buffer we wrote to above, as already noted.
while (mutables.m_currentBufferIndex < m_partitionCount)
{
// If the queue is non-null and still has elements, yield them.
if (mutables.m_currentBuffer != null)
{
Contract.Assert(mutables.m_currentKeyBuffer != null);
if (++mutables.m_currentIndex < mutables.m_currentBuffer.Count)
{
// Return the current element.
currentElement = mutables.m_currentBuffer.m_chunk[mutables.m_currentIndex];
Contract.Assert(mutables.m_currentKeyBuffer != null, "expected same # of buffers/key-buffers");
currentKey = mutables.m_currentKeyBuffer.m_chunk[mutables.m_currentIndex];
return true;
}
else
{
// If the chunk is empty, advance to the next one (if any).
mutables.m_currentIndex = ENUMERATION_NOT_STARTED;
mutables.m_currentBuffer = mutables.m_currentBuffer.Next;
mutables.m_currentKeyBuffer = mutables.m_currentKeyBuffer.Next;
Contract.Assert(mutables.m_currentBuffer == null || mutables.m_currentBuffer.Count > 0);
Contract.Assert((mutables.m_currentBuffer == null) == (mutables.m_currentKeyBuffer == null));
Contract.Assert(mutables.m_currentBuffer == null || mutables.m_currentBuffer.Count == mutables.m_currentKeyBuffer.Count);
continue; // Go back around and invoke this same logic.
}
}
// We're done with the current partition. Slightly different logic depending on whether
// we're on our own buffer or one that somebody else found for us.
if (mutables.m_currentBufferIndex == m_partitionIndex)
{
// We now need to wait at the barrier, in case some other threads aren't done.
// Once we wake up, we reset our index and will increment it immediately after.
m_barrier.Wait(m_cancellationToken);
mutables.m_currentBufferIndex = ENUMERATION_NOT_STARTED;
}
// Advance to the next buffer.
mutables.m_currentBufferIndex++;
mutables.m_currentIndex = ENUMERATION_NOT_STARTED;
if (mutables.m_currentBufferIndex == m_partitionIndex)
{
// Skip our current buffer (since we already enumerated it).
mutables.m_currentBufferIndex++;
}
// Assuming we're within bounds, retrieve the next buffer object.
if (mutables.m_currentBufferIndex < m_partitionCount)
{
mutables.m_currentBuffer = m_valueExchangeMatrix[mutables.m_currentBufferIndex, m_partitionIndex];
mutables.m_currentKeyBuffer = m_keyExchangeMatrix[mutables.m_currentBufferIndex, m_partitionIndex];
}
}
// We're done. No more buffers to enumerate.
return false;
}
//---------------------------------------------------------------------------------------
// Called when this enumerator is first enumerated; it must walk through the source
// and redistribute elements to their slot in the exchange matrix.
//
private void EnumerateAndRedistributeElements()
{
Mutables mutables = m_mutables;
Contract.Assert(mutables != null);
ListChunk<Pair<TInputOutput, THashKey>>[] privateBuffers = new ListChunk<Pair<TInputOutput, THashKey>>[m_partitionCount];
ListChunk<TOrderKey>[] privateKeyBuffers = new ListChunk<TOrderKey>[m_partitionCount];
TInputOutput element = default(TInputOutput);
TOrderKey key = default(TOrderKey);
int loopCount = 0;
while (m_source.MoveNext(ref element, ref key))
{
if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(m_cancellationToken);
// Calculate the element's destination partition index, placing it into the
// appropriate buffer from which partitions will later enumerate.
int destinationIndex;
THashKey elementHashKey = default(THashKey);
if (m_keySelector != null)
{
elementHashKey = m_keySelector(element);
destinationIndex = m_repartitionStream.GetHashCode(elementHashKey) % m_partitionCount;
}
else
{
Contract.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired));
destinationIndex = m_repartitionStream.GetHashCode(element) % m_partitionCount;
}
Contract.Assert(0 <= destinationIndex && destinationIndex < m_partitionCount,
"destination partition outside of the legal range of partitions");
// Get the buffer for the destnation partition, lazily allocating if needed. We maintain
// this list in our own private cache so that we avoid accessing shared memory locations
// too much. In the original implementation, we'd access the buffer in the matrix ([N,M],
// where N is the current partition and M is the destination), but some rudimentary
// performance profiling indicates copying at the end performs better.
ListChunk<Pair<TInputOutput, THashKey>> buffer = privateBuffers[destinationIndex];
ListChunk<TOrderKey> keyBuffer = privateKeyBuffers[destinationIndex];
if (buffer == null)
{
const int INITIAL_PRIVATE_BUFFER_SIZE = 128;
Contract.Assert(keyBuffer == null);
privateBuffers[destinationIndex] = buffer = new ListChunk<Pair<TInputOutput, THashKey>>(INITIAL_PRIVATE_BUFFER_SIZE);
privateKeyBuffers[destinationIndex] = keyBuffer = new ListChunk<TOrderKey>(INITIAL_PRIVATE_BUFFER_SIZE);
}
buffer.Add(new Pair<TInputOutput, THashKey>(element, elementHashKey));
keyBuffer.Add(key);
}
// Copy the local buffers to the shared space and then signal to other threads that
// we are done. We can then immediately move on to enumerating the elements we found
// for the current partition before waiting at the barrier. If we found a lot, we will
// hopefully never have to physically wait.
for (int i = 0; i < m_partitionCount; i++)
{
m_valueExchangeMatrix[m_partitionIndex, i] = privateBuffers[i];
m_keyExchangeMatrix[m_partitionIndex, i] = privateKeyBuffers[i];
}
m_barrier.Signal();
// Begin at our own buffer.
mutables.m_currentBufferIndex = m_partitionIndex;
mutables.m_currentBuffer = privateBuffers[m_partitionIndex];
mutables.m_currentKeyBuffer = privateKeyBuffers[m_partitionIndex];
mutables.m_currentIndex = ENUMERATION_NOT_STARTED;
}
protected override void Dispose(bool disposing)
{
if (m_barrier != null)
{
// Since this enumerator is being disposed, we will decrement the barrier,
// in case other enumerators will wait on the barrier.
if (m_mutables == null || (m_mutables.m_currentBufferIndex == ENUMERATION_NOT_STARTED))
{
m_barrier.Signal();
m_barrier = null;
}
m_source.Dispose();
}
}
}
}
| |
// <copyright file="UserSvdTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
/// <summary>
/// Svd factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserSvdTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorSvd = matrixI.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
Assert.AreEqual(matrixI.RowCount, u.RowCount);
Assert.AreEqual(matrixI.RowCount, u.ColumnCount);
Assert.AreEqual(matrixI.ColumnCount, vt.RowCount);
Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount);
Assert.AreEqual(matrixI.RowCount, w.RowCount);
Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount);
for (var i = 0; i < w.RowCount; i++)
{
for (var j = 0; j < w.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, w[i, j]);
}
}
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
// Make sure the U has the right dimensions.
Assert.AreEqual(row, u.RowCount);
Assert.AreEqual(row, u.ColumnCount);
// Make sure the VT has the right dimensions.
Assert.AreEqual(column, vt.RowCount);
Assert.AreEqual(column, vt.ColumnCount);
// Make sure the W has the right dimensions.
Assert.AreEqual(row, w.RowCount);
Assert.AreEqual(column, w.ColumnCount);
// Make sure the U*W*VT is the original matrix.
var matrix = u*w*vt;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrixA[i, j], matrix[i, j], 1e-4);
}
}
}
/// <summary>
/// Can check rank of a non-square matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(10, 8)]
[TestCase(48, 52)]
[TestCase(100, 93)]
public void CanCheckRankOfNonSquare(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var mn = Math.Min(row, column);
Assert.AreEqual(factorSvd.Rank, mn);
}
/// <summary>
/// Can check rank of a square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(9)]
[TestCase(50)]
[TestCase(90)]
public void CanCheckRankSquare(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(order, order, 1).ToArray());
var factorSvd = matrixA.Svd();
if (factorSvd.Determinant != 0)
{
Assert.AreEqual(factorSvd.Rank, order);
}
else
{
Assert.AreEqual(factorSvd.Rank, order - 1);
}
}
/// <summary>
/// Can check rank of a square singular matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanCheckRankOfSquareSingular(int order)
{
var matrixA = new UserDefinedMatrix(order, order);
matrixA[0, 0] = 1;
matrixA[order - 1, order - 1] = 1;
for (var i = 1; i < order - 1; i++)
{
matrixA[i, i - 1] = 1;
matrixA[i, i + 1] = 1;
matrixA[i - 1, i] = 1;
matrixA[i + 1, i] = 1;
}
var factorSvd = matrixA.Svd();
Assert.AreEqual(factorSvd.Determinant, 0);
Assert.AreEqual(factorSvd.Rank, order - 1);
}
/// <summary>
/// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(10, 10, 1).ToArray());
Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException);
}
/// <summary>
/// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var vectorb = new UserDefinedVector(Vector<float>.Build.Random(10, 1).ToArray());
Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException);
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVector(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<float>.Build.Random(row, 1).ToArray());
var resultx = factorSvd.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixX = factorSvd.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<float>.Build.Random(row, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(column);
factorSvd.Solve(vectorb, resultx);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, column, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(column, column);
factorSvd.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Unity.Collections;
namespace UnityEngine.Rendering.LWRP
{
internal class AdditionalLightsShadowCasterPass : ScriptableRenderPass
{
private static class AdditionalShadowsConstantBuffer
{
public static int _AdditionalLightsWorldToShadow;
public static int _AdditionalShadowStrength;
public static int _AdditionalShadowOffset0;
public static int _AdditionalShadowOffset1;
public static int _AdditionalShadowOffset2;
public static int _AdditionalShadowOffset3;
public static int _AdditionalShadowmapSize;
}
const int k_ShadowmapBufferBits = 16;
private RenderTargetHandle m_AdditionalLightsShadowmap;
RenderTexture m_AdditionalLightsShadowmapTexture;
int m_ShadowmapWidth;
int m_ShadowmapHeight;
Matrix4x4[] m_AdditionalLightShadowMatrices;
ShadowSliceData[] m_AdditionalLightSlices;
float[] m_AdditionalLightsShadowStrength;
List<int> m_AdditionalShadowCastingLightIndices = new List<int>();
const string m_ProfilerTag = "Render Additional Shadows";
public AdditionalLightsShadowCasterPass(RenderPassEvent evt)
{
renderPassEvent = evt;
int maxLights = LightweightRenderPipeline.maxVisibleAdditionalLights;
m_AdditionalLightShadowMatrices = new Matrix4x4[maxLights];
m_AdditionalLightSlices = new ShadowSliceData[maxLights];
m_AdditionalLightsShadowStrength = new float[maxLights];
AdditionalShadowsConstantBuffer._AdditionalLightsWorldToShadow = Shader.PropertyToID("_AdditionalLightsWorldToShadow");
AdditionalShadowsConstantBuffer._AdditionalShadowStrength = Shader.PropertyToID("_AdditionalShadowStrength");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset0 = Shader.PropertyToID("_AdditionalShadowOffset0");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset1 = Shader.PropertyToID("_AdditionalShadowOffset1");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset2 = Shader.PropertyToID("_AdditionalShadowOffset2");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset3 = Shader.PropertyToID("_AdditionalShadowOffset3");
AdditionalShadowsConstantBuffer._AdditionalShadowmapSize = Shader.PropertyToID("_AdditionalShadowmapSize");
m_AdditionalLightsShadowmap.Init("_AdditionalLightsShadowmapTexture");
}
public bool Setup(ref RenderingData renderingData)
{
if (!renderingData.shadowData.supportsAdditionalLightShadows)
return false;
Clear();
m_ShadowmapWidth = renderingData.shadowData.additionalLightsShadowmapWidth;
m_ShadowmapHeight = renderingData.shadowData.additionalLightsShadowmapHeight;
Bounds bounds;
var visibleLights = renderingData.lightData.visibleLights;
int additionalLightsCount = renderingData.lightData.additionalLightsCount;
for (int i = 0; i < visibleLights.Length && m_AdditionalShadowCastingLightIndices.Count < additionalLightsCount; ++i)
{
if (i == renderingData.lightData.mainLightIndex)
continue;
VisibleLight shadowLight = visibleLights[i];
Light light = shadowLight.light;
if (shadowLight.lightType == LightType.Spot && light != null && light.shadows != LightShadows.None)
{
if (renderingData.cullResults.GetShadowCasterBounds(i, out bounds))
m_AdditionalShadowCastingLightIndices.Add(i);
}
}
int shadowCastingLightsCount = m_AdditionalShadowCastingLightIndices.Count;
if (shadowCastingLightsCount == 0)
return false;
// TODO: Add support to point light shadows. We make a simplification here that only works
// for spot lights and with max spot shadows per pass.
int atlasWidth = renderingData.shadowData.additionalLightsShadowmapWidth;
int atlasHeight = renderingData.shadowData.additionalLightsShadowmapHeight;
int sliceResolution = ShadowUtils.GetMaxTileResolutionInAtlas(atlasWidth, atlasHeight, shadowCastingLightsCount);
bool anyShadows = false;
int shadowSlicesPerRow = (atlasWidth / sliceResolution);
for (int i = 0; i < shadowCastingLightsCount; ++i)
{
int shadowLightIndex = m_AdditionalShadowCastingLightIndices[i];
VisibleLight shadowLight = visibleLights[shadowLightIndex];
// Currently Only Spot Lights are supported in additional lights
Debug.Assert(shadowLight.lightType == LightType.Spot);
Matrix4x4 shadowTransform;
bool success = ShadowUtils.ExtractSpotLightMatrix(ref renderingData.cullResults, ref renderingData.shadowData,
shadowLightIndex, out shadowTransform, out m_AdditionalLightSlices[i].viewMatrix, out m_AdditionalLightSlices[i].projectionMatrix);
if (success)
{
// TODO: We need to pass bias and scale list to shader to be able to support multiple
// shadow casting additional lights.
m_AdditionalLightSlices[i].offsetX = (i % shadowSlicesPerRow) * sliceResolution;
m_AdditionalLightSlices[i].offsetY = (i / shadowSlicesPerRow) * sliceResolution;
m_AdditionalLightSlices[i].resolution = sliceResolution;
m_AdditionalLightSlices[i].shadowTransform = shadowTransform;
m_AdditionalLightsShadowStrength[i] = shadowLight.light.shadowStrength;
anyShadows = true;
}
else
{
m_AdditionalShadowCastingLightIndices.RemoveAt(i--);
}
}
return anyShadows;
}
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
m_AdditionalLightsShadowmapTexture = ShadowUtils.GetTemporaryShadowTexture(m_ShadowmapWidth, m_ShadowmapHeight, k_ShadowmapBufferBits);
ConfigureTarget(new RenderTargetIdentifier(m_AdditionalLightsShadowmapTexture));
ConfigureClear(ClearFlag.All, Color.black);
}
/// <inheritdoc/>
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
if (renderingData.shadowData.supportsAdditionalLightShadows)
RenderAdditionalShadowmapAtlas(ref context, ref renderingData.cullResults, ref renderingData.lightData, ref renderingData.shadowData);
}
public override void FrameCleanup(CommandBuffer cmd)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
if (m_AdditionalLightsShadowmapTexture)
{
RenderTexture.ReleaseTemporary(m_AdditionalLightsShadowmapTexture);
m_AdditionalLightsShadowmapTexture = null;
}
}
void Clear()
{
m_AdditionalShadowCastingLightIndices.Clear();
m_AdditionalLightsShadowmapTexture = null;
for (int i = 0; i < m_AdditionalLightShadowMatrices.Length; ++i)
m_AdditionalLightShadowMatrices[i] = Matrix4x4.identity;
for (int i = 0; i < m_AdditionalLightSlices.Length; ++i)
m_AdditionalLightSlices[i].Clear();
for (int i = 0; i < m_AdditionalLightsShadowStrength.Length; ++i)
m_AdditionalLightsShadowStrength[i] = 0.0f;
}
void RenderAdditionalShadowmapAtlas(ref ScriptableRenderContext context, ref CullingResults cullResults, ref LightData lightData, ref ShadowData shadowData)
{
NativeArray<VisibleLight> visibleLights = lightData.visibleLights;
bool additionalLightHasSoftShadows = false;
CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);
using (new ProfilingSample(cmd, m_ProfilerTag))
{
for (int i = 0; i < m_AdditionalShadowCastingLightIndices.Count; ++i)
{
int shadowLightIndex = m_AdditionalShadowCastingLightIndices[i];
VisibleLight shadowLight = visibleLights[shadowLightIndex];
if (m_AdditionalShadowCastingLightIndices.Count > 1)
ShadowUtils.ApplySliceTransform(ref m_AdditionalLightSlices[i], m_ShadowmapWidth, m_ShadowmapHeight);
var settings = new ShadowDrawingSettings(cullResults, shadowLightIndex);
Vector4 shadowBias = ShadowUtils.GetShadowBias(ref shadowLight, shadowLightIndex,
ref shadowData, m_AdditionalLightSlices[i].projectionMatrix, m_AdditionalLightSlices[i].resolution);
ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias);
ShadowUtils.RenderShadowSlice(cmd, ref context, ref m_AdditionalLightSlices[i], ref settings, m_AdditionalLightSlices[i].projectionMatrix, m_AdditionalLightSlices[i].viewMatrix);
additionalLightHasSoftShadows |= shadowLight.light.shadows == LightShadows.Soft;
}
SetupAdditionalLightsShadowReceiverConstants(cmd, ref shadowData);
}
// We share soft shadow settings for main light and additional lights to save keywords.
// So we check here if pipeline supports soft shadows and either main light or any additional light has soft shadows
// to enable the keyword.
// TODO: In PC and Consoles we can upload shadow data per light and branch on shader. That will be more likely way faster.
bool mainLightHasSoftShadows = shadowData.supportsMainLightShadows &&
lightData.mainLightIndex != -1 &&
visibleLights[lightData.mainLightIndex].light.shadows == LightShadows.Soft;
bool softShadows = shadowData.supportsSoftShadows && (mainLightHasSoftShadows || additionalLightHasSoftShadows);
CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, true);
CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.SoftShadows, softShadows);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
void SetupAdditionalLightsShadowReceiverConstants(CommandBuffer cmd, ref ShadowData shadowData)
{
for (int i = 0; i < m_AdditionalLightSlices.Length; ++i)
m_AdditionalLightShadowMatrices[i] = m_AdditionalLightSlices[i].shadowTransform;
float invShadowAtlasWidth = 1.0f / shadowData.additionalLightsShadowmapWidth;
float invShadowAtlasHeight = 1.0f / shadowData.additionalLightsShadowmapHeight;
float invHalfShadowAtlasWidth = 0.5f * invShadowAtlasWidth;
float invHalfShadowAtlasHeight = 0.5f * invShadowAtlasHeight;
cmd.SetGlobalTexture(m_AdditionalLightsShadowmap.id, m_AdditionalLightsShadowmapTexture);
cmd.SetGlobalMatrixArray(AdditionalShadowsConstantBuffer._AdditionalLightsWorldToShadow, m_AdditionalLightShadowMatrices);
cmd.SetGlobalFloatArray(AdditionalShadowsConstantBuffer._AdditionalShadowStrength, m_AdditionalLightsShadowStrength);
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset0, new Vector4(-invHalfShadowAtlasWidth, -invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset1, new Vector4(invHalfShadowAtlasWidth, -invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset2, new Vector4(-invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset3, new Vector4(invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowmapSize, new Vector4(invShadowAtlasWidth, invShadowAtlasHeight,
shadowData.additionalLightsShadowmapWidth, shadowData.additionalLightsShadowmapHeight));
}
}
}
| |
// <copyright file="TokeniserTests.cs" company="Peter Ibbotson">
// (C) Copyright 2017 Peter Ibbotson
// </copyright>
namespace ClassicBasic.Test.InterpreterTests
{
using Autofac;
using ClassicBasic.Interpreter;
using ClassicBasic.Interpreter.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Test for the tokeniser.
/// </summary>
[TestClass]
public class TokeniserTests
{
private static ITokeniser _tokeniser;
/// <summary>
/// Initialises the tokeniser.
/// </summary>
/// <param name="context">Test context.</param>
[ClassInitialize]
public static void SetupSut(TestContext context)
{
var builder = new ContainerBuilder();
RegisterTypes.Register(builder);
builder.RegisterInstance(new MockTeletype()).As<ITeletype>();
var container = builder.Build();
_tokeniser = container.Resolve<ITokeniser>();
}
/// <summary>
/// Basic smoke test that we parse code without spaces.
/// </summary>
[TestMethod]
public void ValidCode()
{
var result = _tokeniser.Tokenise("20IFI<>10THENPRINT\"HELLO\"");
Assert.AreEqual(20, result.LineNumber.Value);
TokenCheck(result.NextToken(), "IF", TokenClass.Statement);
TokenCheck(result.NextToken(), "I", TokenClass.Variable);
TokenCheck(result.NextToken(), "<", TokenClass.Seperator);
TokenCheck(result.NextToken(), ">", TokenClass.Seperator);
TokenCheck(result.NextToken(), "10", TokenClass.Number);
TokenCheck(result.NextToken(), "THEN", TokenClass.Statement);
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
TokenCheck(result.NextToken(), "HELLO", TokenClass.String);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that we find tokens at the end of the line.
/// </summary>
[TestMethod]
public void FindTokensAtEnd()
{
var result = _tokeniser.Tokenise("LET AFOR=23");
TokenCheck(result.NextToken(), "LET", TokenClass.Statement);
TokenCheck(result.NextToken(), "A", TokenClass.Variable);
TokenCheck(result.NextToken(), "FOR", TokenClass.Statement);
TokenCheck(result.NextToken(), "=", TokenClass.Seperator);
TokenCheck(result.NextToken(), "23", TokenClass.Number);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that we find tokens at the end of the line.
/// </summary>
[TestMethod]
public void FindOddTokensAtEnd()
{
var result = _tokeniser.Tokenise("LET AFOR=ONER");
TokenCheck(result.NextToken(), "LET", TokenClass.Statement);
TokenCheck(result.NextToken(), "A", TokenClass.Variable);
TokenCheck(result.NextToken(), "FOR", TokenClass.Statement);
TokenCheck(result.NextToken(), "=", TokenClass.Seperator);
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
TokenCheck(result.NextToken(), "ER", TokenClass.Variable);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that we convert ? to PRINT.
/// </summary>
[TestMethod]
public void ConvertQuestionMarkToPrint()
{
var result = _tokeniser.Tokenise("?\"x\":?");
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
TokenCheck(result.NextToken(), "x", TokenClass.String);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that remarks keep spaces and case correctly.
/// </summary>
[TestMethod]
public void RemarksKeepSpacesAndCase()
{
var result = _tokeniser.Tokenise("REM Hello World");
TokenCheck(result.NextToken(), "REM", TokenClass.Statement);
TokenCheck(result.NextToken(), "Hello World", TokenClass.Remark);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that DATA keep spaces and case correctly.
/// </summary>
[TestMethod]
public void DataKeepSpacesAndCase()
{
var result = _tokeniser.Tokenise("DATA Hello World,\"DEF GH\"");
TokenCheck(result.NextToken(), "DATA", TokenClass.Statement);
TokenCheck(result.NextToken(), "Hello World,\"DEF GH\"", TokenClass.Data);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that DATA keep spaces, case and breaks on colon correctly.
/// </summary>
[TestMethod]
public void DataKeepSpacesAndCaseAndBreaksOnColon()
{
var result = _tokeniser.Tokenise("DATA Hello World, \"DEF GH\" : PRINT");
TokenCheck(result.NextToken(), "DATA", TokenClass.Statement);
TokenCheck(result.NextToken(), "Hello World, \"DEF GH\" ", TokenClass.Data);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that DATA keep spaces, case and breaks on colon correctly.
/// </summary>
[TestMethod]
public void DataKeepSpacesAndCaseAndBreaksOnColonUnlessQuoted()
{
var result = _tokeniser.Tokenise("DATA ab,cd\"ef,\"g:h\" : PRINT");
TokenCheck(result.NextToken(), "DATA", TokenClass.Statement);
TokenCheck(result.NextToken(), "ab,cd\"ef,\"g:h\" ", TokenClass.Data);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that blank DATA adds ClassDataToken.
/// </summary>
[TestMethod]
public void BlankDataAddsClassDataTokenWithNoColon()
{
var result = _tokeniser.Tokenise("DATA ");
TokenCheck(result.NextToken(), "DATA", TokenClass.Statement);
TokenCheck(result.NextToken(), string.Empty, TokenClass.Data);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that blank DATA adds ClassDataToken.
/// </summary>
[TestMethod]
public void BlankDataAddsClassDataTokenWithColon()
{
var result = _tokeniser.Tokenise("DATA : PRINT");
TokenCheck(result.NextToken(), "DATA", TokenClass.Statement);
TokenCheck(result.NextToken(), string.Empty, TokenClass.Data);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that the tokeniser terminates strings that don't have a closing quote.
/// </summary>
[TestMethod]
public void TokeniserTerminatesStrings()
{
var result = _tokeniser.Tokenise("PRINT \"Hello World");
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
TokenCheck(result.NextToken(), "Hello World", TokenClass.String);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Test that the tokeniser terminates strings that don't have a closing quote.
/// </summary>
[TestMethod]
public void TokeniserSplitsVariablesBeforeStrings()
{
var result = _tokeniser.Tokenise("PRINT AB\"Hello World");
TokenCheck(result.NextToken(), "PRINT", TokenClass.Statement);
TokenCheck(result.NextToken(), "AB", TokenClass.Variable);
TokenCheck(result.NextToken(), "Hello World", TokenClass.String);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Check we split correctly where the token is at the end.
/// </summary>
[TestMethod]
public void SplitAwkard()
{
var result = _tokeniser.Tokenise("ACRIGHT$(C$,1)");
TokenCheck(result.NextToken(), "AC", TokenClass.Variable);
TokenCheck(result.NextToken(), "RIGHT$", TokenClass.Function);
TokenCheck(result.NextToken(), "(", TokenClass.Seperator);
TokenCheck(result.NextToken(), "C", TokenClass.Variable);
TokenCheck(result.NextToken(), "$", TokenClass.Seperator);
TokenCheck(result.NextToken(), ",", TokenClass.Seperator);
TokenCheck(result.NextToken(), "1", TokenClass.Number);
TokenCheck(result.NextToken(), ")", TokenClass.Seperator);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// CONT is tricky we initially ended up parsing it as C ON T.
/// </summary>
[TestMethod]
public void SplitAwkardCont()
{
var result = _tokeniser.Tokenise("CON:CONT:CONX:ONX:CON");
TokenCheck(result.NextToken(), "C", TokenClass.Variable);
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "CONT", TokenClass.Statement);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "C", TokenClass.Variable);
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
TokenCheck(result.NextToken(), "X", TokenClass.Variable);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
TokenCheck(result.NextToken(), "X", TokenClass.Variable);
TokenCheck(result.NextToken(), ":", TokenClass.Seperator);
TokenCheck(result.NextToken(), "C", TokenClass.Variable);
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Special case
/// </summary>
[TestMethod]
public void SplitAwkardCont2()
{
var result = _tokeniser.Tokenise("ONX");
TokenCheck(result.NextToken(), "ON", TokenClass.Statement);
TokenCheck(result.NextToken(), "X", TokenClass.Variable);
Assert.IsTrue(result.EndOfLine);
}
/// <summary>
/// Tokeniser throws syntax error if line number > 65535
/// </summary>
/// <param name="command">Command to pass to Tokeniser.</param>
/// <param name="throwsException">Throws exception.</param>
[DataTestMethod]
[DataRow("65535 ONX", false)]
[DataRow("65536 ONX", true)]
public void TokeniserThrowsSyntaxErrorIfLineNumberToBig(string command, bool throwsException)
{
Test.Throws<SyntaxErrorException>(() => _tokeniser.Tokenise(command), throwsException);
}
private void TokenCheck(IToken token, string text, TokenClass tokenClass)
{
Assert.AreEqual(text, token.Text);
Assert.AreEqual(tokenClass, token.TokenClass);
}
}
}
| |
//
// Util.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 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;
using System.Collections;
using System.IO;
using System.Reflection;
using Mono.Addins.Description;
using Mono.Addins.Serialization;
using System.Collections.Generic;
namespace Mono.Addins.Database
{
internal class Util
{
static int isMono;
static string monoVersion;
public static bool IsWindows {
get { return Path.DirectorySeparatorChar == '\\'; }
}
public static bool IsMono {
get {
if (isMono == 0)
isMono = Type.GetType ("Mono.Runtime") != null ? 1 : -1;
return isMono == 1;
}
}
public static string MonoVersion {
get {
if (monoVersion == null) {
if (!IsMono)
throw new InvalidOperationException ();
MethodInfo mi = Type.GetType ("Mono.Runtime").GetMethod ("GetDisplayName", BindingFlags.NonPublic|BindingFlags.Static);
if (mi != null)
monoVersion = (string) mi.Invoke (null, null);
else
monoVersion = string.Empty;
}
return monoVersion;
}
}
public static void CheckWrittableFloder (string path)
{
string testFile = null;
int n = 0;
var random = new Random ();
do {
testFile = Path.Combine (path, random.Next ().ToString ());
n++;
} while (File.Exists (testFile) && n < 100);
if (n == 100)
throw new InvalidOperationException ("Could not create file in directory: " + path);
StreamWriter w = new StreamWriter (testFile);
w.Close ();
File.Delete (testFile);
}
public static void AddDependencies (AddinDescription desc, AddinScanResult scanResult)
{
// Not implemented in AddinScanResult to avoid making AddinDescription remotable
foreach (ModuleDescription mod in desc.AllModules) {
foreach (Dependency dep in mod.Dependencies) {
AddinDependency adep = dep as AddinDependency;
if (adep == null) continue;
string depid = Addin.GetFullId (desc.Namespace, adep.AddinId, adep.Version);
scanResult.AddAddinToUpdateRelations (depid);
}
}
}
public static Assembly LoadAssemblyForReflection (string fileName)
{
/* if (!gotLoadMethod) {
reflectionOnlyLoadFrom = typeof(Assembly).GetMethod ("ReflectionOnlyLoadFrom");
gotLoadMethod = true;
LoadAssemblyForReflection (typeof(Util).Assembly.Location);
}
if (reflectionOnlyLoadFrom != null)
return (Assembly) reflectionOnlyLoadFrom.Invoke (null, new string [] { fileName });
else
*/ return Assembly.LoadFile (fileName);
}
public static string NormalizePath (string path)
{
if (path.Length > 2 && path [0] == '[') {
int i = path.IndexOf (']', 1);
if (i != -1) {
try {
string fname = path.Substring (1, i - 1);
Environment.SpecialFolder sf = (Environment.SpecialFolder) Enum.Parse (typeof(Environment.SpecialFolder), fname, true);
path = Environment.GetFolderPath (sf) + path.Substring (i + 1);
} catch {
// Ignore
}
}
}
if (IsWindows)
return path.Replace ('/','\\');
else
return path.Replace ('\\','/');
}
// A private hash calculation method is used to be able to get consistent
// results across different .NET versions and implementations.
public static int GetStringHashCode (string s)
{
int h = 0;
int n = 0;
for (; n < s.Length - 1; n+=2) {
h = unchecked ((h << 5) - h + s[n]);
h = unchecked ((h << 5) - h + s[n+1]);
}
if (n < s.Length)
h = unchecked ((h << 5) - h + s[n]);
return h;
}
public static string GetGacPath (string fullName)
{
string[] parts = fullName.Split (',');
if (parts.Length != 4) return null;
string name = parts[0].Trim ();
int i = parts[1].IndexOf ('=');
string version = i != -1 ? parts[1].Substring (i+1).Trim () : parts[1].Trim ();
i = parts[2].IndexOf ('=');
string culture = i != -1 ? parts[2].Substring (i+1).Trim () : parts[2].Trim ();
if (culture == "neutral") culture = "";
i = parts[3].IndexOf ('=');
string token = i != -1 ? parts[3].Substring (i+1).Trim () : parts[3].Trim ();
string versionDirName = version + "_" + culture + "_" + token;
if (Util.IsMono) {
string gacDir = typeof(Uri).Assembly.Location;
gacDir = Path.GetDirectoryName (gacDir);
gacDir = Path.GetDirectoryName (gacDir);
gacDir = Path.GetDirectoryName (gacDir);
string dir = Path.Combine (gacDir, name);
return Path.Combine (dir, versionDirName);
} else {
// .NET 4.0 introduces a new GAC directory structure and location.
// Assembly version directory names are now prefixed with the CLR version
// Since there can be different assembly versions for different target CLR runtimes,
// we now look for the best match, that is, the assembly with the higher CLR version
var currentVersion = new Version (Environment.Version.Major, Environment.Version.Minor);
foreach (var gacDir in GetDotNetGacDirectories ()) {
var asmDir = Path.Combine (gacDir, name);
if (!Directory.Exists (asmDir))
continue;
Version bestVersion = new Version (0, 0);
string bestDir = null;
foreach (var dir in Directory.GetDirectories (asmDir, "v*_" + versionDirName)) {
var dirName = Path.GetFileName (dir);
i = dirName.IndexOf ('_');
Version av;
if (Version.TryParse (dirName.Substring (1, i - 1), out av)) {
if (av == currentVersion)
return dir;
else if (av < currentVersion && av > bestVersion) {
bestDir = dir;
bestVersion = av;
}
}
}
if (bestDir != null)
return bestDir;
}
// Look in the old GAC. There are no CLR prefixes here
foreach (var gacDir in GetLegacyDotNetGacDirectories ()) {
var asmDir = Path.Combine (gacDir, name);
asmDir = Path.Combine (asmDir, versionDirName);
if (Directory.Exists (asmDir))
return asmDir;
}
return null;
}
}
static IEnumerable<string> GetLegacyDotNetGacDirectories ()
{
var winDir = Path.GetFullPath (Environment.SystemDirectory + "\\..");
string gacDir = winDir + "\\assembly\\GAC";
if (Directory.Exists (gacDir))
yield return gacDir;
if (Directory.Exists (gacDir + "_32"))
yield return gacDir + "_32";
if (Directory.Exists (gacDir + "_64"))
yield return gacDir + "_64";
if (Directory.Exists (gacDir + "_MSIL"))
yield return gacDir + "_MSIL";
}
static IEnumerable<string> GetDotNetGacDirectories ()
{
var winDir = Path.GetFullPath (Environment.SystemDirectory + "\\..");
string gacDir = winDir + "\\Microsoft.NET\\assembly\\GAC";
if (Directory.Exists (gacDir))
yield return gacDir;
if (Directory.Exists (gacDir + "_32"))
yield return gacDir + "_32";
if (Directory.Exists (gacDir + "_64"))
yield return gacDir + "_64";
if (Directory.Exists (gacDir + "_MSIL"))
yield return gacDir + "_MSIL";
}
internal static bool IsManagedAssembly (string file)
{
try {
AssemblyName.GetAssemblyName (file);
return true;
} catch (BadImageFormatException) {
return false;
}
}
}
}
| |
// 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.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal class OpenSslX509Encoder : IX509Pal
{
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
{
switch (oid.Value)
{
case Oids.RsaRsa:
return BuildRsaPublicKey(encodedKeyValue);
case Oids.Ecc:
return ((OpenSslX509CertificateReader)certificatePal).GetECDsaPublicKey();
}
// NotSupportedException is what desktop and CoreFx-Windows throw in this situation.
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flags)
{
return X500NameEncoder.X500DistinguishedNameDecode(encodedDistinguishedName, true, flags);
}
public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag)
{
throw new NotImplementedException();
}
public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine)
{
throw new NotImplementedException();
}
public X509ContentType GetCertContentType(byte[] rawData)
{
{
ICertificatePal certPal;
if (CertificatePal.TryReadX509Der(rawData, out certPal) ||
CertificatePal.TryReadX509Pem(rawData, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
}
if (PkcsFormatReader.IsPkcs7(rawData))
{
return X509ContentType.Pkcs7;
}
{
OpenSslPkcs12Reader pfx;
if (OpenSslPkcs12Reader.TryRead(rawData, out pfx))
{
pfx.Dispose();
return X509ContentType.Pkcs12;
}
}
// Unsupported format.
// Windows throws new CryptographicException(CRYPT_E_NO_MATCH)
throw new CryptographicException();
}
public X509ContentType GetCertContentType(string fileName)
{
// If we can't open the file, fail right away.
using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(fileName, "rb"))
{
Interop.Crypto.CheckValidOpenSslHandle(fileBio);
int bioPosition = Interop.Crypto.BioTell(fileBio);
Debug.Assert(bioPosition >= 0);
// X509ContentType.Cert
{
ICertificatePal certPal;
if (CertificatePal.TryReadX509Der(fileBio, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
CertificatePal.RewindBio(fileBio, bioPosition);
if (CertificatePal.TryReadX509Pem(fileBio, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
// X509ContentType.Pkcs7
{
if (PkcsFormatReader.IsPkcs7Der(fileBio))
{
return X509ContentType.Pkcs7;
}
CertificatePal.RewindBio(fileBio, bioPosition);
if (PkcsFormatReader.IsPkcs7Pem(fileBio))
{
return X509ContentType.Pkcs7;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
// X509ContentType.Pkcs12 (aka PFX)
{
OpenSslPkcs12Reader pkcs12Reader;
if (OpenSslPkcs12Reader.TryRead(fileBio, out pkcs12Reader))
{
pkcs12Reader.Dispose();
return X509ContentType.Pkcs12;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
}
// Unsupported format.
// Windows throws new CryptographicException(CRYPT_E_NO_MATCH)
throw new CryptographicException();
}
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
// The numeric values of X509KeyUsageFlags mean that if we interpret it as a little-endian
// ushort it will line up with the flags in the spec.
ushort ushortValue = unchecked((ushort)(int)keyUsages);
byte[] data = BitConverter.GetBytes(ushortValue);
// RFC 3280 section 4.2.1.3 (https://tools.ietf.org/html/rfc3280#section-4.2.1.3) defines
// digitalSignature (0) through decipherOnly (8), making 9 named bits.
const int namedBitsCount = 9;
// The expected output of this method isn't the SEQUENCE value, but just the payload bytes.
byte[][] segments = DerEncoder.SegmentedEncodeNamedBitList(data, namedBitsCount);
Debug.Assert(segments.Length == 3);
return ConcatenateArrays(segments);
}
public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
using (SafeAsn1BitStringHandle bitString = Interop.Crypto.DecodeAsn1BitString(encoded, encoded.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(bitString);
byte[] decoded = Interop.Crypto.GetAsn1StringBytes(bitString.DangerousGetHandle());
// Only 9 bits are defined.
if (decoded.Length > 2)
{
throw new CryptographicException();
}
// DER encodings of BIT_STRING values number the bits as
// 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding.
//
// So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit
// is set in this byte stream.
//
// BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which
// is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore
// 0x02 (length remaining) 0x01 (1 bit padding) 0x22.
//
// OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up
// exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02)
//
// Once the decipherOnly (8) bit is added to the mix, the values become:
// 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding)
// { 0x03 0x07 0x22 0x80 }
// And OpenSSL returns new byte[] { 0x22 0x80 }
//
// The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian
// representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively
// ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all
// line up with the existing X509KeyUsageFlags.
int value = 0;
if (decoded.Length > 0)
{
value = decoded[0];
}
if (decoded.Length > 1)
{
value |= decoded[1] << 8;
}
keyUsages = (X509KeyUsageFlags)value;
}
}
public bool SupportsLegacyBasicConstraintsExtension
{
get { return false; }
}
public byte[] EncodeX509BasicConstraints2Extension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
//BasicConstraintsSyntax::= SEQUENCE {
// cA BOOLEAN DEFAULT FALSE,
// pathLenConstraint INTEGER(0..MAX) OPTIONAL,
// ... }
List<byte[][]> segments = new List<byte[][]>(2);
if (certificateAuthority)
{
segments.Add(DerEncoder.SegmentedEncodeBoolean(true));
}
if (hasPathLengthConstraint)
{
byte[] pathLengthBytes = BitConverter.GetBytes(pathLengthConstraint);
// Little-Endian => Big-Endian
Array.Reverse(pathLengthBytes);
segments.Add(DerEncoder.SegmentedEncodeUnsignedInteger(pathLengthBytes));
}
return DerEncoder.ConstructSequence(segments);
}
public void DecodeX509BasicConstraintsExtension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
// No RFC nor ITU document describes the layout of the 2.5.29.10 structure,
// and OpenSSL doesn't have a decoder for it, either.
//
// Since it was never published as a standard (2.5.29.19 replaced it before publication)
// there shouldn't be too many people upset that we can't decode it for them on Unix.
throw new PlatformNotSupportedException(SR.NotSupported_LegacyBasicConstraints);
}
public void DecodeX509BasicConstraints2Extension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
if (!Interop.Crypto.DecodeX509BasicConstraints2Extension(
encoded,
encoded.Length,
out certificateAuthority,
out hasPathLengthConstraint,
out pathLengthConstraint))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
//extKeyUsage EXTENSION ::= {
// SYNTAX SEQUENCE SIZE(1..MAX) OF KeyPurposeId
// IDENTIFIED BY id - ce - extKeyUsage }
//
//KeyPurposeId::= OBJECT IDENTIFIER
List<byte[][]> segments = new List<byte[][]>(usages.Count);
foreach (Oid usage in usages)
{
segments.Add(DerEncoder.SegmentedEncodeOid(usage));
}
return DerEncoder.ConstructSequence(segments);
}
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection oids = new OidCollection();
using (SafeEkuExtensionHandle eku = Interop.Crypto.DecodeExtendedKeyUsage(encoded, encoded.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(eku);
int count = Interop.Crypto.GetX509EkuFieldCount(eku);
for (int i = 0; i < count; i++)
{
IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i);
if (oidPtr == IntPtr.Zero)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
string oidValue = Interop.Crypto.GetOidValue(oidPtr);
oids.Add(new Oid(oidValue));
}
}
usages = oids;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
//subjectKeyIdentifier EXTENSION ::= {
// SYNTAX SubjectKeyIdentifier
// IDENTIFIED BY id - ce - subjectKeyIdentifier }
//
//SubjectKeyIdentifier::= KeyIdentifier
//
//KeyIdentifier ::= OCTET STRING
byte[][] segments = DerEncoder.SegmentedEncodeOctetString(subjectKeyIdentifier);
// The extension is not a sequence, just the octet string
return ConcatenateArrays(segments);
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded);
}
internal static byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded)
{
DerSequenceReader reader = DerSequenceReader.CreateForPayload(encoded);
return reader.ReadOctetString();
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
// The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
// of the DER structural bytes.
//SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier{ { SupportedAlgorithms} },
// subjectPublicKey BIT STRING,
// ... }
//
//AlgorithmIdentifier{ ALGORITHM: SupportedAlgorithms} ::= SEQUENCE {
// algorithm ALGORITHM.&id({ SupportedAlgorithms}),
// parameters ALGORITHM.&Type({ SupportedAlgorithms}
// { @algorithm}) OPTIONAL,
// ... }
//
//ALGORITHM::= CLASS {
// &Type OPTIONAL,
// &id OBJECT IDENTIFIER UNIQUE }
//WITH SYNTAX {
// [&Type]
//IDENTIFIED BY &id }
// key.EncodedKeyValue corresponds to SubjectPublicKeyInfo.subjectPublicKey, except it
// has had the BIT STRING envelope removed.
//
// key.EncodedParameters corresponds to AlgorithmIdentifier.Parameters precisely
// (DER NULL for RSA, DER Constructed SEQUENCE for DSA)
byte[] empty = Array.Empty<byte>();
byte[][] algorithmOid = DerEncoder.SegmentedEncodeOid(key.Oid);
// Because ConstructSegmentedSequence doesn't look to see that it really is tag+length+value (but does check
// that the array has length 3), just hide the joined TLV triplet in the last element.
byte[][] segmentedParameters = { empty, empty, key.EncodedParameters.RawData };
byte[][] algorithmIdentifier = DerEncoder.ConstructSegmentedSequence(algorithmOid, segmentedParameters);
byte[][] subjectPublicKey = DerEncoder.SegmentedEncodeBitString(key.EncodedKeyValue.RawData);
using (SHA1 hash = SHA1.Create())
{
return hash.ComputeHash(
DerEncoder.ConstructSequence(
algorithmIdentifier,
subjectPublicKey));
}
}
private static RSA BuildRsaPublicKey(byte[] encodedData)
{
using (SafeRsaHandle rsaHandle = Interop.Crypto.DecodeRsaPublicKey(encodedData, encodedData.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(rsaHandle);
RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(rsaHandle, false);
RSA rsa = new RSAOpenSsl();
rsa.ImportParameters(rsaParameters);
return rsa;
}
}
private static byte[] ConcatenateArrays(byte[][] segments)
{
int length = 0;
foreach (byte[] segment in segments)
{
length += segment.Length;
}
byte[] concatenated = new byte[length];
int offset = 0;
foreach (byte[] segment in segments)
{
Buffer.BlockCopy(segment, 0, concatenated, offset, segment.Length);
offset += segment.Length;
}
return concatenated;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/rpc/status.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Rpc {
/// <summary>Holder for reflection information generated from google/rpc/status.proto</summary>
public static partial class StatusReflection {
#region Descriptor
/// <summary>File descriptor for google/rpc/status.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StatusReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chdnb29nbGUvcnBjL3N0YXR1cy5wcm90bxIKZ29vZ2xlLnJwYxoZZ29vZ2xl",
"L3Byb3RvYnVmL2FueS5wcm90byJOCgZTdGF0dXMSDAoEY29kZRgBIAEoBRIP",
"CgdtZXNzYWdlGAIgASgJEiUKB2RldGFpbHMYAyADKAsyFC5nb29nbGUucHJv",
"dG9idWYuQW55Ql4KDmNvbS5nb29nbGUucnBjQgtTdGF0dXNQcm90b1ABWjdn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3JwYy9zdGF0",
"dXM7c3RhdHVzogIDUlBDYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Rpc.Status), global::Google.Rpc.Status.Parser, new[]{ "Code", "Message", "Details" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different
/// programming environments, including REST APIs and RPC APIs. It is used by
/// [gRPC](https://github.com/grpc). The error model is designed to be:
///
/// - Simple to use and understand for most users
/// - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message,
/// and error details. The error code should be an enum value of
/// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The
/// error message should be a developer-facing English message that helps
/// developers *understand* and *resolve* the error. If a localized user-facing
/// error message is needed, put the localized message in the error details or
/// localize it in the client. The optional error details may contain arbitrary
/// information about the error. There is a predefined set of error detail types
/// in the package `google.rpc` which can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it
/// is not necessarily the actual wire format. When the `Status` message is
/// exposed in different client libraries and different wire protocols, it can be
/// mapped differently. For example, it will likely be mapped to some exceptions
/// in Java, but more likely mapped to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of
/// environments, either with or without APIs, to provide a
/// consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client,
/// it may embed the `Status` in the normal response to indicate the partial
/// errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may
/// have a `Status` message for error reporting purpose.
///
/// - Batch operations. If a client uses batch request and batch response, the
/// `Status` message should be used directly inside batch response, one for
/// each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation
/// results in its response, the status of those operations should be
/// represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could
/// be used directly after any stripping needed for security/privacy reasons.
/// </summary>
public sealed partial class Status : pb::IMessage<Status> {
private static readonly pb::MessageParser<Status> _parser = new pb::MessageParser<Status>(() => new Status());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Status> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Rpc.StatusReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Status() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Status(Status other) : this() {
code_ = other.code_;
message_ = other.message_;
details_ = other.details_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Status Clone() {
return new Status(this);
}
/// <summary>Field number for the "code" field.</summary>
public const int CodeFieldNumber = 1;
private int code_;
/// <summary>
/// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Code {
get { return code_; }
set {
code_ = value;
}
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 2;
private string message_ = "";
/// <summary>
/// A developer-facing error message, which should be in English. Any
/// user-facing error message should be localized and sent in the
/// [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "details" field.</summary>
public const int DetailsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Any> _repeated_details_codec
= pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Any.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> details_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any>();
/// <summary>
/// A list of messages that carry the error details. There will be a
/// common set of message types for APIs to use.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> Details {
get { return details_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Status);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Status other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Code != other.Code) return false;
if (Message != other.Message) return false;
if(!details_.Equals(other.details_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Code != 0) hash ^= Code.GetHashCode();
if (Message.Length != 0) hash ^= Message.GetHashCode();
hash ^= details_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Code != 0) {
output.WriteRawTag(8);
output.WriteInt32(Code);
}
if (Message.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Message);
}
details_.WriteTo(output, _repeated_details_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Code != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Code);
}
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
size += details_.CalculateSize(_repeated_details_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Status other) {
if (other == null) {
return;
}
if (other.Code != 0) {
Code = other.Code;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
details_.Add(other.details_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Code = input.ReadInt32();
break;
}
case 18: {
Message = input.ReadString();
break;
}
case 26: {
details_.AddEntriesFrom(input, _repeated_details_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
namespace OmniSharp
{
public class SnippetGenerator
{
private int _counter = 1;
private StringBuilder _sb;
private SymbolDisplayFormat _format;
public bool IncludeMarkers { get; set; }
public bool IncludeOptionalParameters { get; set; }
public string Generate(ISymbol symbol)
{
_sb = new StringBuilder();
_format = SymbolDisplayFormat.MinimallyQualifiedFormat;
_format = _format.WithMemberOptions(_format.MemberOptions
^ SymbolDisplayMemberOptions.IncludeContainingType
^ SymbolDisplayMemberOptions.IncludeType);
if (IsConstructor(symbol))
{
// only the containing type contains the type parameters
var parts = symbol.ContainingType.ToDisplayParts(_format);
RenderDisplayParts(symbol, parts);
parts = symbol.ToDisplayParts(_format);
RenderParameters(symbol as IMethodSymbol);
}
else
{
var symbolKind = symbol.Kind;
if (symbol.Kind == SymbolKind.Method)
{
RenderMethodSymbol(symbol as IMethodSymbol);
}
else if (symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Local ||
symbol.Kind == SymbolKind.Parameter)
{
_sb.Append(symbol.Name);
}
else
{
var parts = symbol.ToDisplayParts(_format);
RenderDisplayParts(symbol, parts);
}
}
if (IncludeMarkers)
{
_sb.Append("$0");
}
return _sb.ToString();
}
private void RenderMethodSymbol(IMethodSymbol methodSymbol)
{
var nonInferredTypeArguments = NonInferredTypeArguments(methodSymbol);
_sb.Append(methodSymbol.Name);
if (nonInferredTypeArguments.Any())
{
_sb.Append("<");
var last = nonInferredTypeArguments.Last();
foreach (var arg in nonInferredTypeArguments)
{
RenderSnippetStartMarker();
_sb.Append(arg);
RenderSnippetEndMarker();
if (arg != last)
{
_sb.Append(", ");
}
}
_sb.Append(">");
}
RenderParameters(methodSymbol);
if (methodSymbol.ReturnsVoid && IncludeMarkers)
{
_sb.Append(";");
}
}
private void RenderParameters(IMethodSymbol methodSymbol)
{
IEnumerable<IParameterSymbol> parameters = methodSymbol.Parameters;
if (!IncludeOptionalParameters)
{
parameters = parameters.Where(p => !p.IsOptional);
}
_sb.Append("(");
if (parameters.Any())
{
var last = parameters.Last();
foreach (var parameter in parameters)
{
RenderSnippetStartMarker();
_sb.Append(parameter.ToDisplayString(_format));
RenderSnippetEndMarker();
if (parameter != last)
{
_sb.Append(", ");
}
}
}
_sb.Append(")");
}
private IEnumerable<ISymbol> NonInferredTypeArguments(IMethodSymbol methodSymbol)
{
var typeParameters = methodSymbol.TypeParameters;
var typeArguments = methodSymbol.TypeArguments;
var nonInferredTypeArguments = new List<ISymbol>();
for (int i = 0; i < typeParameters.Count(); i++)
{
var arg = typeArguments[i];
var param = typeParameters[i];
if (arg == param)
{
// this type parameter has not been resolved
nonInferredTypeArguments.Add(arg);
}
}
// We might have more inferred types once the method parameters have
// been supplied. Remove these.
var parameterTypes = ParameterTypes(methodSymbol);
return nonInferredTypeArguments.Except(parameterTypes);
}
private IEnumerable<ISymbol> ParameterTypes(IMethodSymbol methodSymbol)
{
foreach (var parameter in methodSymbol.Parameters)
{
var types = ExplodeTypes(parameter.Type);
foreach (var type in types)
{
yield return type;
}
}
}
private IEnumerable<ISymbol> ExplodeTypes(ISymbol symbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol != null)
{
var typeParams = typeSymbol.TypeArguments;
foreach (var typeParam in typeParams)
{
var explodedTypes = ExplodeTypes(typeParam);
foreach (var type in explodedTypes)
{
yield return type;
}
}
}
yield return symbol;
}
private bool IsConstructor(ISymbol symbol)
{
var methodSymbol = symbol as IMethodSymbol;
return methodSymbol != null && methodSymbol.MethodKind == MethodKind.Constructor;
}
private void RenderSnippetStartMarker()
{
if (IncludeMarkers)
{
_sb.Append("${");
_sb.Append(_counter++);
_sb.Append(":");
}
}
private void RenderSnippetEndMarker()
{
if (IncludeMarkers)
{
_sb.Append("}");
}
}
private void RenderDisplayParts(ISymbol symbol, IEnumerable<SymbolDisplayPart> parts)
{
foreach (var part in parts)
{
if (part.Kind == SymbolDisplayPartKind.TypeParameterName)
{
RenderSnippetStartMarker();
_sb.Append(part.ToString());
RenderSnippetEndMarker();
}
else
{
_sb.Append(part.ToString());
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CsQueryControls.Demo.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
namespace PlayFab.Json.Utilities
{
internal enum ParserTimeZone
{
Unspecified,
Utc,
LocalWestOfUtc,
LocalEastOfUtc
}
internal struct DateTimeParser
{
static DateTimeParser()
{
Power10 = new[] { -1, 10, 100, 1000, 10000, 100000, 1000000 };
Lzyyyy = "yyyy".Length;
Lzyyyy_ = "yyyy-".Length;
Lzyyyy_MM = "yyyy-MM".Length;
Lzyyyy_MM_ = "yyyy-MM-".Length;
Lzyyyy_MM_dd = "yyyy-MM-dd".Length;
Lzyyyy_MM_ddT = "yyyy-MM-ddT".Length;
LzHH = "HH".Length;
LzHH_ = "HH:".Length;
LzHH_mm = "HH:mm".Length;
LzHH_mm_ = "HH:mm:".Length;
LzHH_mm_ss = "HH:mm:ss".Length;
Lz_ = "-".Length;
Lz_zz = "-zz".Length;
Lz_zz_ = "-zz:".Length;
Lz_zz_zz = "-zz:zz".Length;
}
public int Year;
public int Month;
public int Day;
public int Hour;
public int Minute;
public int Second;
public int Fraction;
public int ZoneHour;
public int ZoneMinute;
public ParserTimeZone Zone;
private string _text;
private int _length;
private static readonly int[] Power10;
private static readonly int Lzyyyy;
private static readonly int Lzyyyy_;
private static readonly int Lzyyyy_MM;
private static readonly int Lzyyyy_MM_;
private static readonly int Lzyyyy_MM_dd;
private static readonly int Lzyyyy_MM_ddT;
private static readonly int LzHH;
private static readonly int LzHH_;
private static readonly int LzHH_mm;
private static readonly int LzHH_mm_;
private static readonly int LzHH_mm_ss;
private static readonly int Lz_;
private static readonly int Lz_zz;
private static readonly int Lz_zz_;
private static readonly int Lz_zz_zz;
private const short MaxFractionDigits = 7;
public bool Parse(string text)
{
_text = text;
_length = text.Length;
if (ParseDate(0) && ParseChar(Lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(Lzyyyy_MM_ddT))
return true;
return false;
}
private bool ParseDate(int start)
{
return (Parse4Digit(start, out Year)
&& 1 <= Year
&& ParseChar(start + Lzyyyy, '-')
&& Parse2Digit(start + Lzyyyy_, out Month)
&& 1 <= Month
&& Month <= 12
&& ParseChar(start + Lzyyyy_MM, '-')
&& Parse2Digit(start + Lzyyyy_MM_, out Day)
&& 1 <= Day
&& Day <= DateTime.DaysInMonth(Year, Month));
}
private bool ParseTimeAndZoneAndWhitespace(int start)
{
return (ParseTime(ref start) && ParseZone(start));
}
private bool ParseTime(ref int start)
{
if (!(Parse2Digit(start, out Hour)
&& Hour < 24
&& ParseChar(start + LzHH, ':')
&& Parse2Digit(start + LzHH_, out Minute)
&& Minute < 60
&& ParseChar(start + LzHH_mm, ':')
&& Parse2Digit(start + LzHH_mm_, out Second)
&& Second < 60))
{
return false;
}
start += LzHH_mm_ss;
if (ParseChar(start, '.'))
{
Fraction = 0;
int numberOfDigits = 0;
while (++start < _length && numberOfDigits < MaxFractionDigits)
{
int digit = _text[start] - '0';
if (digit < 0 || digit > 9)
break;
Fraction = (Fraction*10) + digit;
numberOfDigits++;
}
if (numberOfDigits < MaxFractionDigits)
{
if (numberOfDigits == 0)
return false;
Fraction *= Power10[MaxFractionDigits - numberOfDigits];
}
}
return true;
}
private bool ParseZone(int start)
{
if (start < _length)
{
char ch = _text[start];
if (ch == 'Z' || ch == 'z')
{
Zone = ParserTimeZone.Utc;
start++;
}
else
{
if (start + 2 < _length
&& Parse2Digit(start + Lz_, out ZoneHour)
&& ZoneHour <= 99)
{
switch (ch)
{
case '-':
Zone = ParserTimeZone.LocalWestOfUtc;
start += Lz_zz;
break;
case '+':
Zone = ParserTimeZone.LocalEastOfUtc;
start += Lz_zz;
break;
}
}
if (start < _length)
{
if (ParseChar(start, ':'))
{
start += 1;
if (start + 1 < _length
&& Parse2Digit(start, out ZoneMinute)
&& ZoneMinute <= 99)
{
start += 2;
}
}
else
{
if (start + 1 < _length
&& Parse2Digit(start, out ZoneMinute)
&& ZoneMinute <= 99)
{
start += 2;
}
}
}
}
}
return (start == _length);
}
private bool Parse4Digit(int start, out int num)
{
if (start + 3 < _length)
{
int digit1 = _text[start] - '0';
int digit2 = _text[start + 1] - '0';
int digit3 = _text[start + 2] - '0';
int digit4 = _text[start + 3] - '0';
if (0 <= digit1 && digit1 < 10
&& 0 <= digit2 && digit2 < 10
&& 0 <= digit3 && digit3 < 10
&& 0 <= digit4 && digit4 < 10)
{
num = (((((digit1*10) + digit2)*10) + digit3)*10) + digit4;
return true;
}
}
num = 0;
return false;
}
private bool Parse2Digit(int start, out int num)
{
if (start + 1 < _length)
{
int digit1 = _text[start] - '0';
int digit2 = _text[start + 1] - '0';
if (0 <= digit1 && digit1 < 10
&& 0 <= digit2 && digit2 < 10)
{
num = (digit1*10) + digit2;
return true;
}
}
num = 0;
return false;
}
private bool ParseChar(int start, char ch)
{
return (start < _length && _text[start] == ch);
}
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer
{
public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseCollectionInitializerDiagnosticAnalyzer(),
new CSharpUseCollectionInitializerCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestOnVariableDeclarator()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess1_NotInCSharp5()
{
await TestMissingAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexIndexAccess1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
a.b.c = [||]new List<int>();
a.b.c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
a.b.c = new List<int>
{
[1] = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess2()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c[2] = """";
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2,
[2] = """"
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess3()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c[2] = """";
c[3, 4] = 5;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2,
[2] = """",
[3, 4] = 5
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexFollowedByInvocation()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c.Add(0);
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2
};
c.Add(0);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestInvocationFollowedByIndex()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(0);
c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
0
};
c[1] = 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestWithInterimStatement()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
c.Add(2);
throw new Exception();
c.Add(3);
c.Add(4);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1,
2
};
throw new Exception();
c.Add(3);
c.Add(4);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingBeforeCSharp3()
{
await TestMissingAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnNonIEnumerable()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new C();
c.Add(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnNonIEnumerableEvenWithAdd()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new C();
c.Add(1);
}
public void Add(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestWithCreationArguments()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>(1);
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>(1)
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestOnAssignmentExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int> c = null;
c = [||]new List<int>();
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int> c = null;
c = new List<int>
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnRefAdd()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(ref i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexInitializer()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = [||]new List<int>();
array[0].Add(1);
array[0].Add(2);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = new List<int>
{
1,
2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestNotOnNamedArg()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(arg: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingWithExistingInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>() { 1 };
c.Add(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument1()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = {|FixAllInDocument:new|} List<int>();
array[0].Add(1);
array[0].Add(2);
array[1] = new List<int>();
array[1].Add(3);
array[1].Add(4);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = new List<int>
{
1,
2
};
array[1] = new List<int>
{
3,
4
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument2()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = {|FixAllInDocument:new|} List<int>(() => {
var list2 = new List<int>();
list2.Add(2);
});
list1.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = new List<int>(() => {
var list2 = new List<int>
{
2
};
})
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = {|FixAllInDocument:new|} List<int>();
list1.Add(() => {
var list2 = new List<int>();
list2.Add(2);
});
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = new List<int>
{
() => {
var list2 = new List<int>
{
2
};
}
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1); // Foo
c.Add(2); // Bar
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1, // Foo
2 // Bar
};
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexInitializer2()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new [||]Dictionary<int, string>();
c.Add(1, ""x"");
c.Add(2, ""y"");
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new Dictionary<int, string>
{
{
1,
""x""
},
{
2,
""y""
}
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")]
public async Task TestIncorrectAddName()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
public class Foo
{
public static void Bar()
{
string item = null;
var items = new List<string>();
var values = new [||]List<string>(); // Collection initialization can be simplified
values.Add(item);
values.AddRange(items);
}
}",
@"using System.Collections.Generic;
public class Foo
{
public static void Bar()
{
string item = null;
var items = new List<string>();
var values = new List<string>
{
item
}; // Collection initialization can be simplified
values.AddRange(items);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")]
public async Task TestNestedCollectionInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" };
var myStringList = myStringArray?.ToList() ?? new [||]List<string>();
myStringList.Add(""Done"");
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")]
public async Task TestMissingWhenReferencedInInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>();
items[0] = items[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")]
public async Task TestWhenReferencedInInitializer_LocalVar()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>();
items[0] = 1;
items[1] = items[0];
}
}",
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>
{
[0] = 1
};
items[1] = items[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")]
public async Task TestWhenReferencedInInitializer_LocalVar2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var t = [||]new List<int>(new int[] { 1, 2, 3 });
t.Add(t.Min() - 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")]
public async Task TestWhenReferencedInInitializer_Assignment()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
class C
{
static void M()
{
List<object> items = null;
items = new [||]List<object>();
items[0] = 1;
items[1] = items[0];
}
}",
@"
using System.Collections.Generic;
class C
{
static void M()
{
List<object> items = null;
items = new [||]List<object>
{
[0] = 1
};
items[1] = items[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")]
public async Task TestWhenReferencedInInitializer_Assignment2()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
List<int> t = null;
t = [||]new List<int>(new int[] { 1, 2, 3 });
t.Add(t.Min() - 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")]
public async Task TestFieldReference()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
private List<int> myField;
void M()
{
myField = [||]new List<int>();
myField.Add(this.myField.Count);
}
}");
}
[WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingForDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Dynamic;
class C
{
void Foo()
{
dynamic body = [||]new ExpandoObject();
body[0] = new ExpandoObject();
}
}");
}
[WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingAcrossPreprocessorDirective()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
var items = new [||]List<object>();
#if true
items.Add(1);
#endif
}
}");
}
[WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestAvailableInsidePreprocessorDirective()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
#if true
var items = new [||]List<object>();
items.Add(1);
#endif
}
}",
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
#if true
var items = new List<object>
{
1
};
#endif
}
}", ignoreTrivia: false);
}
[WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestObjectInitializerAssignmentAmbiguity()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
int lastItem;
var list = [||]new List<int>();
list.Add(lastItem = 5);
}
}",
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
int lastItem;
var list = new List<int>
{
(lastItem = 5)
};
}
}");
}
[WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestObjectInitializerCompoundAssignment()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
int lastItem = 0;
var list = [||]new List<int>();
list.Add(lastItem += 5);
}
}",
@"
using System.Collections.Generic;
public class Foo
{
public void M()
{
int lastItem = 0;
var list = new List<int>
{
(lastItem += 5)
};
}
}");
}
}
}
| |
/*
* 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:
*
* 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.
*
* 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 System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A virtual network
/// First published in XenServer 4.0.
/// </summary>
public partial class Network : XenObject<Network>
{
#region Constructors
public Network()
{
}
public Network(string uuid,
string name_label,
string name_description,
List<network_operations> allowed_operations,
Dictionary<string, network_operations> current_operations,
List<XenRef<VIF>> VIFs,
List<XenRef<PIF>> PIFs,
long MTU,
Dictionary<string, string> other_config,
string bridge,
bool managed,
Dictionary<string, XenRef<Blob>> blobs,
string[] tags,
network_default_locking_mode default_locking_mode,
Dictionary<XenRef<VIF>, string> assigned_ips,
List<network_purpose> purpose)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VIFs = VIFs;
this.PIFs = PIFs;
this.MTU = MTU;
this.other_config = other_config;
this.bridge = bridge;
this.managed = managed;
this.blobs = blobs;
this.tags = tags;
this.default_locking_mode = default_locking_mode;
this.assigned_ips = assigned_ips;
this.purpose = purpose;
}
/// <summary>
/// Creates a new Network from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Network(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Network from a Proxy_Network.
/// </summary>
/// <param name="proxy"></param>
public Network(Proxy_Network proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Network.
/// </summary>
public override void UpdateFrom(Network update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VIFs = update.VIFs;
PIFs = update.PIFs;
MTU = update.MTU;
other_config = update.other_config;
bridge = update.bridge;
managed = update.managed;
blobs = update.blobs;
tags = update.tags;
default_locking_mode = update.default_locking_mode;
assigned_ips = update.assigned_ips;
purpose = update.purpose;
}
internal void UpdateFrom(Proxy_Network proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<network_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_network_operations(proxy.current_operations);
VIFs = proxy.VIFs == null ? null : XenRef<VIF>.Create(proxy.VIFs);
PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs);
MTU = proxy.MTU == null ? 0 : long.Parse(proxy.MTU);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
bridge = proxy.bridge == null ? null : proxy.bridge;
managed = (bool)proxy.managed;
blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs);
tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags;
default_locking_mode = proxy.default_locking_mode == null ? (network_default_locking_mode) 0 : (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)proxy.default_locking_mode);
assigned_ips = proxy.assigned_ips == null ? null : Maps.convert_from_proxy_XenRefVIF_string(proxy.assigned_ips);
purpose = proxy.purpose == null ? null : Helper.StringArrayToEnumList<network_purpose>(proxy.purpose);
}
public Proxy_Network ToProxy()
{
Proxy_Network result_ = new Proxy_Network();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations);
result_.current_operations = Maps.convert_to_proxy_string_network_operations(current_operations);
result_.VIFs = VIFs == null ? new string[] {} : Helper.RefListToStringArray(VIFs);
result_.PIFs = PIFs == null ? new string[] {} : Helper.RefListToStringArray(PIFs);
result_.MTU = MTU.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.bridge = bridge ?? "";
result_.managed = managed;
result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs);
result_.tags = tags;
result_.default_locking_mode = network_default_locking_mode_helper.ToString(default_locking_mode);
result_.assigned_ips = Maps.convert_to_proxy_XenRefVIF_string(assigned_ips);
result_.purpose = purpose == null ? new string[] {} : Helper.ObjectListToStringArray(purpose);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Network
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<network_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("VIFs"))
VIFs = Marshalling.ParseSetRef<VIF>(table, "VIFs");
if (table.ContainsKey("PIFs"))
PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs");
if (table.ContainsKey("MTU"))
MTU = Marshalling.ParseLong(table, "MTU");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("bridge"))
bridge = Marshalling.ParseString(table, "bridge");
if (table.ContainsKey("managed"))
managed = Marshalling.ParseBool(table, "managed");
if (table.ContainsKey("blobs"))
blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs"));
if (table.ContainsKey("tags"))
tags = Marshalling.ParseStringArray(table, "tags");
if (table.ContainsKey("default_locking_mode"))
default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode"));
if (table.ContainsKey("assigned_ips"))
assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips"));
if (table.ContainsKey("purpose"))
purpose = Helper.StringArrayToEnumList<network_purpose>(Marshalling.ParseStringArray(table, "purpose"));
}
public bool DeepEquals(Network other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VIFs, other._VIFs) &&
Helper.AreEqual2(this._PIFs, other._PIFs) &&
Helper.AreEqual2(this._MTU, other._MTU) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._bridge, other._bridge) &&
Helper.AreEqual2(this._managed, other._managed) &&
Helper.AreEqual2(this._blobs, other._blobs) &&
Helper.AreEqual2(this._tags, other._tags) &&
Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) &&
Helper.AreEqual2(this._assigned_ips, other._assigned_ips) &&
Helper.AreEqual2(this._purpose, other._purpose);
}
internal static List<Network> ProxyArrayToObjectList(Proxy_Network[] input)
{
var result = new List<Network>();
foreach (var item in input)
result.Add(new Network(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Network server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Network.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Network.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_MTU, server._MTU))
{
Network.set_MTU(session, opaqueRef, _MTU);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Network.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_tags, server._tags))
{
Network.set_tags(session, opaqueRef, _tags);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Network get_record(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_record(session.opaque_ref, _network);
else
return new Network(session.XmlRpcProxy.network_get_record(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get a reference to the network instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Network> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Network>.Create(session.XmlRpcProxy.network_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Network> create(Session session, Network _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create(session.opaque_ref, _record);
else
return XenRef<Network>.Create(session.XmlRpcProxy.network_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, Network _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static void destroy(Session session, string _network)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_destroy(session.opaque_ref, _network);
else
session.XmlRpcProxy.network_destroy(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static XenRef<Task> async_destroy(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_destroy(session.opaque_ref, _network);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_destroy(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get all the network instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Network>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Network>.Create(session.XmlRpcProxy.network_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_uuid(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_uuid(session.opaque_ref, _network);
else
return session.XmlRpcProxy.network_get_uuid(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_label(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_name_label(session.opaque_ref, _network);
else
return session.XmlRpcProxy.network_get_name_label(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_description(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_name_description(session.opaque_ref, _network);
else
return session.XmlRpcProxy.network_get_name_description(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<network_operations> get_allowed_operations(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_allowed_operations(session.opaque_ref, _network);
else
return Helper.StringArrayToEnumList<network_operations>(session.XmlRpcProxy.network_get_allowed_operations(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, network_operations> get_current_operations(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_current_operations(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_network_operations(session.XmlRpcProxy.network_get_current_operations(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the VIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<VIF>> get_VIFs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_vifs(session.opaque_ref, _network);
else
return XenRef<VIF>.Create(session.XmlRpcProxy.network_get_vifs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the PIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<PIF>> get_PIFs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_pifs(session.opaque_ref, _network);
else
return XenRef<PIF>.Create(session.XmlRpcProxy.network_get_pifs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static long get_MTU(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_mtu(session.opaque_ref, _network);
else
return long.Parse(session.XmlRpcProxy.network_get_mtu(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, string> get_other_config(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_other_config(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.network_get_other_config(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the bridge field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_bridge(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_bridge(session.opaque_ref, _network);
else
return session.XmlRpcProxy.network_get_bridge(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the managed field of the given network.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static bool get_managed(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_managed(session.opaque_ref, _network);
else
return (bool)session.XmlRpcProxy.network_get_managed(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the blobs field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_blobs(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_XenRefBlob(session.XmlRpcProxy.network_get_blobs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string[] get_tags(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_tags(session.opaque_ref, _network);
else
return (string [])session.XmlRpcProxy.network_get_tags(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the default_locking_mode field of the given network.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static network_default_locking_mode get_default_locking_mode(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_default_locking_mode(session.opaque_ref, _network);
else
return (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)session.XmlRpcProxy.network_get_default_locking_mode(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the assigned_ips field of the given network.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<XenRef<VIF>, string> get_assigned_ips(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_assigned_ips(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_XenRefVIF_string(session.XmlRpcProxy.network_get_assigned_ips(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the purpose field of the given network.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<network_purpose> get_purpose(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_purpose(session.opaque_ref, _network);
else
return Helper.StringArrayToEnumList<network_purpose>(session.XmlRpcProxy.network_get_purpose(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _network, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_name_label(session.opaque_ref, _network, _label);
else
session.XmlRpcProxy.network_set_name_label(session.opaque_ref, _network ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _network, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_name_description(session.opaque_ref, _network, _description);
else
session.XmlRpcProxy.network_set_name_description(session.opaque_ref, _network ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_mtu">New value to set</param>
public static void set_MTU(Session session, string _network, long _mtu)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_mtu(session.opaque_ref, _network, _mtu);
else
session.XmlRpcProxy.network_set_mtu(session.opaque_ref, _network ?? "", _mtu.ToString()).parse();
}
/// <summary>
/// Set the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _network, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_other_config(session.opaque_ref, _network, _other_config);
else
session.XmlRpcProxy.network_set_other_config(session.opaque_ref, _network ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _network, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_to_other_config(session.opaque_ref, _network, _key, _value);
else
session.XmlRpcProxy.network_add_to_other_config(session.opaque_ref, _network ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _network, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_from_other_config(session.opaque_ref, _network, _key);
else
session.XmlRpcProxy.network_remove_from_other_config(session.opaque_ref, _network ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_tags">New value to set</param>
public static void set_tags(Session session, string _network, string[] _tags)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_tags(session.opaque_ref, _network, _tags);
else
session.XmlRpcProxy.network_set_tags(session.opaque_ref, _network ?? "", _tags).parse();
}
/// <summary>
/// Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">New value to add</param>
public static void add_tags(Session session, string _network, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_tags(session.opaque_ref, _network, _value);
else
session.XmlRpcProxy.network_add_tags(session.opaque_ref, _network ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">Value to remove</param>
public static void remove_tags(Session session, string _network, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_tags(session.opaque_ref, _network, _value);
else
session.XmlRpcProxy.network_remove_tags(session.opaque_ref, _network ?? "", _value ?? "").parse();
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static void set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_default_locking_mode(session.opaque_ref, _network, _value);
else
session.XmlRpcProxy.network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse();
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static XenRef<Task> async_set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_set_default_locking_mode(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse());
}
/// <summary>
/// Give a network a new purpose (if not present already)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to add</param>
public static void add_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_purpose(session.opaque_ref, _network, _value);
else
session.XmlRpcProxy.network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse();
}
/// <summary>
/// Give a network a new purpose (if not present already)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to add</param>
public static XenRef<Task> async_add_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_add_purpose(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse());
}
/// <summary>
/// Remove a purpose from a network (if present)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to remove</param>
public static void remove_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_purpose(session.opaque_ref, _network, _value);
else
session.XmlRpcProxy.network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse();
}
/// <summary>
/// Remove a purpose from a network (if present)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to remove</param>
public static XenRef<Task> async_remove_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_remove_purpose(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse());
}
/// <summary>
/// Return a list of all the networks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Network>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_all(session.opaque_ref);
else
return XenRef<Network>.Create(session.XmlRpcProxy.network_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the network Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Network>, Network> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_all_records(session.opaque_ref);
else
return XenRef<Network>.Create<Proxy_Network>(session.XmlRpcProxy.network_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<network_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<network_operations> _allowed_operations = new List<network_operations>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, network_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, network_operations> _current_operations = new Dictionary<string, network_operations>() {};
/// <summary>
/// list of connected vifs
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VIF>))]
public virtual List<XenRef<VIF>> VIFs
{
get { return _VIFs; }
set
{
if (!Helper.AreEqual(value, _VIFs))
{
_VIFs = value;
NotifyPropertyChanged("VIFs");
}
}
}
private List<XenRef<VIF>> _VIFs = new List<XenRef<VIF>>() {};
/// <summary>
/// list of connected pifs
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PIF>))]
public virtual List<XenRef<PIF>> PIFs
{
get { return _PIFs; }
set
{
if (!Helper.AreEqual(value, _PIFs))
{
_PIFs = value;
NotifyPropertyChanged("PIFs");
}
}
}
private List<XenRef<PIF>> _PIFs = new List<XenRef<PIF>>() {};
/// <summary>
/// MTU in octets
/// First published in XenServer 5.6.
/// </summary>
public virtual long MTU
{
get { return _MTU; }
set
{
if (!Helper.AreEqual(value, _MTU))
{
_MTU = value;
NotifyPropertyChanged("MTU");
}
}
}
private long _MTU = 1500;
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// name of the bridge corresponding to this network on the local host
/// </summary>
public virtual string bridge
{
get { return _bridge; }
set
{
if (!Helper.AreEqual(value, _bridge))
{
_bridge = value;
NotifyPropertyChanged("bridge");
}
}
}
private string _bridge = "";
/// <summary>
/// true if the bridge is managed by xapi
/// First published in XenServer 7.2.
/// </summary>
public virtual bool managed
{
get { return _managed; }
set
{
if (!Helper.AreEqual(value, _managed))
{
_managed = value;
NotifyPropertyChanged("managed");
}
}
}
private bool _managed = true;
/// <summary>
/// Binary blobs associated with this network
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringXenRefMapConverter<Blob>))]
public virtual Dictionary<string, XenRef<Blob>> blobs
{
get { return _blobs; }
set
{
if (!Helper.AreEqual(value, _blobs))
{
_blobs = value;
NotifyPropertyChanged("blobs");
}
}
}
private Dictionary<string, XenRef<Blob>> _blobs = new Dictionary<string, XenRef<Blob>>() {};
/// <summary>
/// user-specified tags for categorization purposes
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] tags
{
get { return _tags; }
set
{
if (!Helper.AreEqual(value, _tags))
{
_tags = value;
NotifyPropertyChanged("tags");
}
}
}
private string[] _tags = {};
/// <summary>
/// The network will use this value to determine the behaviour of all VIFs where locking_mode = default
/// First published in XenServer 6.1.
/// </summary>
[JsonConverter(typeof(network_default_locking_modeConverter))]
public virtual network_default_locking_mode default_locking_mode
{
get { return _default_locking_mode; }
set
{
if (!Helper.AreEqual(value, _default_locking_mode))
{
_default_locking_mode = value;
NotifyPropertyChanged("default_locking_mode");
}
}
}
private network_default_locking_mode _default_locking_mode = network_default_locking_mode.unlocked;
/// <summary>
/// The IP addresses assigned to VIFs on networks that have active xapi-managed DHCP
/// First published in XenServer 6.5.
/// </summary>
[JsonConverter(typeof(XenRefStringMapConverter<VIF>))]
public virtual Dictionary<XenRef<VIF>, string> assigned_ips
{
get { return _assigned_ips; }
set
{
if (!Helper.AreEqual(value, _assigned_ips))
{
_assigned_ips = value;
NotifyPropertyChanged("assigned_ips");
}
}
}
private Dictionary<XenRef<VIF>, string> _assigned_ips = new Dictionary<XenRef<VIF>, string>() {};
/// <summary>
/// Set of purposes for which the server will use this network
/// First published in XenServer 7.3.
/// </summary>
public virtual List<network_purpose> purpose
{
get { return _purpose; }
set
{
if (!Helper.AreEqual(value, _purpose))
{
_purpose = value;
NotifyPropertyChanged("purpose");
}
}
}
private List<network_purpose> _purpose = new List<network_purpose>() {};
}
}
| |
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 DocuSign.Web.Areas.HelpPage.ModelDescriptions;
using DocuSign.Web.Areas.HelpPage.Models;
namespace DocuSign.Web.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.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace eventsarray.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.
//
// * Neither the name of Jaroslaw Kowalski 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.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Common;
using NLog.Internal;
using NLog.Targets;
using NLog.Targets.Wrappers;
[TestFixture]
public class PostFilteringTargetWrapperTests : NLogTestBase
{
[Test]
public void PostFilteringTargetWrapperUsingDefaultFilterTest()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
// when there is an error, emit everything
new FilteringRule
{
Exists = "level >= LogLevel.Error",
Filter = "true",
},
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
};
wrapper.WriteAsyncLogEvents(events);
// make sure all Info events went through
Assert.AreEqual(3, target.Events.Count);
Assert.AreSame(events[1].LogEvent, target.Events[0]);
Assert.AreSame(events[2].LogEvent, target.Events[1]);
Assert.AreSame(events[5].LogEvent, target.Events[2]);
Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
}
[Test]
public void PostFilteringTargetWrapperUsingDefaultNonFilterTest()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
// when there is an error, emit everything
new FilteringRule("level >= LogLevel.Error", "true"),
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
Assert.IsTrue(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1);
Assert.IsTrue(result.IndexOf("Trace Rule matched: (level >= Warn)") != -1);
Assert.IsTrue(result.IndexOf("Trace Filter to apply: (level >= Debug)") != -1);
Assert.IsTrue(result.IndexOf("Trace After filtering: 6 events.") != -1);
Assert.IsTrue(result.IndexOf("Trace Sending to MyTarget") != -1);
// make sure all Debug,Info,Warn events went through
Assert.AreEqual(6, target.Events.Count);
Assert.AreSame(events[0].LogEvent, target.Events[0]);
Assert.AreSame(events[1].LogEvent, target.Events[1]);
Assert.AreSame(events[2].LogEvent, target.Events[2]);
Assert.AreSame(events[3].LogEvent, target.Events[3]);
Assert.AreSame(events[5].LogEvent, target.Events[4]);
Assert.AreSame(events[6].LogEvent, target.Events[5]);
Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
}
[Test]
public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2()
{
// in this case both rules would match, but first one is picked
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// when there is an error, emit everything
new FilteringRule("level >= LogLevel.Error", "true"),
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
Assert.IsTrue(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1);
Assert.IsTrue(result.IndexOf("Trace Rule matched: (level >= Error)") != -1);
Assert.IsTrue(result.IndexOf("Trace Filter to apply: True") != -1);
Assert.IsTrue(result.IndexOf("Trace After filtering: 7 events.") != -1);
Assert.IsTrue(result.IndexOf("Trace Sending to MyTarget") != -1);
// make sure all events went through
Assert.AreEqual(7, target.Events.Count);
Assert.AreSame(events[0].LogEvent, target.Events[0]);
Assert.AreSame(events[1].LogEvent, target.Events[1]);
Assert.AreSame(events[2].LogEvent, target.Events[2]);
Assert.AreSame(events[3].LogEvent, target.Events[3]);
Assert.AreSame(events[4].LogEvent, target.Events[4]);
Assert.AreSame(events[5].LogEvent, target.Events[5]);
Assert.AreSame(events[6].LogEvent, target.Events[6]);
Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
}
[Test]
public void PostFilteringTargetWrapperNoFiltersDefined()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
wrapper.WriteAsyncLogEvents(events);
// make sure all events went through
Assert.AreEqual(7, target.Events.Count);
Assert.AreSame(events[0].LogEvent, target.Events[0]);
Assert.AreSame(events[1].LogEvent, target.Events[1]);
Assert.AreSame(events[2].LogEvent, target.Events[2]);
Assert.AreSame(events[3].LogEvent, target.Events[3]);
Assert.AreSame(events[4].LogEvent, target.Events[4]);
Assert.AreSame(events[5].LogEvent, target.Events[5]);
Assert.AreSame(events[6].LogEvent, target.Events[6]);
Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
}
public class MyTarget : Target
{
public MyTarget()
{
this.Events = new List<LogEventInfo>();
}
public List<LogEventInfo> Events { get; set; }
protected override void Write(LogEventInfo logEvent)
{
this.Events.Add(logEvent);
}
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AbsScalar_Vector64_Single()
{
var test = new SimpleUnaryOpTest__AbsScalar_Vector64_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__AbsScalar_Vector64_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__AbsScalar_Vector64_Single testClass)
{
var result = AdvSimd.AbsScalar(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsScalar_Vector64_Single testClass)
{
fixed (Vector64<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector64<Single> _clsVar1;
private Vector64<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__AbsScalar_Vector64_Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
}
public SimpleUnaryOpTest__AbsScalar_Vector64_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AbsScalar(
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsScalar), new Type[] { typeof(Vector64<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsScalar), new Type[] { typeof(Vector64<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AbsScalar(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Single>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr);
var result = AdvSimd.AbsScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr));
var result = AdvSimd.AbsScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__AbsScalar_Vector64_Single();
var result = AdvSimd.AbsScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__AbsScalar_Vector64_Single();
fixed (Vector64<Single>* pFld1 = &test._fld1)
{
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AbsScalar(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AbsScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AbsScalar(
AdvSimd.LoadVector64((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(Math.Abs(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsScalar)}<Single>(Vector64<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Manatee.Json.Internal;
namespace Manatee.Json.Parsing
{
internal class ObjectParser : IJsonParser
{
public bool Handles(char c)
{
return c == '{';
}
public bool TryParse(string source, ref int index, [NotNullWhen(true)] out JsonValue? value, [NotNullWhen(false)] out string? errorMessage, bool allowExtraChars)
{
bool complete = false;
var obj = new JsonObject();
value = obj;
var length = source.Length;
index++;
while (index < length)
{
errorMessage = source.SkipWhiteSpace(ref index, length, out char c);
if (errorMessage != null) return false;
// check for empty object
if (c == '}')
if (obj.Count == 0)
{
complete = true;
index++;
break;
}
else
{
errorMessage = "Expected key.";
return false;
}
// get key
errorMessage = source.SkipWhiteSpace(ref index, length, out c);
if (errorMessage != null) return false;
if (c != '\"')
{
errorMessage = "Expected key.";
return false;
}
if (!JsonParser.TryParse(source, ref index, out var item, out errorMessage)) return false;
var key = item!.String;
// check for colon
errorMessage = source.SkipWhiteSpace(ref index, length, out c);
if (errorMessage != null) return false;
if (c != ':')
{
obj.Add(key, null!);
errorMessage = "Expected ':'.";
return false;
}
index++;
// get value (whitespace is removed in Parse)
var success = JsonParser.TryParse(source, ref index, out item, out errorMessage);
obj.Add(key, item!);
if (!success) return false;
errorMessage = source.SkipWhiteSpace(ref index, length, out c);
if (errorMessage != null) return false;
// check for end or separator
index++;
if (c == '}')
{
complete = true;
break;
}
if (c != ',')
{
errorMessage = "Expected ','.";
return false;
}
}
if (!complete)
{
errorMessage = "Unterminated object (missing '}').";
return false;
}
errorMessage = null;
return true;
}
public bool TryParse(TextReader stream, [NotNullWhen(true)] out JsonValue? value, [NotNullWhen(false)] out string? errorMessage)
{
bool complete = false;
var obj = new JsonObject();
value = obj;
while (stream.Peek() != -1)
{
stream.Read(); // waste the '{' or ','
errorMessage = stream.SkipWhiteSpace(out char c);
if (errorMessage != null) return false;
// check for empty object
if (c == '}')
if (obj.Count == 0)
{
complete = true;
stream.Read(); // waste the '}'
break;
}
else
{
errorMessage = "Expected key.";
return false;
}
// get key
errorMessage = stream.SkipWhiteSpace(out c);
if (errorMessage != null) return false;
if (c != '\"')
{
errorMessage = "Expected key.";
return false;
}
if (!JsonParser.TryParse(stream, out var item, out errorMessage)) return false;
var key = item!.String;
// check for colon
errorMessage = stream.SkipWhiteSpace(out c);
if (errorMessage != null) return false;
if (c != ':')
{
obj.Add(key, null!);
errorMessage = "Expected ':'.";
return false;
}
stream.Read(); // waste the ':'
// get value (whitespace is removed in Parse)
var success = JsonParser.TryParse(stream, out item, out errorMessage);
obj.Add(key, item!);
if (!success) return false;
errorMessage = stream.SkipWhiteSpace(out c);
if (errorMessage != null) return false;
// check for end or separator
if (c == '}')
{
complete = true;
stream.Read(); // waste the '}'
break;
}
if (c != ',')
{
errorMessage = "Expected ','.";
return false;
}
}
if (!complete)
{
errorMessage = "Unterminated object (missing '}').";
return false;
}
errorMessage = null;
return true;
}
public async Task<(string? errorMessage, JsonValue? value)> TryParseAsync(TextReader stream, CancellationToken token)
{
bool complete = false;
var obj = new JsonObject();
var scratch = SmallBufferCache.Acquire(1);
string? errorMessage = null;
while (stream.Peek() != -1)
{
if (token.IsCancellationRequested)
{
errorMessage = "Parsing incomplete. The task was cancelled.";
break;
}
await stream.TryRead(scratch, 0, 1, token); // waste the '{' or ','
char c;
(errorMessage, c) = await stream.SkipWhiteSpaceAsync(scratch);
if (errorMessage != null) break;
// check for empty object
if (c == '}')
if (obj.Count == 0)
{
complete = true;
await stream.TryRead(scratch, 0, 1, token); // waste the '}'
break;
}
else
{
errorMessage = "Expected key.";
break;
}
// get key
(errorMessage, c) = await stream.SkipWhiteSpaceAsync(scratch);
if (errorMessage != null) break;
if (c != '\"')
{
errorMessage = "Expected key.";
break;
}
JsonValue? item;
(errorMessage, item) = await JsonParser.TryParseAsync(stream, token);
if (errorMessage != null) break;
var key = item!.String;
// check for colon
(errorMessage, c) = await stream.SkipWhiteSpaceAsync(scratch);
if (errorMessage != null) break;
if (c != ':')
{
obj.Add(key, null!);
errorMessage = "Expected ':'.";
break;
}
await stream.TryRead(scratch, 0, 1, token); // waste the ':'
// get value (whitespace is removed in Parse)
(errorMessage, item) = await JsonParser.TryParseAsync(stream, token);
obj.Add(key, item!);
if (errorMessage != null) break;
(errorMessage, c) = await stream.SkipWhiteSpaceAsync(scratch);
if (errorMessage != null) break;
// check for end or separator
if (c == '}')
{
complete = true;
await stream.TryRead(scratch, 0, 1, token); // waste the '}'
break;
}
if (c != ',')
{
errorMessage = "Expected ','.";
break;
}
}
if (!complete && errorMessage == null)
errorMessage = "Unterminated object (missing '}').";
SmallBufferCache.Release(scratch);
return (errorMessage, obj);
}
}
}
| |
//
// System.Data.DataTableReader.cs
//
// Author:
// Sureshkumar T <tsureshkumar@novell.com>
// Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Tim Coleman, 2003
//
//
// Copyright (C) 2004 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.
//
#if NET_2_0
using System.Collections;
using System.Data.Common;
namespace System.Data {
public sealed class DataTableReader : DbDataReader
{
bool _closed;
DataTable [] _tables;
int _current = -1;
int _index;
DataTable _schemaTable;
bool _tableCleared = false;
bool _subscribed = false;
DataRow _rowRef;
#region Constructors
public DataTableReader (DataTable dt)
: this (new DataTable[] {dt})
{
}
public DataTableReader (DataTable[] dataTables)
{
if (dataTables == null
|| dataTables.Length <= 0)
throw new ArgumentException ("Cannot Create DataTable. Argument Empty!");
this._tables = new DataTable [dataTables.Length];
for (int i = 0; i < dataTables.Length; i++)
this._tables [i] = dataTables [i];
_closed = false;
_index = 0;
_current = -1;
_rowRef = null;
_tableCleared = false;
SubscribeEvents ();
}
#endregion // Constructors
#region Properties
public override int Depth {
get { return 0; }
}
public override int FieldCount {
get { return CurrentTable.Columns.Count; }
}
public override bool HasRows {
get { return CurrentTable.Rows.Count > 0; }
}
public override bool IsClosed {
get { return _closed; }
}
public override object this [int index] {
get {
Validate ();
if (index < 0 || index >= FieldCount)
throw new ArgumentOutOfRangeException (String.Format ("index {0} is not" +
"in the range",
index)
);
DataRow row = CurrentRow;
if (row.RowState == DataRowState.Deleted)
throw new InvalidOperationException ("Deleted Row's information cannot be accessed!");
return row [index];
}
}
private DataTable CurrentTable
{
get { return _tables [_index]; }
}
private DataRow CurrentRow
{
get { return (DataRow) CurrentTable.Rows [_current]; }
}
public override object this [string name] {
get {
Validate ();
DataRow row = CurrentRow;
if (row.RowState == DataRowState.Deleted)
throw new InvalidOperationException ("Deleted Row's information cannot be accessed!");
return row [name];
}
}
public override int RecordsAffected {
get { return 0; }
}
public override int VisibleFieldCount {
get { return CurrentTable.Columns.Count; }
}
#endregion // Properties
#region Methods
private void SubscribeEvents ()
{
if (_subscribed) // avoid subscribing multiple times
return;
CurrentTable.TableCleared += new DataTableClearEventHandler (OnTableCleared);
CurrentTable.RowChanged += new DataRowChangeEventHandler (OnRowChanged);
_subscribed = true;
}
private void UnsubscribeEvents ()
{
if (!_subscribed) // avoid un-subscribing multiple times
return;
CurrentTable.TableCleared -= new DataTableClearEventHandler (OnTableCleared);
CurrentTable.RowChanged -= new DataRowChangeEventHandler (OnRowChanged);
_subscribed = false;
}
public override void Close ()
{
if (IsClosed)
return;
UnsubscribeEvents ();
_closed = true;
}
public override void Dispose ()
{
Close ();
}
public override bool GetBoolean (int i)
{
return (bool) GetValue (i);
}
public override byte GetByte (int i)
{
return (byte) GetValue (i);
}
[MonoTODO]
public override long GetBytes (int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
public override char GetChar (int i)
{
return (char) GetValue (i);
}
[MonoTODO]
public override long GetChars (int i, long dataIndex, char[] buffer, int bufferIndex, int length)
{
throw new NotImplementedException ();
}
public override string GetDataTypeName (int i)
{
return GetFieldType (i).ToString ();
}
public override DateTime GetDateTime (int i)
{
return (DateTime) GetValue (i);
}
public override decimal GetDecimal (int i)
{
return (decimal) GetValue (i);
}
public override double GetDouble (int i)
{
return (double) GetValue (i);
}
[MonoTODO]
public override IEnumerator GetEnumerator ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public override Type GetFieldProviderSpecificType (int i)
{
throw new NotImplementedException ();
}
public override Type GetFieldType (int i)
{
ValidateClosed ();
return CurrentTable.Columns [i].DataType;
}
public override float GetFloat (int i)
{
return (float) GetValue (i);
}
public override Guid GetGuid (int i)
{
return (Guid) GetValue (i);
}
public override short GetInt16 (int i)
{
return (short) GetValue (i);
}
public override int GetInt32 (int i)
{
return (int) GetValue (i);
}
public override long GetInt64 (int i)
{
return (long) GetValue (i);
}
public override string GetName (int i)
{
return (string) GetValue (i);
}
public override int GetOrdinal (string name)
{
ValidateClosed ();
DataColumn column = CurrentTable.Columns [name];
if (column == null)
throw new ArgumentException (String.Format ("Column {0} is not found in the schema",
name));
return column.Ordinal;
}
[MonoTODO]
public override object GetProviderSpecificValue (int i)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override int GetProviderSpecificValues (object[] values)
{
throw new NotImplementedException ();
}
public override string GetString (int i)
{
return (string) GetValue (i);
}
public override object GetValue (int i)
{
return this [i];
}
[MonoTODO]
public override int GetValues (object[] values)
{
throw new NotImplementedException ();
}
public override bool IsDBNull (int i)
{
return GetValue (i) is DBNull;
}
public override DataTable GetSchemaTable ()
{
if (_schemaTable != null)
return _schemaTable;
DataTable dt = DbDataReader.GetSchemaTableTemplate ();
foreach (DataColumn column in CurrentTable.Columns) {
DataRow row = dt.NewRow ();
row ["ColumnName"] = column.ColumnName;
row ["ColumnOrdinal"] = column.Ordinal;
row ["ColumnSize"] = column.MaxLength;
row ["NumericPrecision"]= DBNull.Value;
row ["NumericScale"] = DBNull.Value;
row ["IsUnique"] = DBNull.Value;
row ["IsKey"] = DBNull.Value;
row ["DataType"] = column.DataType.ToString ();
row ["AllowDBNull"] = column.AllowDBNull;
row ["IsAliased"] = DBNull.Value;
row ["IsExpression"] = DBNull.Value;
row ["IsIdentity"] = DBNull.Value;
row ["IsAutoIncrement"] = DBNull.Value;
row ["IsRowVersion"] = DBNull.Value;
row ["IsHidden"] = DBNull.Value;
row ["IsLong"] = DBNull.Value;
row ["IsReadOnly"] = column.ReadOnly;
dt.Rows.Add (row);
}
return _schemaTable = dt;
}
private void Validate ()
{
ValidateClosed ();
if (_index >= _tables.Length)
throw new InvalidOperationException ("Invalid attempt to read when " +
"no data is present");
if (_tableCleared)
throw new RowNotInTableException ("The table is cleared, no rows are " +
"accessible");
if (_current == -1)
throw new InvalidOperationException ("DataReader is invalid " +
"for the DataTable");
}
private void ValidateClosed ()
{
if (IsClosed)
throw new InvalidOperationException ("Invalid attempt to read when " +
"the reader is closed");
}
private bool MoveNext ()
{
if (_index >= _tables.Length || _tableCleared)
return false;
do {
_current++;
} while (_current < CurrentTable.Rows.Count
&& CurrentRow.RowState == DataRowState.Deleted);
_rowRef = _current < CurrentTable.Rows.Count ? CurrentRow : null;
return _current < CurrentTable.Rows.Count;
}
public override bool NextResult ()
{
if ((_index + 1) >= _tables.Length) {
UnsubscribeEvents ();
_index = _tables.Length; // to make any attempt invalid
return false; // end of tables.
}
UnsubscribeEvents ();
_index++;
_current = -1;
_rowRef = null;
_schemaTable = null; // force to create fresh
_tableCleared = false;
SubscribeEvents ();
return true;
}
public override bool Read ()
{
ValidateClosed ();
return MoveNext ();
}
#endregion // Methods
#region // Event Handlers
private void OnRowChanged (object src, DataRowChangeEventArgs args)
{
DataRowAction action = args.Action;
DataRow row = args.Row;
if (action == DataRowAction.Add) {
if (_tableCleared && _current != -1)
return;
if (_current == -1 // yet to read
|| (_current >= 0 && row.RowID > CurrentRow.RowID) // row added above
) {
_tableCleared = false;
return; // no. movement required, if row added after current.
}
_current++;
_rowRef = CurrentRow;
}
if (action == DataRowAction.Commit
&& row.RowState == DataRowState.Detached) {
// if i am the row deleted, move one down
if (_rowRef == row) {
_current --;
_rowRef = _current >= 0 ? CurrentRow : null;
}
// if the row deleted is the last row, move down
if (_current >= CurrentTable.Rows.Count) {
_current--;
_rowRef = _current >= 0 ? CurrentRow : null;
return;
}
// deleting a row below _current moves the row one down
if (_current > 0 && _rowRef == CurrentTable.Rows [_current-1]) {
_current--;
_rowRef = CurrentRow;
return;
}
}
}
private void OnTableCleared (object src, DataTableClearEventArgs args)
{
_tableCleared = true;
}
#endregion // Event Handlers
}
}
#endif // NET_2_0
| |
//-----------------------------------------------------------------------
// <copyright file="TcpHelper.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using Akka.Actor;
using Akka.IO;
using Akka.Streams.TestKit;
using Akka.TestKit;
using Reactive.Streams;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.IO
{
public abstract class TcpHelper : AkkaSpec
{
protected TcpHelper(string config, ITestOutputHelper helper) : base(config, helper)
{
Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(4, 4);
Materializer = Sys.Materializer(Settings);
}
protected ActorMaterializerSettings Settings { get; }
protected ActorMaterializer Materializer { get; }
protected sealed class ClientWrite
{
public ClientWrite(ByteString bytes)
{
Bytes = bytes;
}
public ByteString Bytes { get; }
}
protected sealed class ClientRead
{
public ClientRead(int count, IActorRef readTo)
{
Count = count;
ReadTo = readTo;
}
public int Count { get; }
public IActorRef ReadTo { get; }
}
protected sealed class ClientClose
{
public ClientClose(Tcp.CloseCommand cmd)
{
Cmd = cmd;
}
public Tcp.CloseCommand Cmd { get; }
}
protected sealed class ReadResult
{
public ReadResult(ByteString bytes)
{
Bytes = bytes;
}
public ByteString Bytes { get; }
}
// FIXME: Workaround object just to force a ResumeReading that will poll for a possibly pending close event
// See https://github.com/akka/akka/issues/16552
// remove this and corresponding code path once above is fixed
protected sealed class PingClose
{
public PingClose(IActorRef requester)
{
Requester = requester;
}
public IActorRef Requester { get; }
}
protected sealed class WriteAck : Tcp.Event
{
public static WriteAck Instance { get; } = new WriteAck();
private WriteAck() { }
}
protected static Props TestClientProps(IActorRef connection)
=> Props.Create(() => new TestClient(connection)).WithDispatcher("akka.test.stream-dispatcher");
protected static Props TestServerProps(EndPoint address, IActorRef probe)
=> Props.Create(() => new TestServer(address, probe)).WithDispatcher("akka.test.stream-dispatcher");
protected class TestClient : UntypedActor
{
private readonly IActorRef _connection;
private readonly Queue<ByteString> _queuedWrites = new Queue<ByteString>();
private bool _writePending;
private int _toRead;
private ByteString _readBuffer = ByteString.Empty;
private IActorRef _readTo = Context.System.DeadLetters;
private Tcp.CloseCommand _closeAfterWrite;
public TestClient(IActorRef connection)
{
_connection = connection;
connection.Tell(new Tcp.Register(Self, keepOpenonPeerClosed: true, useResumeWriting: false));
}
protected override void OnReceive(object message)
{
message.Match().With<ClientWrite>(w =>
{
if (!_writePending)
{
_writePending = true;
_connection.Tell(Tcp.Write.Create(w.Bytes, WriteAck.Instance));
}
else
_queuedWrites.Enqueue(w.Bytes);
}).With<WriteAck>(() =>
{
if (_queuedWrites.Count != 0)
{
var next = _queuedWrites.Dequeue();
_connection.Tell(Tcp.Write.Create(next, WriteAck.Instance));
}
else
{
_writePending = false;
if(_closeAfterWrite != null)
_connection.Tell(_closeAfterWrite);
}
}).With<ClientRead>(r =>
{
_readTo = r.ReadTo;
_toRead = r.Count;
_connection.Tell(Tcp.ResumeReading.Instance);
}).With<Tcp.Received>(r =>
{
_readBuffer += r.Data;
if (_readBuffer.Count >= _toRead)
{
_readTo.Tell(new ReadResult(_readBuffer));
_readBuffer = ByteString.Empty;
_toRead = 0;
_readTo = Context.System.DeadLetters;
}
else
_connection.Tell(Tcp.ResumeReading.Instance);
}).With<PingClose>(p =>
{
_readTo = p.Requester;
_connection.Tell(Tcp.ResumeReading.Instance);
}).With<Tcp.ConnectionClosed>(c =>
{
_readTo.Tell(c);
if(!c.IsPeerClosed)
Context.Stop(Self);
}).With<ClientClose>(c =>
{
if (!_writePending)
_connection.Tell(c.Cmd);
else
_closeAfterWrite = c.Cmd;
});
}
}
protected sealed class ServerClose
{
public static ServerClose Instance { get; } = new ServerClose();
private ServerClose() { }
}
protected class TestServer : UntypedActor
{
private readonly IActorRef _probe;
private IActorRef _listener = Nobody.Instance;
public TestServer(EndPoint address, IActorRef probe)
{
_probe = probe;
Context.System.Tcp().Tell(new Tcp.Bind(Self, address, pullMode: true));
}
protected override void OnReceive(object message)
{
message.Match().With<Tcp.Bound>(b =>
{
_listener = Sender;
_listener.Tell(new Tcp.ResumeAccepting(1));
_probe.Tell(b);
}).With<Tcp.Connected>(() =>
{
var handler = Context.ActorOf(TestClientProps(Sender));
_listener.Tell(new Tcp.ResumeAccepting(1));
_probe.Tell(handler);
}).With<ServerClose>(() =>
{
_listener.Tell(Tcp.Unbind.Instance);
Context.Stop(Self);
});
}
}
protected class Server
{
private readonly TestKitBase _testkit;
public Server(TestKitBase testkit, EndPoint address = null)
{
_testkit = testkit;
Address = address ?? TestUtils.TemporaryServerAddress();
ServerProbe = testkit.CreateTestProbe();
ServerRef = testkit.ActorOf(TestServerProps(Address, ServerProbe.Ref));
ServerProbe.ExpectMsg<Tcp.Bound>();
}
public EndPoint Address { get; }
public TestProbe ServerProbe { get; }
public IActorRef ServerRef { get; }
public ServerConnection WaitAccept() => new ServerConnection(_testkit, ServerProbe.ExpectMsg<IActorRef>());
public void Close() => ServerRef.Tell(ServerClose.Instance);
}
protected class ServerConnection
{
private readonly IActorRef _connectionActor;
private readonly TestProbe _connectionProbe;
public ServerConnection(TestKitBase testkit, IActorRef connectionActor)
{
_connectionActor = connectionActor;
_connectionProbe = testkit.CreateTestProbe();
}
public void Write(ByteString bytes) => _connectionActor.Tell(new ClientWrite(bytes));
public void Read(int count) => _connectionActor.Tell(new ClientRead(count, _connectionProbe.Ref));
public ByteString WaitRead() => _connectionProbe.ExpectMsg<ReadResult>().Bytes;
public void ConfirmedClose() => _connectionActor.Tell(new ClientClose(Tcp.ConfirmedClose.Instance));
public void Close() => _connectionActor.Tell(new ClientClose(Tcp.Close.Instance));
public void Abort() => _connectionActor.Tell(new ClientClose(Tcp.Abort.Instance));
public void ExpectClosed(Tcp.ConnectionClosed expected) => ExpectClosed(close => close == expected);
public void ExpectClosed(Predicate<Tcp.ConnectionClosed> isMessage, TimeSpan? max = null)
{
max = max ?? TimeSpan.FromSeconds(3);
_connectionActor.Tell(new PingClose(_connectionProbe.Ref));
_connectionProbe.FishForMessage(isMessage, max);
}
public void ExpectTerminated()
{
_connectionProbe.Watch(_connectionActor);
_connectionProbe.ExpectTerminated(_connectionActor);
}
}
protected class TcpReadProbe
{
public TcpReadProbe(TestKitBase testkit)
{
SubscriberProbe = testkit.CreateManualSubscriberProbe<ByteString>();
TcpReadSubscription = new Lazy<ISubscription>(() => SubscriberProbe.ExpectSubscription());
}
public Lazy<ISubscription> TcpReadSubscription { get; }
public TestSubscriber.ManualProbe<ByteString> SubscriberProbe { get; }
public ByteString Read(int count)
{
var result = ByteString.Empty;
while (result.Count < count)
{
TcpReadSubscription.Value.Request(1);
result += SubscriberProbe.ExpectNext();
}
return result;
}
public void Close() => TcpReadSubscription.Value.Cancel();
}
protected class TcpWriteProbe
{
private long _demand;
public TcpWriteProbe(TestKitBase testkit)
{
PublisherProbe = testkit.CreateManualPublisherProbe<ByteString>();
TcpWriteSubscription =
new Lazy<StreamTestKit.PublisherProbeSubscription<ByteString>>(
() => PublisherProbe.ExpectSubscription());
}
public Lazy<StreamTestKit.PublisherProbeSubscription<ByteString>> TcpWriteSubscription { get; }
public TestPublisher.ManualProbe<ByteString> PublisherProbe { get; }
public void Write(ByteString bytes)
{
if (_demand == 0)
_demand += TcpWriteSubscription.Value.ExpectRequest();
TcpWriteSubscription.Value.SendNext(bytes);
_demand -= 1;
}
public void Close() => TcpWriteSubscription.Value.SendComplete();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Host), Shared]
internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory
{
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var textFactory = workspaceServices.GetService<ITextFactoryService>();
return new TemporaryStorageService(textFactory);
}
/// <summary>
/// Temporarily stores text and streams in memory mapped files.
/// </summary>
internal class TemporaryStorageService : ITemporaryStorageService2
{
private readonly ITextFactoryService _textFactory;
public TemporaryStorageService(ITextFactoryService textFactory)
{
_textFactory = textFactory;
}
public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken)
{
return new TemporaryTextStorage(this);
}
public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long size, Encoding encoding, CancellationToken cancellationToken)
{
return new TemporaryTextStorage(this, storageName, size, encoding);
}
public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken)
{
return new TemporaryStreamStorage(this);
}
public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long size, CancellationToken cancellationToken)
{
return new TemporaryStreamStorage(this, storageName, size);
}
private class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private Encoding _encoding;
private MemoryMappedInfo _memoryMappedInfo;
public TemporaryTextStorage(TemporaryStorageService service)
{
_service = service;
}
public TemporaryTextStorage(TemporaryStorageService service, string storageName, long size, Encoding encoding)
{
_service = service;
_encoding = encoding;
_memoryMappedInfo = new MemoryMappedInfo(storageName, size);
}
public string Name => _memoryMappedInfo?.Name;
public long Size => _memoryMappedInfo.Size;
public void Dispose()
{
if (_memoryMappedInfo != null)
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo.Dispose();
_memoryMappedInfo = null;
}
if (_encoding != null)
{
_encoding = null;
}
}
public SourceText ReadText(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken))
{
using (var stream = _memoryMappedInfo.CreateReadableStream())
using (var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length, cancellationToken))
{
// we pass in encoding we got from original source text even if it is null.
return _service._textFactory.CreateText(reader, _encoding, cancellationToken);
}
}
}
public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken)
{
// There is a reason for implementing it like this: proper async implementation
// that reads the underlying memory mapped file stream in an asynchronous fashion
// doesn't actually work. Windows doesn't offer
// any non-blocking way to read from a memory mapped file; the underlying memcpy
// may block as the memory pages back in and that's something you have to live
// with. Therefore, any implementation that attempts to use async will still
// always be blocking at least one threadpool thread in the memcpy in the case
// of a page fault. Therefore, if we're going to be blocking a thread, we should
// just block one thread and do the whole thing at once vs. a fake "async"
// implementation which will continue to requeue work back to the thread pool.
return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteText(SourceText text, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken))
{
_encoding = text.Encoding;
// the method we use to get text out of SourceText uses Unicode (2bytes per char).
var size = Encoding.Unicode.GetMaxByteCount(text.Length);
_memoryMappedInfo = new MemoryMappedInfo(size);
// Write the source text out as Unicode. We expect that to be cheap.
using (var stream = _memoryMappedInfo.CreateWritableStream())
{
using (var writer = new StreamWriter(stream, Encoding.Unicode))
{
text.Write(writer, cancellationToken);
}
}
}
}
public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default(CancellationToken))
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
private unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength, CancellationToken cancellationToken)
{
char* src = (char*)accessor.GetPointer();
// BOM: Unicode, little endian
// Skip the BOM when creating the reader
Debug.Assert(*src == 0xFEFF);
return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1);
}
}
private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private MemoryMappedInfo _memoryMappedInfo;
public TemporaryStreamStorage(TemporaryStorageService service)
{
_service = service;
}
public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long size)
{
_service = service;
_memoryMappedInfo = new MemoryMappedInfo(storageName, size);
}
public string Name => _memoryMappedInfo?.Name;
public long Size => _memoryMappedInfo.Size;
public void Dispose()
{
if (_memoryMappedInfo != null)
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo.Dispose();
_memoryMappedInfo = null;
}
}
public Stream ReadStream(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return _memoryMappedInfo.CreateReadableStream();
}
}
public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default(CancellationToken))
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteStream(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
// The Wait() here will not actually block, since with useAsync: false, the
// entire operation will already be done when WaitStreamMaybeAsync completes.
WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult();
}
public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
return WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken);
}
private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once);
}
if (stream.Length == 0)
{
throw new ArgumentOutOfRangeException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken))
{
var size = stream.Length;
_memoryMappedInfo = new MemoryMappedInfo(size);
using (var viewStream = _memoryMappedInfo.CreateWritableStream())
{
var buffer = SharedPools.ByteArray.Allocate();
try
{
while (true)
{
int count;
if (useAsync)
{
count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
else
{
count = stream.Read(buffer, 0, buffer.Length);
}
if (count == 0)
{
break;
}
viewStream.Write(buffer, 0, count);
}
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
}
}
}
}
internal unsafe class DirectMemoryAccessStreamReader : TextReader
{
private char* _position;
private readonly char* _end;
public DirectMemoryAccessStreamReader(char* src, int length)
{
Debug.Assert(src != null);
Debug.Assert(length >= 0);
_position = src;
_end = _position + length;
Length = length;
}
public int Length { get; }
public override int Peek()
{
if (_position >= _end)
{
return -1;
}
return *_position;
}
public override int Read()
{
if (_position >= _end)
{
return -1;
}
return *_position++;
}
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0 || index >= buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0 || (index + count) > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
count = Math.Min(count, (int)(_end - _position));
if (count > 0)
{
Marshal.Copy((IntPtr)_position, buffer, index, count);
_position += count;
}
return count;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public class CSharpCommandLineParser : CommandLineParser
{
public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser();
internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true);
internal CSharpCommandLineParser(bool isScriptRunner = false)
: base(CSharp.MessageProvider.Instance, isScriptRunner)
{
}
protected override string RegularFileExtension { get { return ".cs"; } }
protected override string ScriptFileExtension { get { return ".csx"; } }
internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories)
{
return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories);
}
/// <summary>
/// Parses a command line.
/// </summary>
/// <param name="args">A collection of strings representing the command line arguments.</param>
/// <param name="baseDirectory">The base directory used for qualifying file locations.</param>
/// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param>
/// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param>
/// <returns>a commandlinearguments object representing the parsed command line.</returns>
public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null)
{
List<Diagnostic> diagnostics = new List<Diagnostic>();
List<string> flattenedArgs = new List<string>();
List<string> scriptArgs = IsScriptRunner ? new List<string>() : null;
FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory);
string appConfigPath = null;
bool displayLogo = true;
bool displayHelp = false;
bool optimize = false;
bool checkOverflow = false;
bool allowUnsafe = false;
bool concurrentBuild = true;
bool deterministic = false; // TODO(5431): Enable deterministic mode by default
bool emitPdb = false;
DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb;
bool debugPlus = false;
string pdbPath = null;
bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts
string outputDirectory = baseDirectory;
ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty;
string outputFileName = null;
string documentationPath = null;
string errorLogPath = null;
bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid.
bool utf8output = false;
OutputKind outputKind = OutputKind.ConsoleApplication;
SubsystemVersion subsystemVersion = SubsystemVersion.None;
LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion;
string mainTypeName = null;
string win32ManifestFile = null;
string win32ResourceFile = null;
string win32IconFile = null;
bool noWin32Manifest = false;
Platform platform = Platform.AnyCpu;
ulong baseAddress = 0;
int fileAlignment = 0;
bool? delaySignSetting = null;
string keyFileSetting = null;
string keyContainerSetting = null;
List<ResourceDescription> managedResources = new List<ResourceDescription>();
List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>();
List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>();
bool sourceFilesSpecified = false;
bool resourcesOrModulesSpecified = false;
Encoding codepage = null;
var checksumAlgorithm = SourceHashAlgorithm.Sha1;
var defines = ArrayBuilder<string>.GetInstance();
List<CommandLineReference> metadataReferences = new List<CommandLineReference>();
List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>();
List<string> libPaths = new List<string>();
List<string> sourcePaths = new List<string>();
List<string> keyFileSearchPaths = new List<string>();
List<string> usings = new List<string>();
var generalDiagnosticOption = ReportDiagnostic.Default;
var diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
var noWarns = new Dictionary<string, ReportDiagnostic>();
var warnAsErrors = new Dictionary<string, ReportDiagnostic>();
int warningLevel = 4;
bool highEntropyVA = false;
bool printFullPaths = false;
string moduleAssemblyName = null;
string moduleName = null;
List<string> features = new List<string>();
string runtimeMetadataVersion = null;
bool errorEndLocation = false;
bool reportAnalyzer = false;
string instrument = "";
CultureInfo preferredUILang = null;
string touchedFilesPath = null;
bool optionsEnded = false;
bool interactiveMode = false;
bool publicSign = false;
// Process ruleset files first so that diagnostic severity settings specified on the command line via
// /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
if (!IsScriptRunner)
{
foreach (string arg in flattenedArgs)
{
string name, value;
if (TryParseOption(arg, out name, out value) && (name == "ruleset"))
{
var unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
}
else
{
generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory);
}
}
}
}
foreach (string arg in flattenedArgs)
{
Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal));
string name, value;
if (optionsEnded || !TryParseOption(arg, out name, out value))
{
sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics));
if (sourceFiles.Count > 0)
{
sourceFilesSpecified = true;
}
continue;
}
switch (name)
{
case "?":
case "help":
displayHelp = true;
continue;
case "r":
case "reference":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false));
continue;
case "features":
if (value == null)
{
features.Clear();
}
else
{
features.Add(value);
}
continue;
case "lib":
case "libpath":
case "libpaths":
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics);
continue;
#if DEBUG
case "attachdebugger":
Debugger.Launch();
continue;
#endif
}
if (IsScriptRunner)
{
switch (name)
{
case "-": // csi -- script.csx
if (value != null) break;
// Indicates that the remaining arguments should not be treated as options.
optionsEnded = true;
continue;
case "i":
case "i+":
if (value != null) break;
interactiveMode = true;
continue;
case "i-":
if (value != null) break;
interactiveMode = false;
continue;
case "loadpath":
case "loadpaths":
ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics);
continue;
case "u":
case "using":
case "usings":
case "import":
case "imports":
usings.AddRange(ParseUsings(arg, value, diagnostics));
continue;
}
}
else
{
switch (name)
{
case "a":
case "analyzer":
analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics));
continue;
case "d":
case "define":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
IEnumerable<Diagnostic> defineDiagnostics;
defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics));
diagnostics.AddRange(defineDiagnostics);
continue;
case "codepage":
value = RemoveQuotesAndSlashes(value);
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var encoding = TryParseEncodingName(value);
if (encoding == null)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value);
continue;
}
codepage = encoding;
continue;
case "checksumalgorithm":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var newChecksumAlgorithm = TryParseHashAlgorithmName(value);
if (newChecksumAlgorithm == SourceHashAlgorithm.None)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value);
continue;
}
checksumAlgorithm = newChecksumAlgorithm;
continue;
case "checked":
case "checked+":
if (value != null)
{
break;
}
checkOverflow = true;
continue;
case "checked-":
if (value != null)
break;
checkOverflow = false;
continue;
case "instrument":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
}
else
{
instrument = value;
}
continue;
case "noconfig":
// It is already handled (see CommonCommandLineCompiler.cs).
continue;
case "sqmsessionguid":
// The use of SQM is deprecated in the compiler but we still support the parsing of the option for
// back compat reasons.
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name);
}
else
{
Guid sqmSessionGuid;
if (!Guid.TryParse(value, out sqmSessionGuid))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name);
}
}
continue;
case "preferreduilang":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
try
{
preferredUILang = new CultureInfo(value);
if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false)
{
// Do not use user custom cultures.
preferredUILang = null;
}
}
catch (CultureNotFoundException)
{
}
if (preferredUILang == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value);
}
continue;
case "out":
if (string.IsNullOrWhiteSpace(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory);
}
continue;
case "t":
case "target":
if (value == null)
{
break; // force 'unrecognized option'
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
}
else
{
outputKind = ParseTarget(value, diagnostics);
}
continue;
case "moduleassemblyname":
value = value != null ? value.Unquote() : null;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
}
else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value))
{
// Dev11 C# doesn't check the name (VB does)
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg);
}
else
{
moduleAssemblyName = value;
}
continue;
case "modulename":
var unquotedModuleName = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquotedModuleName))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename");
continue;
}
else
{
moduleName = unquotedModuleName;
}
continue;
case "platform":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg);
}
else
{
platform = ParsePlatform(value, diagnostics);
}
continue;
case "recurse":
value = RemoveQuotesAndSlashes(value);
if (value == null)
{
break; // force 'unrecognized option'
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
int before = sourceFiles.Count;
sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics));
if (sourceFiles.Count > before)
{
sourceFilesSpecified = true;
}
}
continue;
case "doc":
parseDocumentationComments = true;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
continue;
}
string unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
// CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out)
// if we just let the next case handle /doc:"".
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument.
}
else
{
documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "addmodule":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:");
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
// An error will be reported by the assembly manager anyways.
metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module)));
resourcesOrModulesSpecified = true;
}
continue;
case "l":
case "link":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true));
continue;
case "win32res":
win32ResourceFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32icon":
win32IconFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32manifest":
win32ManifestFile = GetWin32Setting(arg, value, diagnostics);
noWin32Manifest = false;
continue;
case "nowin32manifest":
noWin32Manifest = true;
win32ManifestFile = null;
continue;
case "res":
case "resource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true);
if (embeddedResource != null)
{
managedResources.Add(embeddedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "linkres":
case "linkresource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false);
if (linkedResource != null)
{
managedResources.Add(linkedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "debug":
emitPdb = true;
// unused, parsed for backward compat only
value = RemoveQuotesAndSlashes(value);
if (value != null)
{
if (value.IsEmpty())
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name);
continue;
}
switch (value.ToLower())
{
case "full":
case "pdbonly":
debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb;
break;
case "portable":
debugInformationFormat = DebugInformationFormat.PortablePdb;
break;
case "embedded":
debugInformationFormat = DebugInformationFormat.Embedded;
break;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value);
break;
}
}
continue;
case "debug+":
//guard against "debug+:xx"
if (value != null)
break;
emitPdb = true;
debugPlus = true;
continue;
case "debug-":
if (value != null)
break;
emitPdb = false;
debugPlus = false;
continue;
case "o":
case "optimize":
case "o+":
case "optimize+":
if (value != null)
break;
optimize = true;
continue;
case "o-":
case "optimize-":
if (value != null)
break;
optimize = false;
continue;
case "deterministic":
case "deterministic+":
if (value != null)
break;
deterministic = true;
continue;
case "deterministic-":
if (value != null)
break;
deterministic = false;
continue;
case "p":
case "parallel":
case "p+":
case "parallel+":
if (value != null)
break;
concurrentBuild = true;
continue;
case "p-":
case "parallel-":
if (value != null)
break;
concurrentBuild = false;
continue;
case "warnaserror":
case "warnaserror+":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Error;
// Reset specific warnaserror options (since last /warnaserror flag on the command line always wins),
// and bump warnings to errors.
warnAsErrors.Clear();
foreach (var key in diagnosticOptions.Keys)
{
if (diagnosticOptions[key] == ReportDiagnostic.Warn)
{
warnAsErrors[key] = ReportDiagnostic.Error;
}
}
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value));
}
continue;
case "warnaserror-":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Default;
// Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
warnAsErrors.Clear();
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
foreach (var id in ParseWarnings(value))
{
ReportDiagnostic ruleSetValue;
if (diagnosticOptions.TryGetValue(id, out ruleSetValue))
{
warnAsErrors[id] = ruleSetValue;
}
else
{
warnAsErrors[id] = ReportDiagnostic.Default;
}
}
}
continue;
case "w":
case "warn":
value = RemoveQuotesAndSlashes(value);
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
int newWarningLevel;
if (string.IsNullOrEmpty(value) ||
!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (newWarningLevel < 0 || newWarningLevel > 4)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name);
}
else
{
warningLevel = newWarningLevel;
}
continue;
case "nowarn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value));
}
continue;
case "unsafe":
case "unsafe+":
if (value != null)
break;
allowUnsafe = true;
continue;
case "unsafe-":
if (value != null)
break;
allowUnsafe = false;
continue;
case "langversion":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:");
}
else if (!TryParseLanguageVersion(value, out languageVersion))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value);
}
continue;
case "delaysign":
case "delaysign+":
if (value != null)
{
break;
}
delaySignSetting = true;
continue;
case "delaysign-":
if (value != null)
{
break;
}
delaySignSetting = false;
continue;
case "publicsign":
case "publicsign+":
if (value != null)
{
break;
}
publicSign = true;
continue;
case "publicsign-":
if (value != null)
{
break;
}
publicSign = false;
continue;
case "keyfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile");
}
else
{
keyFileSetting = RemoveQuotesAndSlashes(value);
}
// NOTE: Dev11/VB also clears "keycontainer", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "keycontainer":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer");
}
else
{
keyContainerSetting = value;
}
// NOTE: Dev11/VB also clears "keyfile", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "highentropyva":
case "highentropyva+":
if (value != null)
break;
highEntropyVA = true;
continue;
case "highentropyva-":
if (value != null)
break;
highEntropyVA = false;
continue;
case "nologo":
displayLogo = false;
continue;
case "baseaddress":
value = RemoveQuotesAndSlashes(value);
ulong newBaseAddress;
if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress))
{
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value);
}
}
else
{
baseAddress = newBaseAddress;
}
continue;
case "subsystemversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion");
continue;
}
// It seems VS 2012 just silently corrects invalid values and suppresses the error message
SubsystemVersion version = SubsystemVersion.None;
if (SubsystemVersion.TryParse(value, out version))
{
subsystemVersion = version;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value);
}
continue;
case "touchedfiles":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles");
continue;
}
else
{
touchedFilesPath = unquoted;
}
continue;
case "bugreport":
UnimplementedSwitch(diagnostics, name);
continue;
case "utf8output":
if (value != null)
break;
utf8output = true;
continue;
case "m":
case "main":
// Remove any quotes for consistent behavior as MSBuild can return quoted or
// unquoted main.
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
mainTypeName = unquoted;
continue;
case "fullpaths":
if (value != null)
break;
printFullPaths = true;
continue;
case "pathmap":
// "/pathmap:K1=V1,K2=V2..."
{
if (value == null)
break;
pathMap = pathMap.Concat(ParsePathMap(value, diagnostics));
}
continue;
case "filealign":
value = RemoveQuotesAndSlashes(value);
ushort newAlignment;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (!TryParseUInt16(value, out newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else if (!CompilationOptions.IsValidFileAlignment(newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else
{
fileAlignment = newAlignment;
}
continue;
case "pdb":
value = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
pdbPath = ParsePdbPath(value, diagnostics, baseDirectory);
}
continue;
case "errorendlocation":
errorEndLocation = true;
continue;
case "reportanalyzer":
reportAnalyzer = true;
continue;
case "nostdlib":
case "nostdlib+":
if (value != null)
break;
noStdLib = true;
continue;
case "nostdlib-":
if (value != null)
break;
noStdLib = false;
continue;
case "errorreport":
continue;
case "errorlog":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg));
}
else
{
errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "appconfig":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg));
}
else
{
appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "runtimemetadataversion":
unquoted = RemoveQuotesAndSlashes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
runtimeMetadataVersion = unquoted;
continue;
case "ruleset":
// The ruleset arg has already been processed in a separate pass above.
continue;
case "additionalfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name);
continue;
}
additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics));
continue;
}
}
AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg);
}
foreach (var o in warnAsErrors)
{
diagnosticOptions[o.Key] = o.Value;
}
// Specific nowarn options always override specific warnaserror options.
foreach (var o in noWarns)
{
diagnosticOptions[o.Key] = o.Value;
}
if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified))
{
AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources);
}
if (!noStdLib && sdkDirectory != null)
{
metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly));
}
if (!platform.Requires64Bit())
{
if (baseAddress > uint.MaxValue - 0x8000)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress));
baseAddress = 0;
}
}
// add additional reference paths if specified
if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories))
{
ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics);
}
ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths);
ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics);
// Dev11 searches for the key file in the current directory and assembly output directory.
// We always look to base directory and then examine the search paths.
keyFileSearchPaths.Add(baseDirectory);
if (baseDirectory != outputDirectory)
{
keyFileSearchPaths.Add(outputDirectory);
}
// Public sign doesn't use the legacy search path settings
if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting))
{
keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory);
}
var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features);
string compilationName;
GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName);
var parseOptions = new CSharpParseOptions
(
languageVersion: languageVersion,
preprocessorSymbols: defines.ToImmutableAndFree(),
documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None,
kind: SourceCodeKind.Regular,
features: parsedFeatures
);
var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);
// We want to report diagnostics with source suppression in the error log file.
// However, these diagnostics won't be reported on the command line.
var reportSuppressedDiagnostics = errorLogPath != null;
var options = new CSharpCompilationOptions
(
outputKind: outputKind,
moduleName: moduleName,
mainTypeName: mainTypeName,
scriptClassName: WellKnownMemberNames.DefaultScriptClassName,
usings: usings,
optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug,
checkOverflow: checkOverflow,
allowUnsafe: allowUnsafe,
deterministic: deterministic,
concurrentBuild: concurrentBuild,
cryptoKeyContainer: keyContainerSetting,
cryptoKeyFile: keyFileSetting,
delaySign: delaySignSetting,
platform: platform,
generalDiagnosticOption: generalDiagnosticOption,
warningLevel: warningLevel,
specificDiagnosticOptions: diagnosticOptions,
reportSuppressedDiagnostics: reportSuppressedDiagnostics,
publicSign: publicSign
);
if (debugPlus)
{
options = options.WithDebugPlusMode(debugPlus);
}
var emitOptions = new EmitOptions
(
metadataOnly: false,
debugInformationFormat: debugInformationFormat,
pdbFilePath: null, // to be determined later
outputNameOverride: null, // to be determined later
baseAddress: baseAddress,
highEntropyVirtualAddressSpace: highEntropyVA,
fileAlignment: fileAlignment,
subsystemVersion: subsystemVersion,
runtimeMetadataVersion: runtimeMetadataVersion,
instrument: instrument
);
// add option incompatibility errors if any
diagnostics.AddRange(options.Errors);
return new CSharpCommandLineArguments
{
IsScriptRunner = IsScriptRunner,
InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0,
BaseDirectory = baseDirectory,
PathMap = pathMap,
Errors = diagnostics.AsImmutable(),
Utf8Output = utf8output,
CompilationName = compilationName,
OutputFileName = outputFileName,
PdbPath = pdbPath,
EmitPdb = emitPdb,
OutputDirectory = outputDirectory,
DocumentationPath = documentationPath,
ErrorLogPath = errorLogPath,
AppConfigPath = appConfigPath,
SourceFiles = sourceFiles.AsImmutable(),
Encoding = codepage,
ChecksumAlgorithm = checksumAlgorithm,
MetadataReferences = metadataReferences.AsImmutable(),
AnalyzerReferences = analyzers.AsImmutable(),
AdditionalFiles = additionalFiles.AsImmutable(),
ReferencePaths = referencePaths,
SourcePaths = sourcePaths.AsImmutable(),
KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
Win32ResourceFile = win32ResourceFile,
Win32Icon = win32IconFile,
Win32Manifest = win32ManifestFile,
NoWin32Manifest = noWin32Manifest,
DisplayLogo = displayLogo,
DisplayHelp = displayHelp,
ManifestResources = managedResources.AsImmutable(),
CompilationOptions = options,
ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions,
EmitOptions = emitOptions,
ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
TouchedFilesPath = touchedFilesPath,
PrintFullPaths = printFullPaths,
ShouldIncludeErrorEndLocation = errorEndLocation,
PreferredUILang = preferredUILang,
ReportAnalyzer = reportAnalyzer
};
}
private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics)
{
if (string.IsNullOrEmpty(switchValue))
{
Debug.Assert(!string.IsNullOrEmpty(switchName));
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName);
return;
}
foreach (string path in ParseSeparatedPaths(switchValue))
{
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (resolvedPath == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize());
}
else if (!PortableShim.Directory.Exists(resolvedPath))
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize());
}
else
{
builder.Add(resolvedPath);
}
}
}
private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
string noQuotes = RemoveQuotesAndSlashes(value);
if (string.IsNullOrWhiteSpace(noQuotes))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
return noQuotes;
}
}
return null;
}
private void GetCompilationAndModuleNames(
List<Diagnostic> diagnostics,
OutputKind outputKind,
List<CommandLineSourceFile> sourceFiles,
bool sourceFilesSpecified,
string moduleAssemblyName,
ref string outputFileName,
ref string moduleName,
out string compilationName)
{
string simpleName;
if (outputFileName == null)
{
// In C#, if the output file name isn't specified explicitly, then executables take their
// names from the files containing their entrypoints and libraries derive their names from
// their first input files.
if (!IsScriptRunner && !sourceFilesSpecified)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName);
simpleName = null;
}
else if (outputKind.IsApplication())
{
simpleName = null;
}
else
{
simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path));
outputFileName = simpleName + outputKind.GetDefaultExtension();
if (simpleName.Length == 0 && !outputKind.IsNetModule())
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
}
else
{
simpleName = PathUtilities.RemoveExtension(outputFileName);
if (simpleName.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
if (outputKind.IsNetModule())
{
Debug.Assert(!IsScriptRunner);
compilationName = moduleAssemblyName;
}
else
{
if (moduleAssemblyName != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule);
}
compilationName = simpleName;
}
if (moduleName == null)
{
moduleName = outputFileName;
}
}
private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths)
{
var builder = ArrayBuilder<string>.GetInstance();
// Match how Dev11 builds the list of search paths
// see PCWSTR LangCompiler::GetSearchPath()
// current folder first -- base directory is searched by default
// Add SDK directory if it is available
if (sdkDirectoryOpt != null)
{
builder.Add(sdkDirectoryOpt);
}
// libpath
builder.AddRange(libPaths);
return builder.ToImmutableAndFree();
}
public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics)
{
Diagnostic myDiagnostic = null;
value = value.TrimEnd(null);
// Allow a trailing semicolon or comma in the options
if (!value.IsEmpty() &&
(value.Last() == ';' || value.Last() == ','))
{
value = value.Substring(0, value.Length - 1);
}
string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/);
var defines = new ArrayBuilder<string>(values.Length);
foreach (string id in values)
{
string trimmedId = id.Trim();
if (SyntaxFacts.IsValidIdentifier(trimmedId))
{
defines.Add(trimmedId);
}
else if (myDiagnostic == null)
{
myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId);
}
}
diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>()
: SpecializedCollections.SingletonEnumerable(myDiagnostic);
return defines.AsEnumerable();
}
private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "x86":
return Platform.X86;
case "x64":
return Platform.X64;
case "itanium":
return Platform.Itanium;
case "anycpu":
return Platform.AnyCpu;
case "anycpu32bitpreferred":
return Platform.AnyCpu32BitPreferred;
case "arm":
return Platform.Arm;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value);
return Platform.AnyCpu;
}
}
private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "exe":
return OutputKind.ConsoleApplication;
case "winexe":
return OutputKind.WindowsApplication;
case "library":
return OutputKind.DynamicallyLinkedLibrary;
case "module":
return OutputKind.NetModule;
case "appcontainerexe":
return OutputKind.WindowsRuntimeApplication;
case "winmdobj":
return OutputKind.WindowsRuntimeMetadata;
default:
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
return OutputKind.ConsoleApplication;
}
}
private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics)
{
if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg);
yield break;
}
foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
yield return u;
}
}
private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
foreach (string path in paths)
{
yield return new CommandLineAnalyzerReference(path);
}
}
private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
// /r:"reference"
// /r:alias=reference
// /r:alias="reference"
// /r:reference;reference
// /r:"path;containing;semicolons"
// /r:"unterminated_quotes
// /r:"quotes"in"the"middle
// /r:alias=reference;reference ... error 2034
// /r:nonidf=reference ... error 1679
int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });
string alias;
if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
{
alias = value.Substring(0, eqlOrQuote);
value = value.Substring(eqlOrQuote + 1);
if (!SyntaxFacts.IsValidIdentifier(alias))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
yield break;
}
}
else
{
alias = null;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
if (alias != null)
{
if (paths.Count > 1)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
yield break;
}
if (paths.Count == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
yield break;
}
}
foreach (string path in paths)
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;
var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
yield return new CommandLineReference(path, properties);
}
}
private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics)
{
if (win32ResourceFile != null)
{
if (win32IconResourceFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon);
}
if (win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest);
}
}
if (outputKind.IsNetModule() && win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule);
}
}
internal static ResourceDescription ParseResourceDescription(
string arg,
string resourceDescriptor,
string baseDirectory,
IList<Diagnostic> diagnostics,
bool embedded)
{
string filePath;
string fullPath;
string fileName;
string resourceName;
string accessibility;
ParseResourceDescription(
resourceDescriptor,
baseDirectory,
false,
out filePath,
out fullPath,
out fileName,
out resourceName,
out accessibility);
bool isPublic;
if (accessibility == null)
{
// If no accessibility is given, we default to "public".
// NOTE: Dev10 distinguishes between null and empty/whitespace-only.
isPublic = true;
}
else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
{
isPublic = true;
}
else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
{
isPublic = false;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
return null;
}
if (string.IsNullOrEmpty(filePath))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
return null;
}
if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
return null;
}
Func<Stream> dataProvider = () =>
{
// Use FileShare.ReadWrite because the file could be opened by the current process.
// For example, it is an XML doc file produced by the build.
return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite);
};
return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
}
private static bool TryParseLanguageVersion(string str, out LanguageVersion version)
{
var defaultVersion = LanguageVersion.Latest.MapLatestToVersion();
if (str == null)
{
version = defaultVersion;
return true;
}
switch (str.ToLowerInvariant())
{
case "iso-1":
version = LanguageVersion.CSharp1;
return true;
case "iso-2":
version = LanguageVersion.CSharp2;
return true;
case "7":
version = LanguageVersion.CSharp7;
return true;
case "default":
version = defaultVersion;
return true;
default:
// We are likely to introduce minor version numbers after C# 7, thus breaking the
// one-to-one correspondence between the integers and the corresponding
// LanguageVersion enum values. But for compatibility we continue to accept any
// integral value parsed by int.TryParse for its corresponding LanguageVersion enum
// value for language version C# 6 and earlier (e.g. leading zeros are allowed)
int versionNumber;
if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) &&
versionNumber <= 6 &&
((LanguageVersion)versionNumber).IsValid())
{
version = (LanguageVersion)versionNumber;
return true;
}
version = defaultVersion;
return false;
}
}
private static IEnumerable<string> ParseWarnings(string value)
{
value = value.Unquote();
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
ushort number;
if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) &&
ErrorFacts.IsWarning((ErrorCode)number))
{
// The id refers to a compiler warning.
yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number);
}
else
{
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied in /nowarn or
// /warnaserror. We no longer generate a warning in such cases.
// Instead we assume that the unrecognized id refers to a custom diagnostic.
yield return id;
}
}
}
private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
{
foreach (var id in items)
{
ReportDiagnostic existing;
if (d.TryGetValue(id, out existing))
{
// Rewrite the existing value with the latest one unless it is for /nowarn.
if (existing != ReportDiagnostic.Suppress)
d[id] = kind;
}
else
{
d.Add(id, kind);
}
}
}
private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName);
}
internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics)
{
// no error in csc.exe
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode));
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments));
}
/// <summary>
/// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode.
/// </summary>
private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments)
{
int code = (int)errorCode;
ReportDiagnostic value;
warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value);
if (value != ReportDiagnostic.Suppress)
{
AddDiagnostic(diagnostics, errorCode, arguments);
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
using MyTypes;
using System;
public class Raygun : MonoBehaviour {
#region Variables
// Raygun //
private GunMode m_currentGunMode = GunMode.Scaler;
[Tooltip("How far the weapon should shoot")]
public float weaponShootRange = 25;
[Tooltip("The end of the gun [Empty gameobject]")]
public Transform gunEnd;
private Camera fpsCam; // There should be a better transform reference to use instead of camera, it makes it so if multiple guns are present, there won't be enough transform to instantiate the beacon
// Raygun //
// Teleport //
// TODO: BEACON NEEDS TO BE OBJECT POOLED!!!
public Beacon beaconProjectile = null;
private Beacon beacon = null;
private GameObject lastObject = null;
[SerializeField]
private GameObject m_cutsceneCam;
[SerializeField]
private Transform m_targetPos;
[SerializeField]
private Transform m_originalPos;
private float m_targetFOV = 25;
private float m_originalFOV = 60;
[SerializeField]
private float m_screenSpeed = 1.0f;
private bool m_isLooking = false;
private RigidbodyFirstPersonController m_playerController;
private Transform m_rotationMarker;
// Teleport //
// Sizer //
private bool stuck = false;//check if you haved hooked to an object
private bool canFire = true;
private LineRenderer laserLine;
private GameObject currentHit;
private Color currentColor;
//where the beam ends [it starts from the center of the screen]
private Vector3 endPos;
[SerializeField]
[Tooltip("Layer to consider for the beam")]
private LayerMask beamMask;
[SerializeField]
[Tooltip("Layer to consider for the fit checkers")]
private LayerMask fitterMask;
// Sizer //
// Debuging //
public Text displayText = null;
public Text inst1 = null;
public Text inst2 = null;
// Debuging //
//death stuff//
private Transform parent;
private DeathComponent deathComp;
private StoreTransform savePosGun;
private StoreTransform saveRotGun;
private RigidbodyFirstPersonController rigController;
private Renderer cartridgeRenderer;
private Renderer[] gunPartsRenderers;
bool isDropGun = false;
bool isDyingReady = true;
//faux death gun
GameObject tempGun = null;
//private gameObject
// Audio
[SerializeField]
private string shrinkAndGrowSound;
private AudioManager audioManager;
private GameObject fauxGun;
private Animator m_animator;
private StaffAnimation m_staffAnimator;
#endregion Variables
#region Monobehaviour
void Awake() {
fauxGun = Resources.Load("RaygunFaux") as GameObject;
cartridgeRenderer = gameObject.GetComponent<Renderer>();
gunPartsRenderers = gameObject.GetComponentsInChildren<Renderer>();
audioManager = GameObject.FindGameObjectWithTag("Audio").GetComponent<AudioManager>();
}
void Start() {
parent = transform.root;
rigController = parent.GetComponent<RigidbodyFirstPersonController>();
deathComp = GetComponentInParent<DeathComponent>();
m_playerController = GetComponentInParent<RigidbodyFirstPersonController>();
savePosGun = gameObject.transform.Save().Position();
saveRotGun = gameObject.transform.Save().LocalRotation();
//m_oldCamPos = Camera.main.transform.position;
laserLine = GetComponent<LineRenderer>();
fpsCam = GetComponentInParent<Camera>();
if (!fpsCam) {
fpsCam = FindObjectOfType<Camera>();
}
m_animator = GetComponentInChildren<Animator>();
m_staffAnimator = transform.parent.GetComponentInChildren<StaffAnimation>();
}
void Update() {
if (!deathComp.isDead) {
if (isDropGun) {
Destroy(tempGun);
rigController.enabled = true;
cartridgeRenderer.enabled = true;
foreach (Renderer rends in gunPartsRenderers) {
rends.enabled = true;
}
isDyingReady = true;
isDropGun = false;
}
ChangeGunMode();
MoveToScreen();
if (displayText) {
switch (m_currentGunMode) {
case GunMode.Teleporter:
TeleportBeamInput();
displayText.text = "Teleport-Beam";
inst1.text = "Teleport object to beacon";
inst2.text = "Deploy Beacon";
break;
case GunMode.Scaler:
ScalerBeamInput();
StopDisplayingHologram();
displayText.text = "Sizer-beam";
inst1.text = "Grow object";
inst2.text = "Shrink object";
break;
default:
Debug.LogWarning("Current Gun Mode not set properly.");
displayText.text = "Current Gun Mode not set properly.";
break;
}
} else {
var disText = new GameObject("DisplayText", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text));
disText.transform.SetParent(FindObjectOfType<Canvas>().transform);
disText.GetComponent<RectTransform>().anchoredPosition = Vector2.one;
displayText = disText.GetComponent<Text>();
switch (m_currentGunMode) {
case GunMode.Teleporter:
TeleportBeamInput();
displayText.text = "Currently in: Teleport Mode";
break;
case GunMode.Scaler:
ScalerBeamInput();
StopDisplayingHologram();
displayText.text = "Currently in: Scaler Mode";
m_isLooking = false;
break;
default:
Debug.LogWarning("Current Gun Mode not set properly.");
displayText.text = "Current Gun Mode not set properly.";
break;
}
}
} else {
if (isDyingReady) {
print("dead");
tempGun = Instantiate(fauxGun, transform.position, transform.rotation);
rigController.enabled = false;
cartridgeRenderer.enabled = false;
foreach (Renderer rends in gunPartsRenderers) {
rends.enabled = false;
}
isDropGun = true;
isDyingReady = false;
}
}
}
void FixedUpdate() {
switch (m_currentGunMode) {
case GunMode.Teleporter:
TeleportBeam();
ToggleLookAtScreen();
break;
case GunMode.Scaler:
break;
default:
Debug.LogWarning("Current Gun Mode not set properly.");
break;
}
}
//void OnTriggerEnter(Collider other) {
// if (other.CompareTag("ForceField")) {
// Debug.Log("ForceField");
// DestroyBeacon();
// m_rotationMarker = other.GetComponent<LevelStart>().GetRotationMarker();
// }
//}
#endregion Monobehaviour
#region Teleport Beam
private void TeleportBeamInput() {
if (Input.GetMouseButtonDown(1)) {
m_staffAnimator.ThrowBeacon();
// play the next note in the sequence, while throwing the beacon
gameObject.transform.root.SendMessage("PlayNextNote");
// TODO: NEEDS TO BE OBJECT POOLED!!!
if (beacon != null) {
Destroy(beacon.gameObject); // Create cool destruction animation call that before destruction
}
if (m_rotationMarker != null)
{
beacon = Instantiate(beaconProjectile, gunEnd.transform.position/*fpsCam.transform.position*/, fpsCam.transform.rotation) as Beacon;
beacon.GiveLevelRotation(m_rotationMarker);
}
else
{
Debug.LogWarning("NO ROTATION SET");
}
}
if (beacon != null)
{
if (Input.GetKeyDown(KeyCode.Q))
{
beacon.RotateOnXAxis();
}
if (Input.GetKeyDown(KeyCode.E))
{
beacon.RotateOnYAxis();
}
}
}
private void TeleportBeam() {
if (!m_isLooking) {
RaycastHit hitInfo;
InteractMessage msg;
if (Physics.Raycast(gunEnd.transform.position/*fpsCam.transform.position*/, fpsCam.transform.forward, out hitInfo, weaponShootRange)) {
if (hitInfo.collider.GetComponent<TeleportComponent>()) {
if (beacon != null) {
lastObject = hitInfo.collider.gameObject;
msg = new InteractMessage(Interaction.TELEPORTING, "HitBegin", beacon);
lastObject.SendMessage("Interact", msg);
// Input
if (Input.GetMouseButtonDown(0)) {
m_staffAnimator.Teleport();
msg = new InteractMessage(Interaction.TELEPORTING, "Teleport", beacon);
lastObject.SendMessage("Interact", msg);
}
}
} else {
StopDisplayingHologram();
}
}
}
}
private void StopDisplayingHologram() {
InteractMessage msg;
if (beacon != null) {
if (lastObject != null) {
msg = new InteractMessage(Interaction.TELEPORTING, "HitEnd");
lastObject.SendMessage("Interact", msg);
lastObject = null;
}
}
}
private void DestroyBeacon() {
if (beacon != null) {
Destroy(beacon.gameObject);
beacon = null;
}
}
public void EnterLevelEntranceTrigger(Transform levelRotation)
{
DestroyBeacon();
m_rotationMarker = levelRotation;
}
private void ToggleLookAtScreen() {
if (Input.GetKey(KeyCode.LeftControl)) {
Debug.Log("LeftControl");
m_playerController.enabled = false;
m_isLooking = true;
m_cutsceneCam.SetActive(true);
} else if (Input.GetKeyUp(KeyCode.LeftControl)) {
m_playerController.enabled = true;
m_isLooking = false;
m_cutsceneCam.SetActive(false);
}
}
private void MoveToScreen() {
if (m_isLooking) {
if (Vector3.Distance(m_cutsceneCam.transform.position, m_targetPos.position) > 0.05f) {
Vector3 newGunPos = Vector3.Lerp(m_cutsceneCam.transform.position, m_targetPos.position, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.transform.position = newGunPos;
float newFOV = Mathf.Lerp(m_cutsceneCam.GetComponent<Camera>().fieldOfView, m_targetFOV, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.GetComponent<Camera>().fieldOfView = newFOV;
Quaternion newRot = Quaternion.Lerp(m_cutsceneCam.transform.rotation, m_targetPos.rotation, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.transform.rotation = newRot;
}
} else {
if (Vector3.Distance(m_cutsceneCam.transform.position, m_originalPos.position) > 0.05f) {
Vector3 newGunPos = Vector3.Lerp(m_cutsceneCam.transform.position, m_originalPos.position, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.transform.position = newGunPos;
float newFOV = Mathf.Lerp(m_cutsceneCam.GetComponent<Camera>().fieldOfView, m_originalFOV, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.GetComponent<Camera>().fieldOfView = newFOV;
Quaternion newRot = Quaternion.Lerp(m_cutsceneCam.transform.rotation, m_originalPos.rotation, m_screenSpeed * Time.deltaTime);
m_cutsceneCam.transform.rotation = newRot;
}
}
}
#endregion Teleport Beam
#region Scaler Beam
bool scaling = false;
private void ScalerBeamInput() {
if (canFire) {
if (Input.GetButtonDown("Fire1") || Input.GetButtonDown("Fire2"))
{
audioManager.PlaySoundConcurrent(shrinkAndGrowSound, true, 1.0f);
scaling = true;
}
if (Input.GetButtonUp("Fire1") || Input.GetButtonUp("Fire2"))
{
audioManager.StopSoundsConcurrent(shrinkAndGrowSound);
scaling = false;
}
if (Input.GetButton("Fire1")) {
m_staffAnimator.Grow(true);
if (scaling)
shootRay("growing");
}
if (Input.GetButton("Fire2")) {
m_staffAnimator.Shrink(true);
if (scaling)
shootRay("shrinking");
}
}
if (Input.GetButtonUp("Fire1") || Input.GetButtonUp("Fire2") || !canFire || !scaling) {
m_staffAnimator.Grow(false);
m_staffAnimator.Shrink(false);
laserLine.enabled = false;
if (stuck || !canFire) {
currentHit.GetComponent<Renderer>().material.color = currentColor;
stuck = false;
currentHit = null;
canFire = true;
}
}
}
private void shootRay(string whatAmIDoing) {
Vector3 camCenter = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
Vector3 rayOrigin = camCenter;
RaycastHit normalhit;
//lines 'resting' position
laserLine.SetPosition(0, gunEnd.position);
laserLine.SetPosition(1, camCenter);
if (!stuck) {
if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out normalhit, weaponShootRange)) {
Debug.DrawRay(rayOrigin, fpsCam.transform.forward * weaponShootRange, Color.red);
if (normalhit.transform.gameObject.GetComponent<ScaleComponent>()) {
stuck = true;
currentHit = normalhit.transform.gameObject;
//first set the raycast to the pos of object [lock it]
currentColor = currentHit.GetComponent<Renderer>().material.color;
currentHit.GetComponent<Renderer>().material.color = new Color(0, 0, 255);
laserLine.enabled = true;
}
} else {
print("too far");
}
} else {
//if you are hooked to an object, draw line to that object
endPos = currentHit.transform.GetComponent<Renderer>().bounds.center;
laserLine.SetPosition(1, endPos);
//TODO: MOVE THIS OUT
//this.transform.Rotate(new Vector3(0, 0, 60 * Time.deltaTime));
Debug.DrawLine(rayOrigin, endPos, Color.green);
if (Physics.Linecast(rayOrigin, endPos, out normalhit, beamMask.value)) {
if (normalhit.collider.gameObject != currentHit) {
print(normalhit.collider.gameObject);
print("blocked");
canFire = false;
} else {
//send scale msg to obj
InteractMessage sendMsg = new InteractMessage(Interaction.SCALING, "");
if (whatAmIDoing == "growing") {
sendMsg.msg = "GROW";
currentHit.SendMessage("Interact", sendMsg);
} else if (whatAmIDoing == "shrinking") {
sendMsg.msg = "SHRINK";
currentHit.SendMessage("Interact", sendMsg);
}
}
}
}
}
#endregion Scaler Beam
#region Raygun
private void ChangeGunMode() {
if (Input.GetKeyDown(KeyCode.Alpha1)) {
m_currentGunMode = GunMode.Teleporter;
m_animator.SetTrigger("OpenScreen");
scaling = false;
m_staffAnimator.SwitchToMode(m_currentGunMode);
}
if (Input.GetKeyDown(KeyCode.Alpha2)) {
m_currentGunMode = GunMode.Scaler;
m_animator.SetTrigger("CloseScreen");
m_staffAnimator.SwitchToMode(m_currentGunMode);
}
if (Input.GetKeyDown(KeyCode.Tab)) {
m_currentGunMode++;
if (m_currentGunMode >= GunMode.ModeCount) {
m_currentGunMode = 0;
}
if (m_currentGunMode == GunMode.Teleporter) {
m_animator.SetTrigger("OpenScreen");
if (canFire && currentHit != null)
scaling = false;
}
else
{
m_animator.SetTrigger("CloseScreen");
}
m_staffAnimator.SwitchToMode(m_currentGunMode);
}
}
public void ChangeGunMode(GunMode mode) {
m_currentGunMode = mode;
}
#endregion Raygun
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using AGXUnity;
using AGXUnity.Collide;
using AGXUnity.Utils;
using Mesh = AGXUnity.Collide.Mesh;
namespace AGXUnityEditor.Tools
{
public class ShapeCreateTool : Tool
{
public enum ShapeType
{
Box,
Cylinder,
Capsule,
Sphere,
Mesh,
HollowCylinder,
Cone,
HollowCone
}
public static GameObject CreateShape<T>( ShapeInitializationData data, bool shapeAsParent, Action<T> initializeAction ) where T : Shape
{
if ( initializeAction == null ) {
Debug.LogError( "Unable to create shape without an initializeAction." );
return null;
}
if ( data == null )
return null;
GameObject shapeGameObject = Factory.Create<T>();
Undo.RegisterCreatedObjectUndo( shapeGameObject, "New game object with shape component" );
if ( AGXUnity.Rendering.DebugRenderManager.HasInstance )
Undo.AddComponent<AGXUnity.Rendering.ShapeDebugRenderData>( shapeGameObject );
initializeAction( shapeGameObject.GetComponent<T>() );
if ( shapeAsParent ) {
// New parent to shape is filter current parent.
Undo.SetTransformParent( shapeGameObject.transform, data.Filter.transform.parent, "Visual parent as parent to shape" );
Undo.SetTransformParent( data.Filter.transform, shapeGameObject.transform, "Shape as parent to visual" );
}
else
Undo.SetTransformParent( shapeGameObject.transform, data.Filter.transform, "Shape as child to visual" );
// SetTransformParent assigns some scale given the parent. We're in general not
// interested in this scale since it will "un-scale" meshes (and the rest of the
// shapes doesn't support scale so...).
// If mesh and the mesh should be parent to the filter we have to move the
// localScale to the shape game object.
if ( shapeAsParent && typeof( T ) == typeof( Mesh ) ) {
shapeGameObject.transform.localScale = data.Filter.transform.localScale;
data.Filter.transform.localScale = Vector3.one;
}
else
shapeGameObject.transform.localScale = Vector3.one;
return shapeGameObject;
}
private Utils.ShapeCreateButtons m_buttons = new Utils.ShapeCreateButtons();
private List<GameObject> m_selection = new List<GameObject>();
private const string m_visualPrimitiveName = "createShapeVisualPrimitive";
public GameObject Parent { get; private set; }
public Color VisualPrimitiveColor { get; set; }
public string VisualPrimitiveShader { get; set; }
public ShapeCreateTool( GameObject parent )
: base( isSingleInstanceTool: true )
{
Parent = parent;
VisualPrimitiveColor = Color.red;
VisualPrimitiveShader = "Standard";
}
public override void OnAdd()
{
}
public override void OnRemove()
{
Reset();
}
public override void OnSceneViewGUI( SceneView sceneView )
{
if ( Parent == null ) {
PerformRemoveFromParent();
return;
}
if ( HandleKeyEscape( true ) )
return;
// NOTE: Waiting for mouse click!
if ( !Manager.HijackLeftMouseClick() )
return;
var hitResults = Utils.Raycast.IntersectChildren( HandleUtility.GUIPointToWorldRay( Event.current.mousePosition ),
Parent,
null,
true );
// Find target. Ignoring shapes.
GameObject selected = null;
for ( int i = 0; selected == null && i < hitResults.Length; ++i ) {
if ( hitResults[ i ].Target.GetComponent<Shape>() == null )
selected = hitResults[ i ].Target;
}
// Single selection mode.
ClearSelection();
if ( selected != null ) {
m_selection.Add( selected );
// TODO HIGHLIGHT: Add multiple.
//SetVisualizedSelection( selected );
}
else
m_buttons.Reset();
// TODO GUI: Why? Force inspector update instead?
EditorUtility.SetDirty( Parent );
}
public void OnInspectorGUI()
{
if ( HandleKeyEscape( false ) )
return;
var skin = InspectorEditor.Skin;
InspectorGUI.OnDropdownToolBegin( GetCurrentStateInfo() );
UnityEngine.GUI.enabled = m_selection.Count > 0;
m_buttons.OnGUI( Event.current );
UnityEngine.GUI.enabled = true;
InspectorGUI.OnDropdownToolEnd();
EditorUtility.SetDirty( Parent );
// Call this before we exit since it'll remove the visual primitive
// if no shape button currently is selected.
var vp = GetSelectedButtonVisualPrimitive();
if ( m_buttons.Selected == null )
return;
if ( m_selection.Count == 0 || m_buttons.Selected.State.Axis == ShapeInitializationData.Axes.None )
return;
var shapesInitData = ShapeInitializationData.Create( m_selection.ToArray() );
if ( shapesInitData.Length == 0 )
return;
var shapeInitData = shapesInitData[ 0 ];
var axisData = shapeInitData.FindAxisData( m_buttons.Selected.State.Axis, m_buttons.Selected.State.ExpandRadius );
UpdateVisualPrimitive( vp, shapeInitData, axisData );
if ( m_buttons.Selected.State.CreatePressed ) {
if ( m_buttons.Selected.State.ShapeType == ShapeType.Box ) {
CreateShape<Box>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, box =>
{
box.HalfExtents = shapeInitData.LocalExtents;
shapeInitData.SetDefaultPositionRotation( box.gameObject );
} );
}
else if ( m_buttons.Selected.State.ShapeType == ShapeType.Cylinder ) {
CreateShape<Cylinder>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, cylinder =>
{
cylinder.Radius = axisData.Radius;
cylinder.Height = axisData.Height;
shapeInitData.SetPositionRotation( cylinder.gameObject, axisData.Direction );
} );
}
else if ( m_buttons.Selected.State.ShapeType == ShapeType.HollowCylinder ) {
CreateShape<HollowCylinder>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, hollowCylinder =>
{
hollowCylinder.Thickness = axisData.Radius / 10f; // Arbitrary base thickness
hollowCylinder.Radius = axisData.Radius;
hollowCylinder.Height = axisData.Height;
shapeInitData.SetPositionRotation( hollowCylinder.gameObject, axisData.Direction );
} );
}
else if (m_buttons.Selected.State.ShapeType == ShapeType.Cone)
{
CreateShape<Cone>(shapeInitData, m_buttons.Selected.State.ShapeAsParent, cone =>
{
cone.TopRadius = axisData.Radius;
cone.BottomRadius = axisData.Radius;
cone.Height = axisData.Height;
shapeInitData.SetPositionRotation(cone.gameObject, axisData.Direction);
});
}
else if (m_buttons.Selected.State.ShapeType == ShapeType.HollowCone)
{
CreateShape<HollowCone>(shapeInitData, m_buttons.Selected.State.ShapeAsParent, hollowCone =>
{
hollowCone.Thickness = axisData.Radius / 10f; // Arbitrary base thickness
hollowCone.TopRadius = axisData.Radius / 2f; // Arbitrary base top radius
hollowCone.BottomRadius = axisData.Radius;
hollowCone.Height = axisData.Height;
shapeInitData.SetPositionRotation(hollowCone.gameObject, axisData.Direction);
});
}
else if ( m_buttons.Selected.State.ShapeType == ShapeType.Capsule ) {
CreateShape<Capsule>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, capsule =>
{
capsule.Radius = axisData.Radius;
capsule.Height = axisData.Height;
shapeInitData.SetPositionRotation( capsule.gameObject, axisData.Direction );
} );
}
else if ( m_buttons.Selected.State.ShapeType == ShapeType.Sphere ) {
CreateShape<Sphere>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, sphere =>
{
sphere.Radius = axisData.Radius;
shapeInitData.SetPositionRotation( sphere.gameObject, axisData.Direction );
} );
}
else if ( m_buttons.Selected.State.ShapeType == ShapeType.Mesh ) {
CreateShape<Mesh>( shapeInitData, m_buttons.Selected.State.ShapeAsParent, mesh =>
{
mesh.SetSourceObject( shapeInitData.Filter.sharedMesh );
// We don't want to set the position given the center of the bounds
// since we're one-to-one with the mesh filter.
mesh.transform.position = shapeInitData.Filter.transform.position;
mesh.transform.rotation = shapeInitData.Filter.transform.rotation;
} );
}
Reset();
}
}
private string GetCurrentStateInfo()
{
var info = "Create shapes by selecting visual objects in Scene View.\n\n";
if ( m_selection.Count == 0 )
info += "Select highlighted visual object in Scene View" + AwaitingUserActionDots();
else
info += "Choose shape properties or more objects in Scene View" + AwaitingUserActionDots();
return info;
}
private void Reset()
{
m_buttons.Reset();
ClearSelection();
}
private void ClearSelection()
{
m_selection.Clear();
// TODO HIGHLIGHT: Fix.
//ClearVisualizedSelection();
}
private bool HandleKeyEscape( bool isSceneViewUpdate )
{
bool keyEscDown = isSceneViewUpdate ? Manager.KeyEscapeDown : Manager.IsKeyEscapeDown( Event.current );
if ( !keyEscDown )
return false;
if ( isSceneViewUpdate )
Manager.UseKeyEscapeDown();
else
Event.current.Use();
if ( m_buttons.Selected != null )
m_buttons.Selected = null;
else if ( m_selection.Count > 0 )
ClearSelection();
else {
PerformRemoveFromParent();
return true;
}
return false;
}
private Utils.VisualPrimitive GetSelectedButtonVisualPrimitive()
{
Utils.VisualPrimitive vp = GetVisualPrimitive( m_visualPrimitiveName );
if ( m_buttons.Selected == null || m_buttons.Selected.State.Axis == ShapeInitializationData.Axes.None ) {
RemoveVisualPrimitive( m_visualPrimitiveName );
return null;
}
var desiredType = Type.GetType( "AGXUnityEditor.Utils.VisualPrimitive" + m_buttons.Selected.State.ShapeType.ToString() + ", AGXUnityEditor" );
// Desired type doesn't exist - remove current visual primitive if it exists.
if ( desiredType == null ) {
RemoveVisualPrimitive( m_visualPrimitiveName );
return null;
}
// New visual primitive type. Remove old one.
if ( vp != null && vp.GetType() != desiredType ) {
RemoveVisualPrimitive( m_visualPrimitiveName );
vp = null;
}
// Same type as selected button shape type.
if ( vp != null )
return vp;
MethodInfo genericMethod = GetType().GetMethod( "GetOrCreateVisualPrimitive", BindingFlags.NonPublic | BindingFlags.Instance ).MakeGenericMethod( desiredType );
vp = (Utils.VisualPrimitive)genericMethod.Invoke( this, new object[] { m_visualPrimitiveName, VisualPrimitiveShader } );
if ( vp == null )
return null;
vp.Pickable = false;
vp.Color = VisualPrimitiveColor;
return vp;
}
private void UpdateVisualPrimitive( Utils.VisualPrimitive vp, ShapeInitializationData shapeInitData, ShapeInitializationData.AxisData axisData )
{
if ( vp == null )
return;
vp.Visible = shapeInitData != null && axisData != null;
if ( !vp.Visible )
return;
if ( vp is Utils.VisualPrimitiveMesh ) {
vp.Node.transform.localScale = shapeInitData.Filter.transform.lossyScale;
vp.Node.transform.position = shapeInitData.Filter.transform.position;
vp.Node.transform.rotation = shapeInitData.Filter.transform.rotation;
}
else {
vp.Node.transform.localScale = Vector3.one;
vp.Node.transform.position = shapeInitData.WorldCenter;
#if UNITY_2018_1_OR_NEWER
vp.Node.transform.rotation = shapeInitData.Rotation * Quaternion.FromToRotation( Vector3.up, axisData.Direction ).normalized;
#else
vp.Node.transform.rotation = shapeInitData.Rotation * Quaternion.FromToRotation( Vector3.up, axisData.Direction ).Normalize();
#endif
}
if ( vp is Utils.VisualPrimitiveBox )
( vp as Utils.VisualPrimitiveBox ).SetSize( shapeInitData.LocalExtents );
else if ( vp is Utils.VisualPrimitiveCylinder )
( vp as Utils.VisualPrimitiveCylinder ).SetSize( axisData.Radius, axisData.Height );
else if ( vp is Utils.VisualPrimitiveCapsule )
( vp as Utils.VisualPrimitiveCapsule ).SetSize( axisData.Radius, axisData.Height );
else if ( vp is Utils.VisualPrimitiveSphere )
( vp as Utils.VisualPrimitiveSphere ).SetSize( axisData.Radius );
else if ( vp is Utils.VisualPrimitiveMesh )
( vp as Utils.VisualPrimitiveMesh ).SetSourceObject( shapeInitData.Filter.sharedMesh );
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.