context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* InstallContext.cs - Implementation of the
* "System.Configuration.Install.InstallContext" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* 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.Configuration.Install
{
#if !ECMA_COMPAT
using System.IO;
using System.Collections;
using System.Collections.Specialized;
public class InstallContext
{
// Internal state.
private String logFilePath;
private StringDictionary parameters;
// Constructors.
public InstallContext()
{
this.logFilePath = null;
this.parameters = new StringDictionary();
}
public InstallContext(String logFilePath, String[] commandLine)
{
this.logFilePath = logFilePath;
this.parameters = ParseCommandLine(commandLine);
}
internal InstallContext(StringDictionary parameters)
{
this.logFilePath = parameters["logfile"];
this.parameters = parameters;
}
// Get the command-line parameters.
public StringDictionary Parameters
{
get
{
return parameters;
}
}
// Determine if a particular parameter is true.
public bool IsParameterTrue(String paramName)
{
String value = parameters[paramName.ToLower()];
if(value == null)
{
// Special check for "--x" forms of option names.
value = parameters["-" + paramName.ToLower()];
}
if(value == null)
{
return false;
}
else if(String.Compare(value, "true", true) == 0 ||
String.Compare(value, "yes", true) == 0 ||
value == "1" || value == String.Empty)
{
return true;
}
else
{
return false;
}
}
// Write a message to the log file.
public void LogMessage(String message)
{
if(logFilePath != null && message != null)
{
if(IsParameterTrue("LogToConsole"))
{
Console.Write(message);
}
StreamWriter writer = new StreamWriter(logFilePath, true);
writer.Write(message);
writer.Flush();
writer.Close();
}
}
internal void LogLine(String message)
{
if(logFilePath != null && message != null)
{
if(IsParameterTrue("LogToConsole"))
{
Console.WriteLine(message);
}
StreamWriter writer = new StreamWriter(logFilePath, true);
writer.WriteLine(message);
writer.Flush();
writer.Close();
}
}
// Add to a string dictionary, overridding previous values.
private static void Add(StringDictionary dict, String name, String value)
{
if(dict[name] != null)
{
dict.Remove(name);
}
dict[name] = value;
}
// Parse a command line into a string dictionary.
protected static StringDictionary ParseCommandLine(String[] args)
{
StringDictionary dict = new StringDictionary();
if(args != null)
{
int posn = 0;
String str;
while(posn < args.Length)
{
str = args[posn];
if(str.Length > 0 &&
(str[0] == '/' || str[0] == '-'))
{
int index = str.IndexOf('=');
if(index < 0)
{
if((posn + 1) < args.Length &&
args[posn + 1].StartsWith("="))
{
if(args[posn + 1].Length == 1)
{
// Option of the form "/name = value".
if((posn + 2) < args.Length)
{
Add(dict,
str.Substring(1).ToLower(),
"");
++posn;
}
else
{
Add(dict,
str.Substring(1).ToLower(),
args[posn + 2]);
posn += 2;
}
}
else
{
// Option of the form "/name =value".
Add(dict, str.Substring(1).ToLower(),
args[posn + 1].Substring(1));
++posn;
}
}
else
{
// Option of the form "/name".
Add(dict, str.Substring(1).ToLower(), "");
}
}
else if((index + 1) < str.Length &&
(posn + 1) < args.Length)
{
// Option of the form "/name= value".
Add(dict, str.Substring(1, index - 1).ToLower(),
args[posn + 1]);
}
else
{
// Option of the form "/name=value".
Add(dict, str.Substring(1, index - 1).ToLower(),
str.Substring(index + 1));
}
}
++posn;
}
}
return dict;
}
internal static StringDictionary ParseCommandLine
(String[] args, int start, int length, out String[] newArgs)
{
newArgs = new String [length];
Array.Copy(args, start, newArgs, 0, length);
return ParseCommandLine(newArgs);
}
}; // class InstallContext
#endif // !ECMA_COMPAT
}; // namespace System.Configuration.Install
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderLinnCoUkUpdate1 : IDisposable
{
/// <summary>
/// Set the value of the UpdateStatus property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyUpdateStatus(string aValue);
/// <summary>
/// Get a copy of the value of the UpdateStatus property
/// </summary>
/// <returns>Value of the UpdateStatus property.</param>
string PropertyUpdateStatus();
/// <summary>
/// Set the value of the UpdateTopic property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyUpdateTopic(string aValue);
/// <summary>
/// Get a copy of the value of the UpdateTopic property
/// </summary>
/// <returns>Value of the UpdateTopic property.</param>
string PropertyUpdateTopic();
/// <summary>
/// Set the value of the UpdateChannel property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyUpdateChannel(string aValue);
/// <summary>
/// Get a copy of the value of the UpdateChannel property
/// </summary>
/// <returns>Value of the UpdateChannel property.</param>
string PropertyUpdateChannel();
}
/// <summary>
/// Provider for the linn.co.uk:Update:1 UPnP service
/// </summary>
public class DvProviderLinnCoUkUpdate1 : DvProvider, IDisposable, IDvProviderLinnCoUkUpdate1
{
private GCHandle iGch;
private ActionDelegate iDelegatePushManifest;
private ActionDelegate iDelegateSetUpdateFeedParams;
private ActionDelegate iDelegateGetUpdateFeedParams;
private ActionDelegate iDelegateGetUpdateStatus;
private ActionDelegate iDelegateApply;
private ActionDelegate iDelegateRestore;
private PropertyString iPropertyUpdateStatus;
private PropertyString iPropertyUpdateTopic;
private PropertyString iPropertyUpdateChannel;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderLinnCoUkUpdate1(DvDevice aDevice)
: base(aDevice, "linn.co.uk", "Update", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the UpdateStatus property.
/// </summary>
public void EnablePropertyUpdateStatus()
{
List<String> allowedValues = new List<String>();
iPropertyUpdateStatus = new PropertyString(new ParameterString("UpdateStatus", allowedValues));
AddProperty(iPropertyUpdateStatus);
}
/// <summary>
/// Enable the UpdateTopic property.
/// </summary>
public void EnablePropertyUpdateTopic()
{
List<String> allowedValues = new List<String>();
iPropertyUpdateTopic = new PropertyString(new ParameterString("UpdateTopic", allowedValues));
AddProperty(iPropertyUpdateTopic);
}
/// <summary>
/// Enable the UpdateChannel property.
/// </summary>
public void EnablePropertyUpdateChannel()
{
List<String> allowedValues = new List<String>();
allowedValues.Add("release");
allowedValues.Add("beta");
allowedValues.Add("development");
allowedValues.Add("nightly");
iPropertyUpdateChannel = new PropertyString(new ParameterString("UpdateChannel", allowedValues));
AddProperty(iPropertyUpdateChannel);
allowedValues.Clear();
}
/// <summary>
/// Set the value of the UpdateStatus property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateStatus has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyUpdateStatus(string aValue)
{
if (iPropertyUpdateStatus == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyUpdateStatus, aValue);
}
/// <summary>
/// Get a copy of the value of the UpdateStatus property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateStatus has previously been called.</remarks>
/// <returns>Value of the UpdateStatus property.</returns>
public string PropertyUpdateStatus()
{
if (iPropertyUpdateStatus == null)
throw new PropertyDisabledError();
return iPropertyUpdateStatus.Value();
}
/// <summary>
/// Set the value of the UpdateTopic property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateTopic has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyUpdateTopic(string aValue)
{
if (iPropertyUpdateTopic == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyUpdateTopic, aValue);
}
/// <summary>
/// Get a copy of the value of the UpdateTopic property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateTopic has previously been called.</remarks>
/// <returns>Value of the UpdateTopic property.</returns>
public string PropertyUpdateTopic()
{
if (iPropertyUpdateTopic == null)
throw new PropertyDisabledError();
return iPropertyUpdateTopic.Value();
}
/// <summary>
/// Set the value of the UpdateChannel property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateChannel has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyUpdateChannel(string aValue)
{
if (iPropertyUpdateChannel == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyUpdateChannel, aValue);
}
/// <summary>
/// Get a copy of the value of the UpdateChannel property
/// </summary>
/// <remarks>Can only be called if EnablePropertyUpdateChannel has previously been called.</remarks>
/// <returns>Value of the UpdateChannel property.</returns>
public string PropertyUpdateChannel()
{
if (iPropertyUpdateChannel == null)
throw new PropertyDisabledError();
return iPropertyUpdateChannel.Value();
}
/// <summary>
/// Signal that the action PushManifest is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// PushManifest must be overridden if this is called.</remarks>
protected void EnableActionPushManifest()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("PushManifest");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Uri", allowedValues));
iDelegatePushManifest = new ActionDelegate(DoPushManifest);
EnableAction(action, iDelegatePushManifest, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action SetUpdateFeedParams is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// SetUpdateFeedParams must be overridden if this is called.</remarks>
protected void EnableActionSetUpdateFeedParams()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetUpdateFeedParams");
action.AddInputParameter(new ParameterRelated("Topic", iPropertyUpdateTopic));
action.AddInputParameter(new ParameterRelated("Channel", iPropertyUpdateChannel));
iDelegateSetUpdateFeedParams = new ActionDelegate(DoSetUpdateFeedParams);
EnableAction(action, iDelegateSetUpdateFeedParams, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetUpdateFeedParams is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetUpdateFeedParams must be overridden if this is called.</remarks>
protected void EnableActionGetUpdateFeedParams()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetUpdateFeedParams");
action.AddOutputParameter(new ParameterRelated("Topic", iPropertyUpdateTopic));
action.AddOutputParameter(new ParameterRelated("Channel", iPropertyUpdateChannel));
iDelegateGetUpdateFeedParams = new ActionDelegate(DoGetUpdateFeedParams);
EnableAction(action, iDelegateGetUpdateFeedParams, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetUpdateStatus is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetUpdateStatus must be overridden if this is called.</remarks>
protected void EnableActionGetUpdateStatus()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetUpdateStatus");
action.AddOutputParameter(new ParameterRelated("UpdateStatus", iPropertyUpdateStatus));
iDelegateGetUpdateStatus = new ActionDelegate(DoGetUpdateStatus);
EnableAction(action, iDelegateGetUpdateStatus, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Apply is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Apply must be overridden if this is called.</remarks>
protected void EnableActionApply()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Apply");
iDelegateApply = new ActionDelegate(DoApply);
EnableAction(action, iDelegateApply, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Restore is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Restore must be overridden if this is called.</remarks>
protected void EnableActionRestore()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Restore");
iDelegateRestore = new ActionDelegate(DoRestore);
EnableAction(action, iDelegateRestore, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// PushManifest action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// PushManifest action for the owning device.
///
/// Must be implemented iff EnableActionPushManifest was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aUri"></param>
protected virtual void PushManifest(IDvInvocation aInvocation, string aUri)
{
throw (new ActionDisabledError());
}
/// <summary>
/// SetUpdateFeedParams action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// SetUpdateFeedParams action for the owning device.
///
/// Must be implemented iff EnableActionSetUpdateFeedParams was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aTopic"></param>
/// <param name="aChannel"></param>
protected virtual void SetUpdateFeedParams(IDvInvocation aInvocation, string aTopic, string aChannel)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetUpdateFeedParams action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetUpdateFeedParams action for the owning device.
///
/// Must be implemented iff EnableActionGetUpdateFeedParams was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aTopic"></param>
/// <param name="aChannel"></param>
protected virtual void GetUpdateFeedParams(IDvInvocation aInvocation, out string aTopic, out string aChannel)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetUpdateStatus action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetUpdateStatus action for the owning device.
///
/// Must be implemented iff EnableActionGetUpdateStatus was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aUpdateStatus"></param>
protected virtual void GetUpdateStatus(IDvInvocation aInvocation, out string aUpdateStatus)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Apply action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Apply action for the owning device.
///
/// Must be implemented iff EnableActionApply was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
protected virtual void Apply(IDvInvocation aInvocation)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Restore action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Restore action for the owning device.
///
/// Must be implemented iff EnableActionRestore was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
protected virtual void Restore(IDvInvocation aInvocation)
{
throw (new ActionDisabledError());
}
private static int DoPushManifest(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string uri;
try
{
invocation.ReadStart();
uri = invocation.ReadString("Uri");
invocation.ReadEnd();
self.PushManifest(invocation, uri);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "PushManifest");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "PushManifest" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "PushManifest" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "PushManifest" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSetUpdateFeedParams(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string topic;
string channel;
try
{
invocation.ReadStart();
topic = invocation.ReadString("Topic");
channel = invocation.ReadString("Channel");
invocation.ReadEnd();
self.SetUpdateFeedParams(invocation, topic, channel);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "SetUpdateFeedParams");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetUpdateFeedParams" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetUpdateFeedParams" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetUpdateFeedParams" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetUpdateFeedParams(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string topic;
string channel;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetUpdateFeedParams(invocation, out topic, out channel);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetUpdateFeedParams");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetUpdateFeedParams" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetUpdateFeedParams" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Topic", topic);
invocation.WriteString("Channel", channel);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetUpdateFeedParams" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetUpdateStatus(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string updateStatus;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetUpdateStatus(invocation, out updateStatus);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetUpdateStatus");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetUpdateStatus" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetUpdateStatus" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("UpdateStatus", updateStatus);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetUpdateStatus" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoApply(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.Apply(invocation);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Apply");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Apply" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Apply" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Apply" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoRestore(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderLinnCoUkUpdate1 self = (DvProviderLinnCoUkUpdate1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.Restore(invocation);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Restore");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Restore" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Restore" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Restore" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
///Scans the project and warns about the following conditions:
///Audio sources > 16
///Using MSAA levels other than recommended level
///GPU skinning is also probably usually ideal.
///Excessive pixel lights (>1 on Gear VR; >3 on Rift)
///Directional Lightmapping Modes (on Gear; use Non-Directional)
///Preload audio setting on individual audio clips
///Decompressing audio clips on load
///Disabling occlusion mesh
///Android target API level set to 19 or higher
///Unity skybox use (on by default, but if you can't see the skybox switching to Color is much faster on Gear)
///Lights marked as "baked" but that were not included in the last bake (and are therefore realtime).
///Lack of static batching and dynamic batching settings activated.
///Full screen image effects (Gear)
///Warn about large textures that are marked as uncompressed.
///32-bit depth buffer (use 16)
///Use of projectors (Gear; can be used carefully but slow enough to warrant a warning)
///Maybe in the future once quantified: Graphics jobs and IL2CPP on Gear.
///Real-time global illumination
///No texture compression, or non-ASTC texture compression as a global setting (Gear).
///Using deferred rendering
///Excessive texture resolution after LOD bias (>2k on Gear VR; >4k on Rift)
///Not using trilinear or aniso filtering and not generating mipmaps
///Excessive render scale (>1.2)
///Slow physics settings: Sleep Threshold < 0.005, Default Contact Offset < 0.01, Solver Iteration Count > 6
///Shadows on when approaching the geometry or draw call limits
///Non-static objects with colliders that are missing rigidbodies on themselves or in the parent chain.
///No initialization of GPU/CPU throttling settings, or init to dangerous values (-1 or > 3) (Gear)
///Using inefficient effects: SSAO, motion blur, global fog, parallax mapping, etc.
///Too many Overlay layers
///Use of Standard shader or Standard Specular shader on Gear. More generally, excessive use of multipass shaders (legacy specular, etc).
///Multiple cameras with clears (on Gear, potential for excessive fill cost)
///Excessive shader passes (>2)
///Material pointers that have been instanced in the editor (esp. if we could determine that the instance has no deltas from the original)
///Excessive draw calls (>150 on Gear VR; >2000 on Rift)
///Excessive tris or verts (>100k on Gear VR; >1M on Rift)
///Large textures, lots of prefabs in startup scene (for bootstrap optimization)
/// </summary>
public class OVRLint : EditorWindow
{
//TODO: The following require reflection or static analysis.
///Use of ONSP reflections (Gear)
///Use of LoadLevelAsync / LoadLevelAdditiveAsync (on Gear, this kills frame rate so dramatically it's probably better to just go to black and load synchronously)
///Use of Linq in non-editor assemblies (common cause of GCs). Minor: use of foreach.
///Use of Unity WWW (exceptionally high overhead for large file downloads, but acceptable for tiny gets).
///Declared but empty Awake/Start/Update/OnCollisionEnter/OnCollisionExit/OnCollisionStay. Also OnCollision* star methods that declare the Collision argument but do not reference it (omitting it short-circuits the collision contact calculation).
public delegate void FixMethodDelegate(UnityEngine.Object obj, bool isLastInSet, int selectedIndex);
public struct FixRecord
{
public string category;
public string message;
public FixMethodDelegate fixMethod;
public UnityEngine.Object targetObject;
public string[] buttonNames;
public bool complete;
public FixRecord(string cat, string msg, FixMethodDelegate fix, UnityEngine.Object target, string[] buttons)
{
category = cat;
message = msg;
buttonNames = buttons;
fixMethod = fix;
targetObject = target;
complete = false;
}
}
private static List<FixRecord> mRecords = new List<FixRecord>();
private Vector2 mScrollPosition;
[MenuItem("Tools/Oculus/Audit Project for VR Performance Issues")]
static void Init ()
{
// Get existing open window or if none, make a new one:
EditorWindow.GetWindow (typeof (OVRLint));
}
void OnGUI ()
{
GUILayout.Label ("OVR Lint Tool", EditorStyles.boldLabel);
if (GUILayout.Button("Run Lint", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
{
RunCheck();
}
string lastCategory = "";
mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition);
for (int x = 0; x < mRecords.Count; x++)
{
FixRecord record = mRecords[x];
if (!record.category.Equals(lastCategory)) // new category
{
lastCategory = record.category;
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
GUILayout.Label(lastCategory, EditorStyles.label, GUILayout.Width(200));
bool moreThanOne = (x + 1 < mRecords.Count && mRecords[x + 1].category.Equals(lastCategory));
if (record.buttonNames != null && record.buttonNames.Length > 0)
{
if (moreThanOne)
{
GUILayout.Label("Apply to all:", EditorStyles.label, GUILayout.Width(75));
for (int y = 0; y < record.buttonNames.Length; y++)
{
if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(100)))
{
List<FixRecord> recordsToProcess = new List<FixRecord>();
for (int z = x; z < mRecords.Count; z++)
{
FixRecord thisRecord = mRecords[z];
bool isLast = false;
if (z + 1 >= mRecords.Count || !mRecords[z + 1].category.Equals(lastCategory))
{
isLast = true;
}
if (!thisRecord.complete)
{
recordsToProcess.Add(thisRecord);
}
if (isLast)
{
break;
}
}
UnityEngine.Object[] undoObjects = new UnityEngine.Object[recordsToProcess.Count];
for (int z = 0; z < recordsToProcess.Count; z++)
{
undoObjects[z] = recordsToProcess[z].targetObject;
}
Undo.RecordObjects(undoObjects, record.category + " (Multiple)");
for (int z = 0; z < recordsToProcess.Count; z++)
{
FixRecord thisRecord = recordsToProcess[z];
thisRecord.fixMethod(thisRecord.targetObject, (z + 1 == recordsToProcess.Count), y);
thisRecord.complete = true;
}
}
}
}
}
EditorGUILayout.EndHorizontal();
if (moreThanOne || record.targetObject)
{
GUILayout.Label(record.message);
}
}
EditorGUILayout.BeginHorizontal();
GUI.enabled = !record.complete;
if (record.targetObject)
{
EditorGUILayout.ObjectField(record.targetObject, record.targetObject.GetType(), true);
}
else
{
GUILayout.Label(record.message);
}
for (int y = 0; y < record.buttonNames.Length; y++)
{
if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(100)))
{
if (record.targetObject != null)
{
Undo.RecordObject(record.targetObject, record.category);
}
record.fixMethod(record.targetObject, true, y);
record.complete = true;
}
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
}
static void RunCheck()
{
mRecords.Clear();
CheckStaticCommonIssues();
#if UNITY_ANDROID
CheckStaticAndroidIssues();
#endif
if (EditorApplication.isPlaying)
{
CheckRuntimeCommonIssues();
#if UNITY_ANDROID
CheckRuntimeAndroidIssues();
#endif
}
mRecords.Sort(delegate(FixRecord record1, FixRecord record2)
{
return record1.category.CompareTo(record2.category);
});
}
static void AddFix(string category, string message, FixMethodDelegate method, UnityEngine.Object target, params string[] buttons)
{
mRecords.Add(new FixRecord(category, message, method, target, buttons));
}
static void CheckStaticCommonIssues ()
{
if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable)
{
AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal quality and performance.", delegate(UnityEngine.Object obj, bool last, int selected)
{
QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable;
}, null, "Fix");
}
#if UNITY_ANDROID
int recommendedPixelLightCount = 1;
#else
int recommendedPixelLightCount = 3;
#endif
if (QualitySettings.pixelLightCount > recommendedPixelLightCount)
{
AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate(UnityEngine.Object obj, bool last, int selected)
{
QualitySettings.pixelLightCount = recommendedPixelLightCount;
}, null, "Fix");
}
if (!PlayerSettings.gpuSkinning)
{
AddFix ("Optimize GPU Skinning", "For CPU performance, please use GPU skinning.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.gpuSkinning = true;
}, null, "Fix");
}
#if UNITY_5_4_OR_NEWER
// Should we recommend this? Seems to be mutually exclusive w/ dynamic batching.
if (!PlayerSettings.graphicsJobs)
{
AddFix ("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.graphicsJobs = true;
}, null, "Fix");
}
#endif
#if UNITY_2017_2_OR_NEWER
if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android)))
#else
if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering))
#endif
{
AddFix ("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate(UnityEngine.Object obj, bool last, int selected)
{
#if UNITY_2017_2_OR_NEWER
PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true);
PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);
#else
PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true;
#endif
}, null, "Fix");
}
#if UNITY_5_5_OR_NEWER
BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup;
var tier = UnityEngine.Rendering.GraphicsTier.Tier1;
var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier);
if ((tierSettings.renderingPath == RenderingPath.DeferredShading ||
tierSettings.renderingPath == RenderingPath.DeferredLighting))
{
AddFix ("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected)
{
tierSettings.renderingPath = RenderingPath.Forward;
UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings);
}, null, "Use Forward");
}
#else
if (PlayerSettings.renderingPath == RenderingPath.DeferredShading ||
PlayerSettings.renderingPath == RenderingPath.DeferredLighting ||
PlayerSettings.mobileRenderingPath == RenderingPath.DeferredShading ||
PlayerSettings.mobileRenderingPath == RenderingPath.DeferredLighting)
{
AddFix ("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.renderingPath = PlayerSettings.mobileRenderingPath = RenderingPath.Forward;
}, null, "Use Forward");
}
#endif
#if UNITY_5_5_OR_NEWER
if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass)
{
AddFix ("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing;
}, null, "Fix");
}
#elif UNITY_5_4_OR_NEWER
if (!PlayerSettings.singlePassStereoRendering)
{
AddFix ("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.singlePassStereoRendering = true;
}, null, "Enable Single-Pass");
}
#endif
if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional)
{
AddFix ("Optimize Lightmap Directionality", "For GPU performance, please don't use directional lightmaps.", delegate(UnityEngine.Object obj, bool last, int selected)
{
LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional;
}, null, "Switch Lightmap Mode");
}
#if UNITY_5_4_OR_NEWER
if (Lightmapping.realtimeGI)
{
AddFix ("Optimize Realtime GI", "For GPU performance, please don't use real-time global illumination. (Set Lightmapping.realtimeGI = false.)", delegate(UnityEngine.Object obj, bool last, int selected)
{
Lightmapping.realtimeGI = false;
}, null, "Disable Realtime GI");
}
#endif
var lights = GameObject.FindObjectsOfType<Light> ();
for (int i = 0; i < lights.Length; ++i)
{
#if UNITY_5_4_OR_NEWER
if (lights [i].type != LightType.Directional && !lights [i].isBaked && IsLightBaked(lights[i]))
{
AddFix ("Optimize Light Baking", "For GPU performance, please bake lightmaps to avoid realtime lighting cost.", delegate(UnityEngine.Object obj, bool last, int selected)
{
if (last)
{
Lightmapping.Bake ();
}
}, lights[i], "Bake Lightmaps");
}
#endif
if (lights [i].shadows != LightShadows.None && !IsLightBaked(lights[i]))
{
AddFix ("Optimize Shadows", "For CPU performance, please disable shadows on realtime lights.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Light thisLight = (Light)obj;
thisLight.shadows = LightShadows.None;
}, lights [i], "Disable Shadows");
}
}
/*
// CP: I think this should modify the max number of simultaneous voices in the audio settings rather than
// the number of sources. Sources don't cost anything if they aren't playing simultaneously.
// Couldn't figure out if there's an API for max voices.
var sources = GameObject.FindObjectsOfType<AudioSource> ();
if (sources.Length > 16 &&
EditorUtility.DisplayDialog ("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", "Use recommended", "Skip")) {
Array.Sort(sources, (a, b) => { return a.priority.CompareTo(b.priority); });
for (int i = 16; i < sources.Length; ++i) {
sources[i].enabled = false;
}
}
*/
var clips = GameObject.FindObjectsOfType<AudioClip> ();
for (int i = 0; i < clips.Length; ++i)
{
if (clips [i].loadType == AudioClipLoadType.DecompressOnLoad)
{
AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate(UnityEngine.Object obj, bool last, int selected)
{
AudioClip thisClip = (AudioClip)obj;
if (selected == 0)
{
SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last);
}
else
{
SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last);
}
}, clips [i], "Change to Compressed in Memory", "Change to Streaming");
}
if (clips [i].preloadAudioData)
{
AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate(UnityEngine.Object obj, bool last, int selected)
{
SetAudioPreload(clips[i], false, last);
}, clips [i], "Fix");
}
}
if (Physics.defaultContactOffset < 0.01f)
{
AddFix ("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Physics.defaultContactOffset = 0.01f;
}, null, "Fix");
}
if (Physics.sleepThreshold < 0.005f)
{
AddFix ("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Physics.sleepThreshold = 0.005f;
}, null, "Fix");
}
#if UNITY_5_4_OR_NEWER
if (Physics.defaultSolverIterations > 8)
{
AddFix ("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Physics.defaultSolverIterations = 8;
}, null, "Fix");
}
#endif
var colliders = GameObject.FindObjectsOfType<Collider> ();
for (int i = 0; i < colliders.Length; ++i)
{
// CP: unsure when attachedRigidbody is init'd, so search parents to be sure.
if (!colliders [i].gameObject.isStatic && colliders [i].attachedRigidbody == null && colliders[i].GetComponent<Rigidbody>() == null && FindComponentInParents<Rigidbody>(colliders[i].gameObject) == null)
{
AddFix ("Optimize Nonstatic Collider", "For CPU performance, please make static or attach a Rigidbody to non-static colliders.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Collider thisCollider = (Collider)obj;
if (selected == 0)
{
thisCollider.gameObject.isStatic = true;
}
else
{
var rb = thisCollider.gameObject.AddComponent<Rigidbody> ();
rb.isKinematic = true;
}
}, colliders[i], "Make Static", "Add Rigidbody");
}
}
var materials = Resources.FindObjectsOfTypeAll<Material> ();
for (int i = 0; i < materials.Length; ++i)
{
if (materials [i].shader.name.Contains ("Parallax") || materials [i].IsKeywordEnabled ("_PARALLAXMAP"))
{
AddFix ("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Material thisMaterial = (Material)obj;
if (thisMaterial.IsKeywordEnabled ("_PARALLAXMAP"))
{
thisMaterial.DisableKeyword ("_PARALLAXMAP");
}
if (thisMaterial.shader.name.Contains ("Parallax"))
{
var newName = thisMaterial.shader.name.Replace ("-ParallaxSpec", "-BumpSpec");
newName = newName.Replace ("-Parallax", "-Bump");
var newShader = Shader.Find (newName);
if (newShader)
{
thisMaterial.shader = newShader;
}
else
{
Debug.LogWarning ("Unable to find a replacement for shader " + materials [i].shader.name);
}
}
}, materials[i], "Fix");
}
}
var renderers = GameObject.FindObjectsOfType<Renderer> ();
for (int i = 0; i < renderers.Length; ++i)
{
if (renderers [i].sharedMaterial == null)
{
AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers [i]);
}
}
var overlays = GameObject.FindObjectsOfType<OVROverlay> ();
if (overlays.Length > 4)
{
AddFix ("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate(UnityEngine.Object obj, bool last, int selected)
{
for (int i = 4; i < OVROverlay.instances.Length; ++i)
{
OVROverlay.instances[i].enabled = false;
}
}, null, "Fix");
}
}
static void CheckRuntimeCommonIssues()
{
if (!OVRPlugin.occlusionMesh)
{
AddFix ("Optimize Occlusion Mesh", "For GPU performance, please use occlusion mesh.", delegate(UnityEngine.Object obj, bool last, int selected)
{
OVRPlugin.occlusionMesh = true;
}, null, "Fix");
}
if (OVRManager.instance != null && !OVRManager.instance.useRecommendedMSAALevel)
{
AddFix("Optimize MSAA", "OVRManager can select the optimal antialiasing for the installed hardware at runtime. Recommend enabling this.", delegate(UnityEngine.Object obj, bool last, int selected)
{
OVRManager.instance.useRecommendedMSAALevel = true;
}, null, "Fix");
}
if (UnityEngine.VR.VRSettings.renderScale > 1.5)
{
AddFix ("Optimize Render Scale", "For CPU performance, please don't use render scale over 1.5.", delegate(UnityEngine.Object obj, bool last, int selected)
{
UnityEngine.VR.VRSettings.renderScale = 1.5f;
}, null, "Fix");
}
}
static void CheckStaticAndroidIssues ()
{
AndroidSdkVersions recommendedAndroidSdkVersion = AndroidSdkVersions.AndroidApiLevel19;
if ((int)PlayerSettings.Android.minSdkVersion < (int)recommendedAndroidSdkVersion)
{
AddFix ("Optimize Android API Level", "To avoid legacy work-arounds, please require at least API level " + (int)recommendedAndroidSdkVersion, delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.Android.minSdkVersion = recommendedAndroidSdkVersion;
}, null, "Fix");
}
if (RenderSettings.skybox)
{
AddFix ("Optimize Clearing", "For GPU performance, please don't use Unity's built-in Skybox.", delegate(UnityEngine.Object obj, bool last, int selected)
{
RenderSettings.skybox = null;
}, null, "Clear Skybox");
}
var materials = Resources.FindObjectsOfTypeAll<Material> ();
for (int i = 0; i < materials.Length; ++i)
{
if (materials [i].IsKeywordEnabled ("_SPECGLOSSMAP") || materials [i].IsKeywordEnabled ("_METALLICGLOSSMAP"))
{
AddFix ("Optimize Specular Material", "For GPU performance, please don't use specular shader on materials.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Material thisMaterial = (Material)obj;
thisMaterial.DisableKeyword ("_SPECGLOSSMAP");
thisMaterial.DisableKeyword ("_METALLICGLOSSMAP");
}, materials[i], "Fix");
}
if (materials [i].passCount > 1)
{
AddFix ("Material Passes", "Please use 2 or fewer passes in materials.", null, materials[i]);
}
}
#if UNITY_5_5_OR_NEWER
ScriptingImplementation backend = PlayerSettings.GetScriptingBackend(UnityEditor.BuildTargetGroup.Android);
if (backend != UnityEditor.ScriptingImplementation.IL2CPP)
{
AddFix ("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.SetScriptingBackend(UnityEditor.BuildTargetGroup.Android, UnityEditor.ScriptingImplementation.IL2CPP);
}, null, "Fix");
}
#else
ScriptingImplementation backend = (ScriptingImplementation)PlayerSettings.GetPropertyInt("ScriptingBackend", UnityEditor.BuildTargetGroup.Android);
if (backend != UnityEditor.ScriptingImplementation.IL2CPP)
{
AddFix ("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate(UnityEngine.Object obj, bool last, int selected)
{
PlayerSettings.SetPropertyInt("ScriptingBackend", (int)UnityEditor.ScriptingImplementation.IL2CPP, UnityEditor.BuildTargetGroup.Android);
}, null, "Fix");
}
#endif
var monoBehaviours = GameObject.FindObjectsOfType<MonoBehaviour> ();
System.Type effectBaseType = System.Type.GetType ("UnityStandardAssets.ImageEffects.PostEffectsBase");
if (effectBaseType != null)
{
for (int i = 0; i < monoBehaviours.Length; ++i)
{
if (monoBehaviours [i].GetType ().IsSubclassOf (effectBaseType))
{
AddFix ("Image Effects", "Please don't use image effects.", null, monoBehaviours[i]);
}
}
}
var textures = Resources.FindObjectsOfTypeAll<Texture2D> ();
int maxTextureSize = 1024 * (1 << QualitySettings.masterTextureLimit);
maxTextureSize = maxTextureSize * maxTextureSize;
for (int i = 0; i < textures.Length; ++i)
{
if (textures [i].filterMode == FilterMode.Trilinear && textures [i].mipmapCount == 1)
{
AddFix ("Optimize Texture Filtering", "For GPU performance, please generate mipmaps or disable trilinear filtering for textures.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Texture2D thisTexture = (Texture2D)obj;
if (selected == 0)
{
thisTexture.filterMode = FilterMode.Bilinear;
}
else
{
SetTextureUseMips(thisTexture, true, last);
}
}, textures[i], "Switch to Bilinear", "Generate Mipmaps");
}
}
var projectors = GameObject.FindObjectsOfType<Projector> ();
if (projectors.Length > 0)
{
AddFix ("Optimize Projectors", "For GPU performance, please don't use projectors.", delegate(UnityEngine.Object obj, bool last, int selected)
{
Projector[] thisProjectors = GameObject.FindObjectsOfType<Projector> ();
for (int i = 0; i < thisProjectors.Length; ++i)
{
thisProjectors[i].enabled = false;
}
}, null, "Disable Projectors");
}
if (EditorUserBuildSettings.androidBuildSubtarget != MobileTextureSubtarget.ASTC)
{
AddFix ("Optimize Texture Compression", "For GPU performance, please use ASTC.", delegate(UnityEngine.Object obj, bool last, int selected)
{
EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC;
}, null, "Fix");
}
var cameras = GameObject.FindObjectsOfType<Camera> ();
int clearCount = 0;
for (int i = 0; i < cameras.Length; ++i)
{
if (cameras [i].clearFlags != CameraClearFlags.Nothing && cameras [i].clearFlags != CameraClearFlags.Depth)
++clearCount;
}
if (clearCount > 2)
{
AddFix ("Camera Clears", "Please use 2 or fewer clears.", null, null);
}
}
static void CheckRuntimeAndroidIssues()
{
if (UnityStats.usedTextureMemorySize + UnityStats.vboTotalBytes > 1000000)
{
AddFix ("Graphics Memory", "Please use less than 1GB of vertex and texture memory.", null, null);
}
if (OVRManager.cpuLevel < 0 || OVRManager.cpuLevel > 3)
{
AddFix ("Optimize CPU level", "For battery life, please use a safe CPU level.", delegate(UnityEngine.Object obj, bool last, int selected)
{
OVRManager.cpuLevel = 2;
}, null, "Set to CPU2");
}
if (OVRManager.gpuLevel < 0 || OVRManager.gpuLevel > 3)
{
AddFix ("Optimize GPU level", "For battery life, please use a safe GPU level.", delegate(UnityEngine.Object obj, bool last, int selected)
{
OVRManager.gpuLevel = 2;
}, null, "Set to GPU2");
}
if (UnityStats.triangles > 100000 || UnityStats.vertices > 100000)
{
AddFix ("Triangles and Verts", "Please use less than 100000 triangles or vertices.", null, null);
}
// Warn for 50 if in non-VR mode?
if (UnityStats.drawCalls > 100)
{
AddFix ("Draw Calls", "Please use less than 100 draw calls.", null, null);
}
}
enum LightmapType {Realtime = 4, Baked = 2, Mixed = 1};
static bool IsLightBaked(Light light)
{
#if UNITY_5_6_OR_NEWER
return light.lightmapBakeType == LightmapBakeType.Baked;
#elif UNITY_5_5_OR_NEWER
return light.lightmappingMode == LightmappingMode.Baked;
#else
SerializedObject serialObj = new SerializedObject(light);
SerializedProperty lightmapProp = serialObj.FindProperty("m_Lightmapping");
return (LightmapType)lightmapProp.intValue == LightmapType.Baked;
#endif
}
static void SetAudioPreload( AudioClip clip, bool preload, bool refreshImmediately)
{
if ( clip != null )
{
string assetPath = AssetDatabase.GetAssetPath( clip );
AudioImporter importer = AssetImporter.GetAtPath( assetPath ) as AudioImporter;
if (importer != null)
{
if (preload != importer.preloadAudioData)
{
importer.preloadAudioData = preload;
AssetDatabase.ImportAsset( assetPath );
if (refreshImmediately)
{
AssetDatabase.Refresh();
}
}
}
}
}
static void SetAudioLoadType( AudioClip clip, AudioClipLoadType loadType, bool refreshImmediately)
{
if ( clip != null )
{
string assetPath = AssetDatabase.GetAssetPath( clip );
AudioImporter importer = AssetImporter.GetAtPath( assetPath ) as AudioImporter;
if (importer != null)
{
if (loadType != importer.defaultSampleSettings.loadType)
{
AudioImporterSampleSettings settings = importer.defaultSampleSettings;
settings.loadType = loadType;
importer.defaultSampleSettings = settings;
AssetDatabase.ImportAsset( assetPath );
if (refreshImmediately)
{
AssetDatabase.Refresh();
}
}
}
}
}
public static void SetTextureUseMips( Texture texture, bool useMips, bool refreshImmediately)
{
if ( texture != null )
{
string assetPath = AssetDatabase.GetAssetPath( texture );
TextureImporter tImporter = AssetImporter.GetAtPath( assetPath ) as TextureImporter;
if ( tImporter != null && tImporter.mipmapEnabled != useMips)
{
tImporter.mipmapEnabled = useMips;
AssetDatabase.ImportAsset( assetPath );
if (refreshImmediately)
{
AssetDatabase.Refresh();
}
}
}
}
static T FindComponentInParents<T>(GameObject obj) where T : Component
{
T component = null;
if (obj != null)
{
Transform parent = obj.transform.parent;
if (parent != null)
{
do
{
component = parent.GetComponent(typeof(T)) as T;
parent = parent.parent;
} while (parent != null && component == null);
}
}
return component;
}
}
#endif
| |
// jQueryDataHttpRequest.cs
// Script#/Libraries/jQuery/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Net;
using System.Runtime.CompilerServices;
using System.Xml;
namespace jQueryApi {
/// <summary>
/// Represents an XMLHttpRequest object as a deferred object.
/// </summary>
[ScriptImport]
[ScriptIgnoreNamespace]
public sealed class jQueryDataHttpRequest<TData> : IDeferred<TData> {
private jQueryDataHttpRequest() {
}
/// <summary>
/// The ready state property of the XmlHttpRequest object.
/// </summary>
[ScriptField]
public ReadyState ReadyState {
get {
return ReadyState.Uninitialized;
}
}
/// <summary>
/// The XML document for an XML response.
/// </summary>
[ScriptField]
[ScriptName("responseXML")]
public XmlDocument ResponseXml {
get {
return null;
}
}
/// <summary>
/// The text of the response.
/// </summary>
[ScriptField]
public string ResponseText {
get {
return null;
}
}
/// <summary>
/// The status code associated with the response.
/// </summary>
[ScriptField]
public int Status {
get {
return 0;
}
}
/// <summary>
/// The status text of the response.
/// </summary>
[ScriptField]
public string StatusText {
get {
return null;
}
}
/// <summary>
/// Aborts the request.
/// </summary>
public void Abort() {
}
/// <summary>
/// Add handlers to be called when the request completes or fails.
/// </summary>
/// <param name="callbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Always(params Action[] callbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request completes or fails.
/// </summary>
/// <param name="callbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Always(params Action<TData>[] callbacks) {
return null;
}
/// <summary>
/// Adds a callback to handle completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Complete(AjaxCompletedCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is successfully completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Done(params Action[] doneCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is successfully completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Done(params Action<TData>[] doneCallbacks) {
return null;
}
/// <summary>
/// Adds a callback to handle an error completing the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Error(AjaxErrorCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request errors. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="failCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Fail(params Action[] failCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request errors. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="failCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Fail(params Action<TData>[] failCallbacks) {
return null;
}
/// <summary>
/// Gets the response headers associated with the request.
/// </summary>
/// <returns>The response headers.</returns>
public string GetAllResponseHeaders() {
return null;
}
/// <summary>
/// Gets a specific response header associated with the request.
/// </summary>
/// <param name="name">The name of the response header.</param>
/// <returns>The response header value.</returns>
public string GetResponseHeader(string name) {
return null;
}
/// <summary>
/// Sets the mime type on the request.
/// </summary>
/// <param name="type">The mime type to use.</param>
public void OverrideMimeType(string type) {
}
/// <summary>
/// Filters or chains the result of the request.
/// </summary>
/// <param name="successFilter">The filter to invoke when the request successfully completes.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) {
return null;
}
/// <summary>
/// Filters or chains the result of the request.
/// </summary>
/// <param name="successFilter">The filter to invoke when the request successfully completes.</param>
/// <param name="failFilter">The filter to invoke when the request fails.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) {
return null;
}
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(Func<TData, jQueryDataHttpRequest<TTargetData>> successChain) {
return null;
}
/// <summary>
/// Sets a request header value.
/// </summary>
/// <param name="name">The name of the request header.</param>
/// <param name="value">The value of the request header.</param>
public void SetRequestHeader(string name, string value) {
}
/// <summary>
/// Adds a callback to handle a successful completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Success(AjaxCallback<TData> callback) {
return null;
}
/// <summary>
/// Adds a callback to handle a successful completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Success(AjaxRequestCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallback">The callback to invoke when the request completes successfully.</param>
/// <param name="failCallback">The callback to invoke when the request completes with an error.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Then(Action doneCallback, Action failCallback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallback">The callback to invoke when the request completes successfully.</param>
/// <param name="failCallback">The callback to invoke when the request completes with an error.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Then(Action<TData> doneCallback, Action<TData> failCallback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param>
/// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param>
/// <returns>The current deferred object.</returns>
public jQueryDataHttpRequest<TData> Then(Action[] doneCallbacks, Action[] failCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param>
/// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param>
/// <returns>The current deferred object.</returns>
public jQueryDataHttpRequest<TData> Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) {
return null;
}
#region Implementation of IDeferred
IDeferred<TData> IDeferred<TData>.Always(params Action[] callbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Always(params Action<TData>[] callbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Done(params Action[] doneCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Done(params Action<TData>[] doneCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Fail(params Action[] failCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Fail(params Action<TData>[] failCallbacks) {
return null;
}
bool IDeferred<TData>.IsRejected() {
return false;
}
bool IDeferred<TData>.IsResolved() {
return false;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(Func<TData, IDeferred<TTargetData>> successFilter) {
return null;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) {
return null;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action doneCallback, Action failCallback) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action<TData> doneCallback, Action<TData> failCallback) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action[] doneCallbacks, Action[] failCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) {
return null;
}
#endregion
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Text;
using NodaTime.Utility;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using static NodaTime.NodaConstants;
namespace NodaTime
{
/// <summary>
/// Represents an instant on the global timeline, with nanosecond resolution.
/// </summary>
/// <remarks>
/// <para>
/// An <see cref="Instant"/> has no concept of a particular time zone or calendar: it simply represents a point in
/// time that can be globally agreed-upon.
/// </para>
/// <para>
/// Equality and ordering comparisons are defined in the natural way, with earlier points on the timeline
/// being considered "less than" later points.
/// </para>
/// </remarks>
/// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety>
[TypeConverter(typeof(InstantTypeConverter))]
[XmlSchemaProvider(nameof(AddSchema))]
public readonly struct Instant : IEquatable<Instant>, IComparable<Instant>, IFormattable, IComparable, IXmlSerializable
{
// These correspond to -9998-01-01 and 9999-12-31 respectively.
internal const int MinDays = -4371222;
internal const int MaxDays = 2932896;
private const long MinTicks = MinDays * TicksPerDay;
private const long MaxTicks = (MaxDays + 1) * TicksPerDay - 1;
private const long MinMilliseconds = MinDays * (long) MillisecondsPerDay;
private const long MaxMilliseconds = (MaxDays + 1) * (long) MillisecondsPerDay - 1;
private const long MinSeconds = MinDays * (long) SecondsPerDay;
private const long MaxSeconds = (MaxDays + 1) * (long) SecondsPerDay - 1;
/// <summary>
/// Represents the smallest possible <see cref="Instant"/>.
/// </summary>
/// <remarks>This value is equivalent to -9998-01-01T00:00:00Z</remarks>
public static Instant MinValue { get; } = new Instant(MinDays, 0);
/// <summary>
/// Represents the largest possible <see cref="Instant"/>.
/// </summary>
/// <remarks>This value is equivalent to 9999-12-31T23:59:59.999999999Z</remarks>
public static Instant MaxValue { get; } = new Instant(MaxDays, NanosecondsPerDay - 1);
/// <summary>
/// Instant which is invalid *except* for comparison purposes; it is earlier than any valid value.
/// This must never be exposed.
/// </summary>
internal static readonly Instant BeforeMinValue = new Instant(Duration.MinDays, deliberatelyInvalid: true);
/// <summary>
/// Instant which is invalid *except* for comparison purposes; it is later than any valid value.
/// This must never be exposed.
/// </summary>
internal static readonly Instant AfterMaxValue = new Instant(Duration.MaxDays, deliberatelyInvalid: true);
/// <summary>
/// Time elapsed since the Unix epoch.
/// </summary>
private readonly Duration duration;
/// <summary>
/// Constructor which should *only* be used to construct the invalid instances.
/// </summary>
private Instant([Trusted] int days, bool deliberatelyInvalid)
{
this.duration = new Duration(days, 0);
}
/// <summary>
/// Constructor which constructs a new instance with the given duration, which
/// is trusted to be valid. Should only be called from FromTrustedDuration and
/// FromUntrustedDuration.
/// </summary>
private Instant([Trusted] Duration duration)
{
this.duration = duration;
}
internal Instant([Trusted] int days, [Trusted] long nanoOfDay)
{
Preconditions.DebugCheckArgumentRange(nameof(days), days, MinDays, MaxDays);
Preconditions.DebugCheckArgumentRange(nameof(nanoOfDay), nanoOfDay, 0, NanosecondsPerDay - 1);
duration = new Duration(days, nanoOfDay);
}
/// <summary>
/// Creates an Instant with the given duration, with no validation (in release mode).
/// </summary>
internal static Instant FromTrustedDuration([Trusted] Duration duration)
{
Preconditions.DebugCheckArgumentRange(nameof(duration), duration.FloorDays, MinDays, MaxDays);
return new Instant(duration);
}
/// <summary>
/// Creates an Instant with the given duration, validating that it has a suitable
/// "day" part. (It is assumed that the nanoOfDay is okay.)
/// </summary>
internal static Instant FromUntrustedDuration(Duration duration)
{
int days = duration.FloorDays;
if (days < MinDays || days > MaxDays)
{
throw new OverflowException("Operation would overflow range of Instant");
}
return new Instant(duration);
}
/// <summary>
/// Returns whether or not this is a valid instant. Returns true for all but
/// <see cref="BeforeMinValue"/> and <see cref="AfterMaxValue"/>.
/// </summary>
internal bool IsValid => DaysSinceEpoch >= MinDays && DaysSinceEpoch <= MaxDays;
/// <summary>
/// Get the elapsed time since the Unix epoch, to nanosecond resolution.
/// </summary>
/// <returns>The elapsed time since the Unix epoch.</returns>
internal Duration TimeSinceEpoch => duration;
/// <summary>
/// Number of days since the local unix epoch.
/// </summary>
internal int DaysSinceEpoch => duration.FloorDays;
/// <summary>
/// Nanosecond within the day.
/// </summary>
internal long NanosecondOfDay => duration.NanosecondOfFloorDay;
#region IComparable<Instant> and IComparable Members
/// <summary>
/// Compares the current object with another object of the same type.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// <list type = "table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>< 0</term>
/// <description>This object is less than the <paramref name = "other" /> parameter.</description>
/// </item>
/// <item>
/// <term>0</term>
/// <description>This object is equal to <paramref name = "other" />.</description>
/// </item>
/// <item>
/// <term>> 0</term>
/// <description>This object is greater than <paramref name = "other" />.</description>
/// </item>
/// </list>
/// </returns>
public int CompareTo(Instant other) => duration.CompareTo(other.duration);
/// <summary>
/// Implementation of <see cref="IComparable.CompareTo"/> to compare two instants.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <remarks>
/// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred.
/// </remarks>
/// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="Instant"/>.</exception>
/// <param name="obj">The object to compare this value with.</param>
/// <returns>The result of comparing this instant with another one; see <see cref="CompareTo(NodaTime.Instant)"/> for general details.
/// If <paramref name="obj"/> is null, this method returns a value greater than 0.
/// </returns>
int IComparable.CompareTo(object obj)
{
if (obj is null)
{
return 1;
}
Preconditions.CheckArgument(obj is Instant, nameof(obj), "Object must be of type NodaTime.Instant.");
return CompareTo((Instant) obj);
}
#endregion
#region Object overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => obj is Instant other && Equals(other);
/// <summary>
/// Returns a hash code for this instance.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode() => duration.GetHashCode();
#endregion // Object overrides
/// <summary>
/// Returns a new value of this instant with the given number of ticks added to it.
/// </summary>
/// <param name="ticks">The ticks to add to this instant to create the return value.</param>
/// <returns>The result of adding the given number of ticks to this instant.</returns>
[Pure]
public Instant PlusTicks(long ticks) => FromUntrustedDuration(duration + Duration.FromTicks(ticks));
/// <summary>
/// Returns a new value of this instant with the given number of nanoseconds added to it.
/// </summary>
/// <param name="nanoseconds">The nanoseconds to add to this instant to create the return value.</param>
/// <returns>The result of adding the given number of ticks to this instant.</returns>
[Pure]
public Instant PlusNanoseconds(long nanoseconds) => FromUntrustedDuration(duration + Duration.FromNanoseconds(nanoseconds));
#region Operators
/// <summary>
/// Implements the operator + (addition) for <see cref="Instant" /> + <see cref="Duration" />.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Instant" /> representing the sum of the given values.</returns>
public static Instant operator +(Instant left, Duration right) => FromUntrustedDuration(left.duration + right);
/// <summary>
/// Adds the given offset to this instant, to return a <see cref="LocalInstant" />.
/// A positive offset indicates that the local instant represents a "later local time" than the UTC
/// representation of this instant.
/// </summary>
/// <remarks>
/// This was previously an operator+ implementation, but operators can't be internal.
/// </remarks>
/// <param name="offset">The right hand side of the operator.</param>
/// <returns>A new <see cref="LocalInstant" /> representing the sum of the given values.</returns>
[Pure]
internal LocalInstant Plus(Offset offset) => new LocalInstant(duration.PlusSmallNanoseconds(offset.Nanoseconds));
/// <summary>
/// Adds the given offset to this instant, either returning a normal LocalInstant,
/// or <see cref="LocalInstant.BeforeMinValue"/> or <see cref="LocalInstant.AfterMaxValue"/>
/// if the value would overflow.
/// </summary>
/// <param name="offset"></param>
/// <returns></returns>
internal LocalInstant SafePlus(Offset offset)
{
int days = duration.FloorDays;
// If we can do the arithmetic safely, do so.
if (days > MinDays && days < MaxDays)
{
return Plus(offset);
}
// Handle BeforeMinValue and BeforeMaxValue simply.
if (days < MinDays)
{
return LocalInstant.BeforeMinValue;
}
if (days > MaxDays)
{
return LocalInstant.AfterMaxValue;
}
// Okay, do the arithmetic as a Duration, then check the result for overflow, effectively.
var asDuration = duration.PlusSmallNanoseconds(offset.Nanoseconds);
if (asDuration.FloorDays < Instant.MinDays)
{
return LocalInstant.BeforeMinValue;
}
if (asDuration.FloorDays > Instant.MaxDays)
{
return LocalInstant.AfterMaxValue;
}
return new LocalInstant(asDuration);
}
/// <summary>
/// Adds a duration to an instant. Friendly alternative to <c>operator+()</c>.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Instant" /> representing the sum of the given values.</returns>
public static Instant Add(Instant left, Duration right) => left + right;
/// <summary>
/// Returns the result of adding a duration to this instant, for a fluent alternative to <c>operator+()</c>.
/// </summary>
/// <param name="duration">The duration to add</param>
/// <returns>A new <see cref="Instant" /> representing the result of the addition.</returns>
[Pure]
public Instant Plus(Duration duration) => this + duration;
/// <summary>
/// Implements the operator - (subtraction) for <see cref="Instant" /> - <see cref="Instant" />.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Duration" /> representing the difference of the given values.</returns>
public static Duration operator -(Instant left, Instant right) => left.duration - right.duration;
/// <summary>
/// Implements the operator - (subtraction) for <see cref="Instant" /> - <see cref="Duration" />.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Instant" /> representing the difference of the given values.</returns>
public static Instant operator -(Instant left, Duration right) => FromUntrustedDuration(left.duration - right);
/// <summary>
/// Subtracts one instant from another. Friendly alternative to <c>operator-()</c>.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Duration" /> representing the difference of the given values.</returns>
public static Duration Subtract(Instant left, Instant right) => left - right;
/// <summary>
/// Returns the result of subtracting another instant from this one, for a fluent alternative to <c>operator-()</c>.
/// </summary>
/// <param name="other">The other instant to subtract</param>
/// <returns>A new <see cref="Instant" /> representing the result of the subtraction.</returns>
[Pure]
public Duration Minus(Instant other) => this - other;
/// <summary>
/// Subtracts a duration from an instant. Friendly alternative to <c>operator-()</c>.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns>A new <see cref="Instant" /> representing the difference of the given values.</returns>
[Pure]
public static Instant Subtract(Instant left, Duration right) => left - right;
/// <summary>
/// Returns the result of subtracting a duration from this instant, for a fluent alternative to <c>operator-()</c>.
/// </summary>
/// <param name="duration">The duration to subtract</param>
/// <returns>A new <see cref="Instant" /> representing the result of the subtraction.</returns>
[Pure]
public Instant Minus(Duration duration) => this - duration;
/// <summary>
/// Implements the operator == (equality).
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if values are equal to each other, otherwise <c>false</c>.</returns>
public static bool operator ==(Instant left, Instant right) => left.duration == right.duration;
/// <summary>
/// Implements the operator != (inequality).
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if values are not equal to each other, otherwise <c>false</c>.</returns>
public static bool operator !=(Instant left, Instant right) => !(left == right);
/// <summary>
/// Implements the operator < (less than).
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if the left value is less than the right value, otherwise <c>false</c>.</returns>
public static bool operator <(Instant left, Instant right) => left.duration < right.duration;
/// <summary>
/// Implements the operator <= (less than or equal).
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if the left value is less than or equal to the right value, otherwise <c>false</c>.</returns>
public static bool operator <=(Instant left, Instant right) => left.duration <= right.duration;
/// <summary>
/// Implements the operator > (greater than).
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if the left value is greater than the right value, otherwise <c>false</c>.</returns>
public static bool operator >(Instant left, Instant right) => left.duration > right.duration;
/// <summary>
/// Implements the operator >= (greater than or equal).
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if the left value is greater than or equal to the right value, otherwise <c>false</c>.</returns>
public static bool operator >=(Instant left, Instant right) => left.duration >= right.duration;
#endregion // Operators
#region Convenience methods
/// <summary>
/// Returns a new instant corresponding to the given UTC date and time in the ISO calendar.
/// In most cases applications should use <see cref="ZonedDateTime" /> to represent a date
/// and time, but this method is useful in some situations where an <see cref="Instant" /> is
/// required, such as time zone testing.
/// </summary>
/// <param name="year">The year. This is the "absolute year",
/// so a value of 0 means 1 BC, for example.</param>
/// <param name="monthOfYear">The month of year.</param>
/// <param name="dayOfMonth">The day of month.</param>
/// <param name="hourOfDay">The hour.</param>
/// <param name="minuteOfHour">The minute.</param>
/// <returns>An <see cref="Instant"/> value representing the given date and time in UTC and the ISO calendar.</returns>
public static Instant FromUtc(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour)
{
var days = new LocalDate(year, monthOfYear, dayOfMonth).DaysSinceEpoch;
var nanoOfDay = new LocalTime(hourOfDay, minuteOfHour).NanosecondOfDay;
return new Instant(days, nanoOfDay);
}
/// <summary>
/// Returns a new instant corresponding to the given UTC date and
/// time in the ISO calendar. In most cases applications should
/// use <see cref="ZonedDateTime" />
/// to represent a date and time, but this method is useful in some
/// situations where an Instant is required, such as time zone testing.
/// </summary>
/// <param name="year">The year. This is the "absolute year",
/// so a value of 0 means 1 BC, for example.</param>
/// <param name="monthOfYear">The month of year.</param>
/// <param name="dayOfMonth">The day of month.</param>
/// <param name="hourOfDay">The hour.</param>
/// <param name="minuteOfHour">The minute.</param>
/// <param name="secondOfMinute">The second.</param>
/// <returns>An <see cref="Instant"/> value representing the given date and time in UTC and the ISO calendar.</returns>
public static Instant FromUtc(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute)
{
var days = new LocalDate(year, monthOfYear, dayOfMonth).DaysSinceEpoch;
var nanoOfDay = new LocalTime(hourOfDay, minuteOfHour, secondOfMinute).NanosecondOfDay;
return new Instant(days, nanoOfDay);
}
/// <summary>
/// Returns the later instant of the given two.
/// </summary>
/// <param name="x">The first instant to compare.</param>
/// <param name="y">The second instant to compare.</param>
/// <returns>The later instant of <paramref name="x"/> or <paramref name="y"/>.</returns>
public static Instant Max(Instant x, Instant y)
{
return x > y ? x : y;
}
/// <summary>
/// Returns the earlier instant of the given two.
/// </summary>
/// <param name="x">The first instant to compare.</param>
/// <param name="y">The second instant to compare.</param>
/// <returns>The earlier instant of <paramref name="x"/> or <paramref name="y"/>.</returns>
public static Instant Min(Instant x, Instant y) => x < y ? x : y;
#endregion
#region Formatting
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// The value of the current instance in the default format pattern ("g"), using the current thread's
/// culture to obtain a format provider.
/// </returns>
public override string ToString() => InstantPattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture);
/// <summary>
/// Formats the value of the current instance using the specified pattern.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> containing the value of the current instance in the specified format.
/// </returns>
/// <param name="patternText">The <see cref="T:System.String" /> specifying the pattern to use,
/// or null to use the default format pattern ("g").
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when formatting the value,
/// or null to use the current thread's culture to obtain a format provider.
/// </param>
/// <filterpriority>2</filterpriority>
public string ToString(string? patternText, IFormatProvider? formatProvider) =>
InstantPattern.BclSupport.Format(this, patternText, formatProvider);
#endregion Formatting
#region IEquatable<Instant> Members
/// <summary>
/// Indicates whether the value of this instant is equal to the value of the specified instant.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="other">The value to compare with this instance.</param>
/// <returns>
/// true if the value of this instant is equal to the value of the <paramref name="other" /> parameter;
/// otherwise, false.
/// </returns>
public bool Equals(Instant other) => this == other;
#endregion
/// <summary>
/// Returns the Julian Date of this instance - the number of days since
/// <see cref="NodaConstants.JulianEpoch"/> (noon on January 1st, 4713 BCE in the Julian calendar).
/// </summary>
/// <returns>The number of days (including fractional days) since the Julian Epoch.</returns>
[Pure]
[TestExemption(TestExemptionCategory.ConversionName)]
public double ToJulianDate() => (this - JulianEpoch).TotalDays;
/// <summary>
/// Constructs a <see cref="DateTime"/> from this Instant which has a <see cref="DateTime.Kind" />
/// of <see cref="DateTimeKind.Utc"/> and represents the same instant of time as this value.
/// </summary>
/// <remarks>
/// <para>
/// If the date and time is not on a tick boundary (the unit of granularity of DateTime) the value will be truncated
/// towards the start of time.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">The final date/time is outside the range of <c>DateTime</c>.</exception>
/// <returns>A <see cref="DateTime"/> representing the same instant in time as this value, with a kind of "universal".</returns>
[Pure]
public DateTime ToDateTimeUtc()
{
if (this < BclEpoch)
{
throw new InvalidOperationException("Instant out of range for DateTime");
}
return new DateTime(BclTicksAtUnixEpoch + ToUnixTimeTicks(), DateTimeKind.Utc);
}
/// <summary>
/// Constructs a <see cref="DateTimeOffset"/> from this Instant which has an offset of zero.
/// </summary>
/// <remarks>
/// <para>
/// If the date and time is not on a tick boundary (the unit of granularity of DateTime) the value will be truncated
/// towards the start of time.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">The final date/time is outside the range of <c>DateTimeOffset</c>.</exception>
/// <returns>A <see cref="DateTimeOffset"/> representing the same instant in time as this value.</returns>
[Pure]
public DateTimeOffset ToDateTimeOffset()
{
if (this < BclEpoch)
{
throw new InvalidOperationException("Instant out of range for DateTimeOffset");
}
return new DateTimeOffset(BclTicksAtUnixEpoch + ToUnixTimeTicks(), TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> into a new Instant representing the same instant in time. Note that
/// the offset information is not preserved in the returned Instant.
/// </summary>
/// <returns>An <see cref="Instant"/> value representing the same instant in time as the given <see cref="DateTimeOffset"/>.</returns>
/// <param name="dateTimeOffset">Date and time value with an offset.</param>
public static Instant FromDateTimeOffset(DateTimeOffset dateTimeOffset) =>
BclEpoch.PlusTicks(dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks);
/// <summary>
/// Converts a Julian Date representing the given number of days
/// since <see cref="NodaConstants.JulianEpoch"/> (noon on January 1st, 4713 BCE in the Julian calendar)
/// into an <see cref="Instant"/>.
/// </summary>
/// <param name="julianDate">The number of days since the Julian Epoch to convert into an <see cref="Instant"/>.</param>
/// <returns>An <see cref="Instant"/> value which is <paramref name="julianDate"/> days after the Julian Epoch.</returns>
public static Instant FromJulianDate(double julianDate) => JulianEpoch + Duration.FromDays(julianDate);
/// <summary>
/// Converts a <see cref="DateTime"/> into a new Instant representing the same instant in time.
/// </summary>
/// <returns>An <see cref="Instant"/> value representing the same instant in time as the given universal <see cref="DateTime"/>.</returns>
/// <param name="dateTime">Date and time value which must have a <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Utc"/></param>
/// <exception cref="ArgumentException"><paramref name="dateTime"/> is not of <see cref="DateTime.Kind"/>
/// <see cref="DateTimeKind.Utc"/>.</exception>
public static Instant FromDateTimeUtc(DateTime dateTime)
{
Preconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, nameof(dateTime), "Invalid DateTime.Kind for Instant.FromDateTimeUtc");
return BclEpoch.PlusTicks(dateTime.Ticks);
}
/// <summary>
/// Initializes a new instance of the <see cref="Instant" /> struct based
/// on a number of seconds since the Unix epoch of (ISO) January 1st 1970, midnight, UTC.
/// </summary>
/// <param name="seconds">Number of seconds since the Unix epoch. May be negative (for instants before the epoch).</param>
/// <returns>An <see cref="Instant"/> at exactly the given number of seconds since the Unix epoch.</returns>
/// <exception cref="ArgumentOutOfRangeException">The constructed instant would be out of the range representable in Noda Time.</exception>
public static Instant FromUnixTimeSeconds(long seconds)
{
Preconditions.CheckArgumentRange(nameof(seconds), seconds, MinSeconds, MaxSeconds);
return Instant.FromTrustedDuration(Duration.FromSeconds(seconds));
}
/// <summary>
/// Initializes a new instance of the <see cref="Instant" /> struct based
/// on a number of milliseconds since the Unix epoch of (ISO) January 1st 1970, midnight, UTC.
/// </summary>
/// <param name="milliseconds">Number of milliseconds since the Unix epoch. May be negative (for instants before the epoch).</param>
/// <returns>An <see cref="Instant"/> at exactly the given number of milliseconds since the Unix epoch.</returns>
/// <exception cref="ArgumentOutOfRangeException">The constructed instant would be out of the range representable in Noda Time.</exception>
public static Instant FromUnixTimeMilliseconds(long milliseconds)
{
Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, MinMilliseconds, MaxMilliseconds);
return Instant.FromTrustedDuration(Duration.FromMilliseconds(milliseconds));
}
/// <summary>
/// Initializes a new instance of the <see cref="Instant" /> struct based
/// on a number of ticks since the Unix epoch of (ISO) January 1st 1970, midnight, UTC.
/// </summary>
/// <returns>An <see cref="Instant"/> at exactly the given number of ticks since the Unix epoch.</returns>
/// <param name="ticks">Number of ticks since the Unix epoch. May be negative (for instants before the epoch).</param>
public static Instant FromUnixTimeTicks(long ticks)
{
Preconditions.CheckArgumentRange(nameof(ticks), ticks, MinTicks, MaxTicks);
return Instant.FromTrustedDuration(Duration.FromTicks(ticks));
}
/// <summary>
/// Gets the number of seconds since the Unix epoch. Negative values represent instants before the Unix epoch.
/// </summary>
/// <remarks>
/// If the number of nanoseconds in this instant is not an exact number of seconds, the value is truncated towards the start of time.
/// </remarks>
/// <value>The number of seconds since the Unix epoch.</value>
[Pure]
[TestExemption(TestExemptionCategory.ConversionName)]
public long ToUnixTimeSeconds() =>
duration.FloorDays * (long) SecondsPerDay + duration.NanosecondOfFloorDay / NanosecondsPerSecond;
/// <summary>
/// Gets the number of milliseconds since the Unix epoch. Negative values represent instants before the Unix epoch.
/// </summary>
/// <remarks>
/// If the number of nanoseconds in this instant is not an exact number of milliseconds, the value is truncated towards the start of time.
/// </remarks>
/// <value>The number of milliseconds since the Unix epoch.</value>
[Pure]
[TestExemption(TestExemptionCategory.ConversionName)]
public long ToUnixTimeMilliseconds() =>
duration.FloorDays * (long) MillisecondsPerDay + duration.NanosecondOfFloorDay / NanosecondsPerMillisecond;
/// <summary>
/// Gets the number of ticks since the Unix epoch. Negative values represent instants before the Unix epoch.
/// </summary>
/// <remarks>
/// A tick is equal to 100 nanoseconds. There are 10,000 ticks in a millisecond. If the number of nanoseconds
/// in this instant is not an exact number of ticks, the value is truncated towards the start of time.
/// </remarks>
/// <returns>The number of ticks since the Unix epoch.</returns>
[Pure]
[TestExemption(TestExemptionCategory.ConversionName)]
public long ToUnixTimeTicks() =>
TickArithmetic.BoundedDaysAndTickOfDayToTicks(duration.FloorDays, duration.NanosecondOfFloorDay / NanosecondsPerTick);
/// <summary>
/// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the UTC time
/// zone and ISO-8601 calendar. This is a shortcut for calling <see cref="InZone(DateTimeZone)" /> with an
/// argument of <see cref="DateTimeZone.Utc"/>.
/// </summary>
/// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the UTC time zone
/// and the ISO-8601 calendar</returns>
[Pure]
public ZonedDateTime InUtc()
{
// Bypass any determination of offset and arithmetic, as we know the offset is zero.
var offsetDateTime = new OffsetDateTime(
new LocalDate(duration.FloorDays),
new OffsetTime(nanosecondOfDayZeroOffset: duration.NanosecondOfFloorDay));
return new ZonedDateTime(offsetDateTime, DateTimeZone.Utc);
}
/// <summary>
/// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the
/// specified time zone and ISO-8601 calendar.
/// </summary>
/// <param name="zone">The time zone in which to represent this instant.</param>
/// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the given time zone
/// and the ISO-8601 calendar</returns>
[Pure]
public ZonedDateTime InZone(DateTimeZone zone) =>
// zone is checked for nullity by the constructor.
new ZonedDateTime(this, zone);
/// <summary>
/// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the
/// specified time zone and calendar system.
/// </summary>
/// <param name="zone">The time zone in which to represent this instant.</param>
/// <param name="calendar">The calendar system in which to represent this instant.</param>
/// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the given time zone
/// and calendar</returns>
[Pure]
public ZonedDateTime InZone(DateTimeZone zone, CalendarSystem calendar)
{
Preconditions.CheckNotNull(zone, nameof(zone));
Preconditions.CheckNotNull(calendar, nameof(calendar));
return new ZonedDateTime(this, zone, calendar);
}
/// <summary>
/// Returns the <see cref="OffsetDateTime"/> representing the same point in time as this instant, with
/// the specified UTC offset in the ISO calendar system.
/// </summary>
/// <param name="offset">The offset from UTC with which to represent this instant.</param>
/// <returns>An <see cref="OffsetDateTime"/> for the same instant, with the given offset
/// in the ISO calendar system</returns>
[Pure]
public OffsetDateTime WithOffset(Offset offset) => new OffsetDateTime(this, offset);
/// <summary>
/// Returns the <see cref="OffsetDateTime"/> representing the same point in time as this instant, with
/// the specified UTC offset and calendar system.
/// </summary>
/// <param name="offset">The offset from UTC with which to represent this instant.</param>
/// <param name="calendar">The calendar system in which to represent this instant.</param>
/// <returns>An <see cref="OffsetDateTime"/> for the same instant, with the given offset
/// and calendar</returns>
[Pure]
public OffsetDateTime WithOffset(Offset offset, CalendarSystem calendar)
{
Preconditions.CheckNotNull(calendar, nameof(calendar));
return new OffsetDateTime(this, offset, calendar);
}
#region XML serialization
/// <summary>
/// Adds the XML schema type describing the structure of the <see cref="Instant"/> XML serialization to the given <paramref name="xmlSchemaSet"/>.
/// </summary>
/// <param name="xmlSchemaSet">The XML schema set provided by <see cref="XmlSchemaExporter"/>.</param>
/// <returns>The qualified name of the schema type that was added to the <paramref name="xmlSchemaSet"/>.</returns>
public static XmlQualifiedName AddSchema(XmlSchemaSet xmlSchemaSet) => Xml.XmlSchemaDefinition.AddInstantSchemaType(xmlSchemaSet);
/// <inheritdoc />
XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that
/// <inheritdoc />
void IXmlSerializable.ReadXml(XmlReader reader)
{
Preconditions.CheckNotNull(reader, nameof(reader));
var pattern = InstantPattern.ExtendedIso;
string text = reader.ReadElementContentAsString();
Unsafe.AsRef(this) = pattern.Parse(text).Value;
}
/// <inheritdoc />
void IXmlSerializable.WriteXml(XmlWriter writer)
{
Preconditions.CheckNotNull(writer, nameof(writer));
writer.WriteString(InstantPattern.ExtendedIso.Format(this));
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.DotNet.ProjectModel.Workspaces;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using Microsoft.DocAsCode.Exceptions;
public sealed class ExtractMetadataWorker : IDisposable
{
private const string XmlCommentFileExtension = "xml";
private readonly Dictionary<FileType, List<FileInformation>> _files;
private readonly bool _rebuild;
private readonly bool _shouldSkipMarkup;
private readonly bool _preserveRawInlineComments;
private readonly bool _useCompatibilityFileName;
private readonly string _filterConfigFile;
private readonly string _outputFolder;
private readonly Dictionary<string, string> _msbuildProperties;
//Lacks UT for shared workspace
private readonly Lazy<MSBuildWorkspace> _workspace;
internal const string IndexFileName = ".manifest";
public ExtractMetadataWorker(ExtractMetadataInputModel input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (string.IsNullOrEmpty(input.OutputFolder))
{
throw new ArgumentNullException(nameof(input.OutputFolder), "Output folder must be specified");
}
_files = input.Files?.Select(s => new FileInformation(s))
.GroupBy(f => f.Type)
.ToDictionary(s => s.Key, s => s.Distinct().ToList());
_rebuild = input.ForceRebuild;
_shouldSkipMarkup = input.ShouldSkipMarkup;
_preserveRawInlineComments = input.PreserveRawInlineComments;
_useCompatibilityFileName = input.UseCompatibilityFileName;
_outputFolder = input.OutputFolder;
if (input.FilterConfigFile != null)
{
_filterConfigFile = new FileInformation(input.FilterConfigFile).NormalizedPath;
}
_msbuildProperties = input.MSBuildProperties ?? new Dictionary<string, string>();
if (!_msbuildProperties.ContainsKey("Configuration"))
{
_msbuildProperties["Configuration"] = "Release";
}
_workspace = new Lazy<MSBuildWorkspace>(() =>
{
var workspace = MSBuildWorkspace.Create(_msbuildProperties);
workspace.WorkspaceFailed += (s, e) =>
{
Logger.LogWarning($"Workspace failed with: {e.Diagnostic}");
};
return workspace;
});
}
public async Task ExtractMetadataAsync()
{
if (_files == null || _files.Count == 0)
{
Logger.Log(LogLevel.Warning, "No source project or file to process, exiting...");
return;
}
try
{
if (_files.TryGetValue(FileType.NotSupported, out List<FileInformation> unsupportedFiles))
{
Logger.LogWarning($"Projects {GetPrintableFileList(unsupportedFiles)} are not supported");
}
await SaveAllMembersFromCacheAsync();
}
catch (AggregateException e)
{
throw new ExtractMetadataException($"Error extracting metadata for {GetPrintableFileList(_files.SelectMany(s => s.Value))}: {e.GetBaseException()?.Message}", e);
}
catch (Exception e)
{
var files = GetPrintableFileList(_files.SelectMany(s => s.Value));
throw new ExtractMetadataException($"Error extracting metadata for {files}: {e.Message}", e);
}
}
public void Dispose()
{
}
#region Internal For UT
internal static MetadataItem GenerateYamlMetadata(Compilation compilation, IAssemblySymbol assembly = null, bool preserveRawInlineComments = false, string filterConfigFile = null, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods = null)
{
if (compilation == null)
{
return null;
}
var options = new ExtractMetadataOptions
{
PreserveRawInlineComments = preserveRawInlineComments,
FilterConfigFile = filterConfigFile,
ExtensionMethods = extensionMethods,
};
return new MetadataExtractor(compilation, assembly).Extract(options);
}
internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromCompilation(IEnumerable<Compilation> compilations)
{
var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>();
foreach (var compilation in compilations)
{
if (compilation.Assembly.MightContainExtensionMethods)
{
var extensions = (from n in GetAllNamespaceMembers(compilation.Assembly).Distinct()
from m in GetExtensionMethodPerNamespace(n)
select m).ToList();
if (extensions.Count > 0)
{
methods[compilation] = extensions;
}
}
}
return methods;
}
internal static IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> GetAllExtensionMethodsFromAssembly(Compilation compilation, IEnumerable<IAssemblySymbol> assemblies)
{
var methods = new Dictionary<Compilation, IEnumerable<IMethodSymbol>>();
foreach (var assembly in assemblies)
{
if (assembly.MightContainExtensionMethods)
{
var extensions = (from n in GetAllNamespaceMembers(assembly).Distinct()
from m in GetExtensionMethodPerNamespace(n)
select m).ToList();
if (extensions.Count > 0)
{
IEnumerable<IMethodSymbol> ext;
if (methods.TryGetValue(compilation, out ext))
{
methods[compilation] = ext.Union(extensions);
}
else
{
methods[compilation] = extensions;
}
}
}
}
return methods;
}
#endregion
#region Private
private async Task SaveAllMembersFromCacheAsync()
{
var forceRebuild = _rebuild;
var outputFolder = _outputFolder;
var projectCache = new ConcurrentDictionary<string, Project>();
// Project<=>Documents
var documentCache = new ProjectDocumentCache();
var projectDependencyGraph = new ConcurrentDictionary<string, List<string>>();
DateTime triggeredTime = DateTime.UtcNow;
// Exclude not supported files from inputs
var cacheKey = GetCacheKey(_files.SelectMany(s => s.Value));
// Add filter config file into inputs and cache
if (!string.IsNullOrEmpty(_filterConfigFile))
{
cacheKey = cacheKey.Concat(new string[] { _filterConfigFile });
documentCache.AddDocument(_filterConfigFile, _filterConfigFile);
}
if (_files.TryGetValue(FileType.Solution, out var sln))
{
var solutions = sln.Select(s => s.NormalizedPath);
// No matter is incremental or not, we have to load solutions into memory
foreach (var path in solutions)
{
documentCache.AddDocument(path, path);
var solution = await GetSolutionAsync(path);
if (solution != null)
{
foreach (var project in solution.Projects)
{
var projectFile = new FileInformation(project.FilePath);
// If the project is csproj/vbproj, add to project dictionary, otherwise, ignore
if (projectFile.IsSupportedProject())
{
projectCache.GetOrAdd(projectFile.NormalizedPath, s => project);
}
else
{
Logger.LogWarning($"Project {projectFile.RawPath} inside solution {path} is ignored, supported projects are csproj and vbproj.");
}
}
}
}
}
if (_files.TryGetValue(FileType.Project, out var p))
{
foreach (var pp in p)
{
GetProject(projectCache, pp.NormalizedPath);
}
}
if (_files.TryGetValue(FileType.ProjectJsonProject, out var pjp))
{
await pjp.Select(s => s.NormalizedPath).ForEachInParallelAsync(path =>
{
projectCache.GetOrAdd(path, s => GetProjectJsonProject(s));
return Task.CompletedTask;
}, 60);
}
foreach (var item in projectCache)
{
var path = item.Key;
var project = item.Value;
documentCache.AddDocument(path, path);
if (project.HasDocuments)
{
documentCache.AddDocuments(path, project.Documents.Select(s => s.FilePath));
}
else
{
Logger.Log(LogLevel.Warning, $"Project '{project.FilePath}' does not contain any documents.");
}
documentCache.AddDocuments(path, project.MetadataReferences
.Where(s => s is PortableExecutableReference)
.Select(s => ((PortableExecutableReference)s).FilePath));
FillProjectDependencyGraph(projectCache, projectDependencyGraph, project);
// duplicate project references will fail Project.GetCompilationAsync
var groups = project.ProjectReferences.GroupBy(r => r);
if (groups.Any(g => g.Count() > 1))
{
projectCache[path] = project.WithProjectReferences(groups.Select(g => g.Key));
}
}
var csFiles = new List<string>();
var vbFiles = new List<string>();
var assemblyFiles = new List<string>();
if (_files.TryGetValue(FileType.CSSourceCode, out var cs))
{
csFiles.AddRange(cs.Select(s => s.NormalizedPath));
documentCache.AddDocuments(csFiles);
}
if (_files.TryGetValue(FileType.VBSourceCode, out var vb))
{
vbFiles.AddRange(vb.Select(s => s.NormalizedPath));
documentCache.AddDocuments(vbFiles);
}
if (_files.TryGetValue(FileType.Assembly, out var asm))
{
assemblyFiles.AddRange(asm.Select(s => s.NormalizedPath));
documentCache.AddDocuments(assemblyFiles);
}
// Incremental check for inputs as a whole:
var applicationCache = ApplicationLevelCache.Get(cacheKey);
if (!forceRebuild)
{
var buildInfo = applicationCache.GetValidConfig(cacheKey);
if (buildInfo != null && buildInfo.ShouldSkipMarkup == _shouldSkipMarkup)
{
IncrementalCheck check = new IncrementalCheck(buildInfo);
// 1. Check if sln files/ project files and its contained documents/ source files are modified
var projectModified = check.AreFilesModified(documentCache.Documents) || check.MSBuildPropertiesUpdated(_msbuildProperties);
if (!projectModified)
{
// 2. Check if documents/ assembly references are changed in a project
// e.g. <Compile Include="*.cs* /> and file added/deleted
foreach (var project in projectCache.Values)
{
var key = StringExtension.ToNormalizedFullPath(project.FilePath);
IEnumerable<string> currentContainedFiles = documentCache.GetDocuments(project.FilePath);
var previousDocumentCache = new ProjectDocumentCache(buildInfo.ContainedFiles);
IEnumerable<string> previousContainedFiles = previousDocumentCache.GetDocuments(project.FilePath);
if (previousContainedFiles != null && currentContainedFiles != null)
{
projectModified = !previousContainedFiles.SequenceEqual(currentContainedFiles);
}
else
{
// When one of them is not null, project is modified
if (!object.Equals(previousContainedFiles, currentContainedFiles))
{
projectModified = true;
}
}
if (projectModified) break;
}
}
if (!projectModified)
{
// Nothing modified, use the result in cache
try
{
CopyFromCachedResult(buildInfo, cacheKey, outputFolder);
return;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Unable to copy results from cache: {e.Message}. Rebuild starts.");
}
}
}
}
// Build all the projects to get the output and save to cache
List<MetadataItem> projectMetadataList = new List<MetadataItem>();
ConcurrentDictionary<string, bool> projectRebuildInfo = new ConcurrentDictionary<string, bool>();
ConcurrentDictionary<string, Compilation> compilationCache = await GetProjectCompilationAsync(projectCache);
var extensionMethods = GetAllExtensionMethodsFromCompilation(compilationCache.Values);
foreach (var key in GetTopologicalSortedItems(projectDependencyGraph))
{
var dependencyRebuilt = projectDependencyGraph[key].Any(r => projectRebuildInfo[r]);
var projectMetadataResult = await GetProjectMetadataFromCacheAsync(projectCache[key], compilationCache[key], outputFolder, documentCache, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods, dependencyRebuilt);
var projectMetadata = projectMetadataResult.Item1;
if (projectMetadata != null) projectMetadataList.Add(projectMetadata);
projectRebuildInfo[key] = projectMetadataResult.Item2;
}
if (csFiles.Count > 0)
{
var csContent = string.Join(Environment.NewLine, csFiles.Select(s => File.ReadAllText(s)));
var csCompilation = CompilationUtility.CreateCompilationFromCsharpCode(csContent);
if (csCompilation != null)
{
var csMetadata = await GetFileMetadataFromCacheAsync(csFiles, csCompilation, outputFolder, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods);
if (csMetadata != null) projectMetadataList.Add(csMetadata.Item1);
}
}
if (vbFiles.Count > 0)
{
var vbContent = string.Join(Environment.NewLine, vbFiles.Select(s => File.ReadAllText(s)));
var vbCompilation = CompilationUtility.CreateCompilationFromVBCode(vbContent);
if (vbCompilation != null)
{
var vbMetadata = await GetFileMetadataFromCacheAsync(vbFiles, vbCompilation, outputFolder, forceRebuild, _preserveRawInlineComments, _shouldSkipMarkup, _filterConfigFile, extensionMethods);
if (vbMetadata != null) projectMetadataList.Add(vbMetadata.Item1);
}
}
if (assemblyFiles.Count > 0)
{
var assemblyCompilation = CompilationUtility.CreateCompilationFromAssembly(assemblyFiles);
if (assemblyCompilation != null)
{
var commentFiles = (from file in assemblyFiles
select Path.ChangeExtension(file, XmlCommentFileExtension) into xmlFile
where File.Exists(xmlFile)
select xmlFile).ToList();
var referencedAssemblyList = CompilationUtility.GetAssemblyFromAssemblyComplation(assemblyCompilation);
var assemblyExtension = GetAllExtensionMethodsFromAssembly(assemblyCompilation, referencedAssemblyList);
foreach (var assembly in referencedAssemblyList)
{
var mta = await GetAssemblyMetadataFromCacheAsync(assemblyFiles, assemblyCompilation, assembly, outputFolder, forceRebuild, _filterConfigFile, assemblyExtension);
if (mta != null)
{
MergeCommentsHelper.MergeComments(mta.Item1, commentFiles);
projectMetadataList.Add(mta.Item1);
}
}
}
}
var allMemebers = MergeYamlProjectMetadata(projectMetadataList);
var allReferences = MergeYamlProjectReferences(projectMetadataList);
if (allMemebers == null || allMemebers.Count == 0)
{
var value = StringExtension.ToDelimitedString(projectMetadataList.Select(s => s.Name));
Logger.Log(LogLevel.Warning, $"No metadata is generated for {value}.");
applicationCache.SaveToCache(cacheKey, null, triggeredTime, outputFolder, null, _shouldSkipMarkup, _msbuildProperties);
}
else
{
// TODO: need an intermediate folder? when to clean it up?
// Save output to output folder
var outputFiles = ResolveAndExportYamlMetadata(allMemebers, allReferences, outputFolder, _preserveRawInlineComments, _shouldSkipMarkup, _useCompatibilityFileName).ToList();
applicationCache.SaveToCache(cacheKey, documentCache.Cache, triggeredTime, outputFolder, outputFiles, _shouldSkipMarkup, _msbuildProperties);
}
}
private static void FillProjectDependencyGraph(ConcurrentDictionary<string, Project> projectCache, ConcurrentDictionary<string, List<string>> projectDependencyGraph, Project project)
{
projectDependencyGraph.GetOrAdd(project.FilePath.ToNormalizedFullPath(), _ => GetTransitiveProjectReferences(projectCache, project).Distinct().ToList());
}
private static IEnumerable<string> GetTransitiveProjectReferences(ConcurrentDictionary<string, Project> projectCache, Project project)
{
var solution = project.Solution;
foreach (var pr in project.ProjectReferences)
{
var refProject = solution.GetProject(pr.ProjectId);
var path = StringExtension.ToNormalizedFullPath(refProject.FilePath);
if (projectCache.ContainsKey(path))
{
yield return path;
}
else
{
foreach (var rpr in GetTransitiveProjectReferences(projectCache, refProject))
{
yield return rpr;
}
}
}
}
private static async Task<ConcurrentDictionary<string, Compilation>> GetProjectCompilationAsync(ConcurrentDictionary<string, Project> projectCache)
{
var compilations = new ConcurrentDictionary<string, Compilation>();
var sb = new StringBuilder();
foreach (var project in projectCache)
{
try
{
var compilation = await project.Value.GetCompilationAsync();
compilations.TryAdd(project.Key, compilation);
}
catch (Exception e)
{
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.Append($"Error extracting metadata for project \"{project.Key}\": {e.Message}");
}
}
if (sb.Length > 0)
{
throw new ExtractMetadataException(sb.ToString());
}
return compilations;
}
private static IEnumerable<IMethodSymbol> GetExtensionMethodPerNamespace(INamespaceSymbol space)
{
var typesWithExtensionMethods = space.GetTypeMembers().Where(t => t.MightContainExtensionMethods);
foreach (var type in typesWithExtensionMethods)
{
var members = type.GetMembers();
foreach (var member in members)
{
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
if (method.IsExtensionMethod)
{
yield return method;
}
}
}
}
}
private static IEnumerable<INamespaceSymbol> GetAllNamespaceMembers(IAssemblySymbol assembly)
{
var queue = new Queue<INamespaceSymbol>();
queue.Enqueue(assembly.GlobalNamespace);
while (queue.Count > 0)
{
var space = queue.Dequeue();
yield return space;
var childSpaces = space.GetNamespaceMembers();
foreach (var child in childSpaces)
{
queue.Enqueue(child);
}
}
}
private static void CopyFromCachedResult(BuildInfo buildInfo, IEnumerable<string> inputs, string outputFolder)
{
var outputFolderSource = buildInfo.OutputFolder;
var relativeFiles = buildInfo.RelatvieOutputFiles;
if (relativeFiles == null)
{
Logger.Log(LogLevel.Warning, $"No metadata is generated for '{StringExtension.ToDelimitedString(inputs)}'.");
return;
}
Logger.Log(LogLevel.Info, $"'{StringExtension.ToDelimitedString(inputs)}' keep up-to-date since '{buildInfo.TriggeredUtcTime.ToString()}', cached result from '{buildInfo.OutputFolder}' is used.");
PathUtility.CopyFilesToFolder(relativeFiles.Select(s => Path.Combine(outputFolderSource, s)), outputFolderSource, outputFolder, true, s => Logger.Log(LogLevel.Info, s), null);
}
private Task<Tuple<MetadataItem, bool>> GetProjectMetadataFromCacheAsync(Project project, Compilation compilation, string outputFolder, ProjectDocumentCache documentCache, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods, bool isReferencedProjectRebuilt)
{
var projectFilePath = project.FilePath;
var k = documentCache.GetDocuments(projectFilePath);
return GetMetadataFromProjectLevelCacheAsync(
project,
new[] { projectFilePath, filterConfigFile },
s => Task.FromResult(forceRebuild || s.AreFilesModified(k.Concat(new string[] { filterConfigFile })) || isReferencedProjectRebuilt || s.MSBuildPropertiesUpdated(_msbuildProperties)),
s => Task.FromResult(compilation),
s => Task.FromResult(compilation.Assembly),
s =>
{
return new Dictionary<string, List<string>> { { StringExtension.ToNormalizedFullPath(s.FilePath), k.ToList() } };
},
outputFolder,
preserveRawInlineComments,
shouldSkipMarkup,
filterConfigFile,
extensionMethods);
}
private Task<Tuple<MetadataItem, bool>> GetAssemblyMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, IAssemblySymbol assembly, string outputFolder, bool forceRebuild, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
if (files == null || !files.Any()) return null;
return GetMetadataFromProjectLevelCacheAsync(
files,
files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))),
s => Task.FromResult(compilation),
s => Task.FromResult(assembly),
s => null,
outputFolder,
false,
false,
filterConfigFile,
extensionMethods);
}
private Task<Tuple<MetadataItem, bool>> GetFileMetadataFromCacheAsync(IEnumerable<string> files, Compilation compilation, string outputFolder, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
if (files == null || !files.Any()) return null;
return GetMetadataFromProjectLevelCacheAsync(
files,
files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile })) || s.MSBuildPropertiesUpdated(_msbuildProperties)),
s => Task.FromResult(compilation),
s => Task.FromResult(compilation.Assembly),
s => null,
outputFolder,
preserveRawInlineComments,
shouldSkipMarkup,
filterConfigFile,
extensionMethods);
}
private async Task<Tuple<MetadataItem, bool>> GetMetadataFromProjectLevelCacheAsync<T>(
T input,
IEnumerable<string> inputKey,
Func<IncrementalCheck, Task<bool>> rebuildChecker,
Func<T, Task<Compilation>> compilationProvider,
Func<T, Task<IAssemblySymbol>> assemblyProvider,
Func<T, IDictionary<string, List<string>>> containedFilesProvider,
string outputFolder,
bool preserveRawInlineComments,
bool shouldSkipMarkup,
string filterConfigFile,
IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> extensionMethods)
{
DateTime triggeredTime = DateTime.UtcNow;
var projectLevelCache = ProjectLevelCache.Get(inputKey);
var projectConfig = projectLevelCache.GetValidConfig(inputKey);
var rebuildProject = true;
if (projectConfig != null)
{
var projectCheck = new IncrementalCheck(projectConfig);
rebuildProject = await rebuildChecker(projectCheck);
}
MetadataItem projectMetadata;
if (!rebuildProject)
{
// Load from cache
var cacheFile = Path.Combine(projectConfig.OutputFolder, projectConfig.RelatvieOutputFiles.First());
Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' keep up-to-date since '{projectConfig.TriggeredUtcTime.ToString()}', cached intermediate result '{cacheFile}' is used.");
if (TryParseYamlMetadataFile(cacheFile, out projectMetadata))
{
return Tuple.Create(projectMetadata, rebuildProject);
}
else
{
Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' is invalid, rebuild needed.");
}
}
var compilation = await compilationProvider(input);
var assembly = await assemblyProvider(input);
projectMetadata = GenerateYamlMetadata(compilation, assembly, preserveRawInlineComments, filterConfigFile, extensionMethods);
var file = Path.GetRandomFileName();
var cacheOutputFolder = projectLevelCache.OutputFolder;
var path = Path.Combine(cacheOutputFolder, file);
YamlUtility.Serialize(path, projectMetadata);
Logger.Log(LogLevel.Verbose, $"Successfully generated metadata {cacheOutputFolder} for {projectMetadata.Name}");
IDictionary<string, List<string>> containedFiles = null;
if (containedFilesProvider != null)
{
containedFiles = containedFilesProvider(input);
}
// Save to cache
projectLevelCache.SaveToCache(inputKey, containedFiles, triggeredTime, cacheOutputFolder, new List<string>() { file }, shouldSkipMarkup, _msbuildProperties);
return Tuple.Create(projectMetadata, rebuildProject);
}
private static IEnumerable<string> ResolveAndExportYamlMetadata(
Dictionary<string, MetadataItem> allMembers,
Dictionary<string, ReferenceItem> allReferences,
string folder,
bool preserveRawInlineComments,
bool shouldSkipMarkup,
bool useCompatibilityFileName)
{
var outputFileNames = new Dictionary<string, int>(FilePathComparer.OSPlatformSensitiveStringComparer);
var model = YamlMetadataResolver.ResolveMetadata(allMembers, allReferences, preserveRawInlineComments);
var tocFileName = Constants.TocYamlFileName;
// 0. load last Manifest and remove files
CleanupHistoricalFile(folder);
// 1. generate toc.yml
model.TocYamlViewModel.Type = MemberType.Toc;
// TOC do not change
var tocViewModel = model.TocYamlViewModel.ToTocViewModel();
string tocFilePath = Path.Combine(folder, tocFileName);
YamlUtility.Serialize(tocFilePath, tocViewModel, YamlMime.TableOfContent);
outputFileNames.Add(tocFilePath, 1);
yield return tocFileName;
ApiReferenceViewModel indexer = new ApiReferenceViewModel();
// 2. generate each item's yaml
var members = model.Members;
foreach (var memberModel in members)
{
var fileName = useCompatibilityFileName ? memberModel.Name : memberModel.Name.Replace('`', '-');
var outputFileName = GetUniqueFileNameWithSuffix(fileName + Constants.YamlExtension, outputFileNames);
string itemFilePath = Path.Combine(folder, outputFileName);
Directory.CreateDirectory(Path.GetDirectoryName(itemFilePath));
var memberViewModel = memberModel.ToPageViewModel();
memberViewModel.ShouldSkipMarkup = shouldSkipMarkup;
YamlUtility.Serialize(itemFilePath, memberViewModel, YamlMime.ManagedReference);
Logger.Log(LogLevel.Diagnostic, $"Metadata file for {memberModel.Name} is saved to {itemFilePath}.");
AddMemberToIndexer(memberModel, outputFileName, indexer);
yield return outputFileName;
}
// 3. generate manifest file
string indexFilePath = Path.Combine(folder, IndexFileName);
JsonUtility.Serialize(indexFilePath, indexer, Newtonsoft.Json.Formatting.Indented);
yield return IndexFileName;
}
private static void CleanupHistoricalFile(string outputFolder)
{
var indexFilePath = Path.Combine(outputFolder, IndexFileName);
ApiReferenceViewModel index;
if (!File.Exists(indexFilePath))
{
return;
}
try
{
index = JsonUtility.Deserialize<ApiReferenceViewModel>(indexFilePath);
}
catch (Exception e)
{
Logger.LogInfo($"{indexFilePath} is not in a valid metadata manifest file format, ignored: {e.Message}.");
return;
}
foreach (var pair in index)
{
var filePath = Path.Combine(outputFolder, pair.Value);
try
{
File.Delete(filePath);
}
catch (Exception e)
{
Logger.LogDiagnostic($"Error deleting file {filePath}: {e.Message}");
}
}
}
private static string GetUniqueFileNameWithSuffix(string fileName, Dictionary<string, int> existingFileNames)
{
if (existingFileNames.TryGetValue(fileName, out int suffix))
{
existingFileNames[fileName] = suffix + 1;
var newFileName = $"{fileName}_{suffix}";
var extensionIndex = fileName.LastIndexOf('.');
if (extensionIndex > -1)
{
newFileName = $"{fileName.Substring(0, extensionIndex)}_{suffix}.{fileName.Substring(extensionIndex + 1)}";
}
var extension = Path.GetExtension(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
return GetUniqueFileNameWithSuffix(newFileName, existingFileNames);
}
else
{
existingFileNames[fileName] = 1;
return fileName;
}
}
private static void AddMemberToIndexer(MetadataItem memberModel, string outputPath, ApiReferenceViewModel indexer)
{
if (memberModel.Type == MemberType.Namespace)
{
indexer.Add(memberModel.Name, outputPath);
}
else
{
TreeIterator.Preorder(memberModel, null, s => s.Items, (member, parent) =>
{
string path;
if (indexer.TryGetValue(member.Name, out path))
{
Logger.LogWarning($"{member.Name} already exists in {path}, the duplicate one {outputPath} will be ignored.");
}
else
{
indexer.Add(member.Name, outputPath);
}
return true;
});
}
}
private static Dictionary<string, MetadataItem> MergeYamlProjectMetadata(List<MetadataItem> projectMetadataList)
{
if (projectMetadataList == null || projectMetadataList.Count == 0)
{
return null;
}
Dictionary<string, MetadataItem> namespaceMapping = new Dictionary<string, MetadataItem>();
Dictionary<string, MetadataItem> allMembers = new Dictionary<string, MetadataItem>();
foreach (var project in projectMetadataList)
{
if (project.Items != null)
{
foreach (var ns in project.Items)
{
if (ns.Type == MemberType.Namespace)
{
MetadataItem nsOther;
if (namespaceMapping.TryGetValue(ns.Name, out nsOther))
{
if (ns.Items != null)
{
if (nsOther.Items == null)
{
nsOther.Items = new List<MetadataItem>();
}
foreach (var i in ns.Items)
{
if (!nsOther.Items.Any(s => s.Name == i.Name))
{
nsOther.Items.Add(i);
}
else
{
Logger.Log(LogLevel.Info, $"{i.Name} already exists in {nsOther.Name}, ignore current one");
}
}
}
}
else
{
namespaceMapping.Add(ns.Name, ns);
}
}
if (!allMembers.ContainsKey(ns.Name))
{
allMembers.Add(ns.Name, ns);
}
ns.Items?.ForEach(s =>
{
MetadataItem existingMetadata;
if (allMembers.TryGetValue(s.Name, out existingMetadata))
{
Logger.Log(LogLevel.Warning, $"Duplicate member {s.Name} is found from {existingMetadata.Source.Path} and {s.Source.Path}, use the one in {existingMetadata.Source.Path} and ignore the one from {s.Source.Path}");
}
else
{
allMembers.Add(s.Name, s);
}
s.Items?.ForEach(s1 =>
{
MetadataItem existingMetadata1;
if (allMembers.TryGetValue(s1.Name, out existingMetadata1))
{
Logger.Log(LogLevel.Warning, $"Duplicate member {s1.Name} is found from {existingMetadata1.Source.Path} and {s1.Source.Path}, use the one in {existingMetadata1.Source.Path} and ignore the one from {s1.Source.Path}");
}
else
{
allMembers.Add(s1.Name, s1);
}
});
});
}
}
}
return allMembers;
}
private static bool TryParseYamlMetadataFile(string metadataFileName, out MetadataItem projectMetadata)
{
projectMetadata = null;
try
{
using (StreamReader reader = new StreamReader(metadataFileName))
{
projectMetadata = YamlUtility.Deserialize<MetadataItem>(reader);
return true;
}
}
catch (Exception e)
{
Logger.LogInfo($"Error parsing yaml metadata file: {e.Message}");
return false;
}
}
private static Dictionary<string, ReferenceItem> MergeYamlProjectReferences(List<MetadataItem> projectMetadataList)
{
if (projectMetadataList == null || projectMetadataList.Count == 0)
{
return null;
}
var result = new Dictionary<string, ReferenceItem>();
foreach (var project in projectMetadataList)
{
if (project.References != null)
{
foreach (var pair in project.References)
{
if (!result.ContainsKey(pair.Key))
{
result[pair.Key] = pair.Value;
}
else
{
result[pair.Key].Merge(pair.Value);
}
}
}
}
return result;
}
private async Task<Solution> GetSolutionAsync(string path)
{
try
{
Logger.LogVerbose($"Loading solution {path}", file: path);
var solution = await _workspace.Value.OpenSolutionAsync(path);
_workspace.Value.CloseSolution();
return solution;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening solution {path}: {e.Message}. Ignored.");
return null;
}
}
private Project GetProject(ConcurrentDictionary<string, Project> cache, string path)
{
return cache.GetOrAdd(path.ToNormalizedFullPath(), s =>
{
try
{
Logger.LogVerbose($"Loading project {s}", file: s);
var project = _workspace.Value.CurrentSolution.Projects.FirstOrDefault(
p => FilePathComparer.OSPlatformSensitiveRelativePathComparer.Equals(p.FilePath, s));
if (project != null)
{
return project;
}
return _workspace.Value.OpenProjectAsync(s).Result;
}
catch (AggregateException e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.GetBaseException()?.Message}. Ignored.");
return null;
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.Message}. Ignored.");
return null;
}
});
}
private Project GetProjectJsonProject(string path)
{
try
{
Logger.LogVerbose($"Loading project {path}", file: path);
var workspace = new ProjectJsonWorkspace(path);
return workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == Path.GetFullPath(path));
}
catch (Exception e)
{
Logger.Log(LogLevel.Warning, $"Error opening project {path}: {e.Message}. Ignored.");
return null;
}
}
/// <summary>
/// use DFS to get topological sorted items
/// </summary>
private static IEnumerable<string> GetTopologicalSortedItems(IDictionary<string, List<string>> graph)
{
var visited = new HashSet<string>();
var result = new List<string>();
foreach (var node in graph.Keys)
{
DepthFirstTraverse(graph, node, visited, result);
}
return result;
}
private static void DepthFirstTraverse(IDictionary<string, List<string>> graph, string start, HashSet<string> visited, List<string> result)
{
if (!visited.Add(start))
{
return;
}
foreach (var presequisite in graph[start])
{
DepthFirstTraverse(graph, presequisite, visited, result);
}
result.Add(start);
}
private static string GetPrintableFileList(IEnumerable<FileInformation> files)
{
return files?.Select(s => s.RawPath).ToDelimitedString();
}
private static IEnumerable<string> GetCacheKey(IEnumerable<FileInformation> files)
{
return files.Where(s => s.Type != FileType.NotSupported).OrderBy(s => s.Type).Select(s => s.NormalizedPath);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Compute Management API includes operations for managing the load
/// balancers for your subscription.
/// </summary>
internal partial class LoadBalancerOperations : IServiceOperations<ComputeManagementClient>, ILoadBalancerOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LoadBalancerOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Add an internal load balancer to a an existing deployment. When
/// used by an input endpoint, the internal load balancer will provide
/// an additional private VIP that can be used for load balancing to
/// the roles in this deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Load Balancer operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginCreatingAsync(string serviceName, string deploymentName, LoadBalancerCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement loadBalancerElement = new XElement(XName.Get("LoadBalancer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(loadBalancerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
loadBalancerElement.Add(nameElement);
}
if (parameters.FrontendIPConfiguration != null)
{
XElement frontendIpConfigurationElement = new XElement(XName.Get("FrontendIpConfiguration", "http://schemas.microsoft.com/windowsazure"));
loadBalancerElement.Add(frontendIpConfigurationElement);
if (parameters.FrontendIPConfiguration.Type != null)
{
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.FrontendIPConfiguration.Type;
frontendIpConfigurationElement.Add(typeElement);
}
if (parameters.FrontendIPConfiguration.SubnetName != null)
{
XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://schemas.microsoft.com/windowsazure"));
subnetNameElement.Value = parameters.FrontendIPConfiguration.SubnetName;
frontendIpConfigurationElement.Add(subnetNameElement);
}
if (parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress != null)
{
XElement staticVirtualNetworkIPAddressElement = new XElement(XName.Get("StaticVirtualNetworkIPAddress", "http://schemas.microsoft.com/windowsazure"));
staticVirtualNetworkIPAddressElement.Value = parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress;
frontendIpConfigurationElement.Add(staticVirtualNetworkIPAddressElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete an internal load balancer from the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the load balancer.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginDeletingAsync(string serviceName, string deploymentName, string loadBalancerName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (loadBalancerName == null)
{
throw new ArgumentNullException("loadBalancerName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers/";
url = url + Uri.EscapeDataString(loadBalancerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates an internal load balancer associated with an existing
/// deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Load Balancer operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginUpdatingAsync(string serviceName, string deploymentName, string loadBalancerName, LoadBalancerUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (loadBalancerName == null)
{
throw new ArgumentNullException("loadBalancerName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers/";
url = url + Uri.EscapeDataString(loadBalancerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement loadBalancerElement = new XElement(XName.Get("LoadBalancer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(loadBalancerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
loadBalancerElement.Add(nameElement);
}
if (parameters.FrontendIPConfiguration != null)
{
XElement frontendIpConfigurationElement = new XElement(XName.Get("FrontendIpConfiguration", "http://schemas.microsoft.com/windowsazure"));
loadBalancerElement.Add(frontendIpConfigurationElement);
if (parameters.FrontendIPConfiguration.Type != null)
{
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.FrontendIPConfiguration.Type;
frontendIpConfigurationElement.Add(typeElement);
}
if (parameters.FrontendIPConfiguration.SubnetName != null)
{
XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://schemas.microsoft.com/windowsazure"));
subnetNameElement.Value = parameters.FrontendIPConfiguration.SubnetName;
frontendIpConfigurationElement.Add(subnetNameElement);
}
if (parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress != null)
{
XElement staticVirtualNetworkIPAddressElement = new XElement(XName.Get("StaticVirtualNetworkIPAddress", "http://schemas.microsoft.com/windowsazure"));
staticVirtualNetworkIPAddressElement.Value = parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress;
frontendIpConfigurationElement.Add(staticVirtualNetworkIPAddressElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Add an internal load balancer to a an existing deployment. When
/// used by an input endpoint, the internal load balancer will provide
/// an additional private VIP that can be used for load balancing to
/// the roles in this deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Load Balancer operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> CreateAsync(string serviceName, string deploymentName, LoadBalancerCreateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginCreatingAsync(serviceName, deploymentName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Delete an internal load balancer from the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the load balancer.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string serviceName, string deploymentName, string loadBalancerName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginDeletingAsync(serviceName, deploymentName, loadBalancerName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Updates an internal load balancer associated with an existing
/// deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Load Balancer operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> UpdateAsync(string serviceName, string deploymentName, string loadBalancerName, LoadBalancerUpdateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginUpdatingAsync(serviceName, deploymentName, loadBalancerName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
// <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.Double.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<double>.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], 1.0e-11);
}
}
}
/// <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<double>.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<double>.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<double>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var matrixB = new UserDefinedMatrix(Matrix<double>.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<double>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var vectorb = new UserDefinedVector(Vector<double>.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<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<double>.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], 1.0e-11);
}
// 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<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<double>.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], 1.0e-11);
}
}
// 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<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<double>.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], 1.0e-11);
}
// 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<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<double>.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], 1.0e-11);
}
}
// 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;
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 BlueYonder.Reservations.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 FlatRedBall.Instructions;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Utilities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Matrix = Microsoft.Xna.Framework.Matrix;
using Vector3 = Microsoft.Xna.Framework.Vector3;
namespace FlatRedBall.Graphics
{
#region Enums
public enum SetCameraOptions
{
PerformZRotation,
ApplyMatrix
}
#endregion
#region Other Classes
public class LayerCameraSettings
{
public float FieldOfView = (float)System.Math.PI / 4.0f;
public bool Orthogonal = false;
/// <summary>
/// The orthogonal width to use when drawing this layer, if Orthogonal is true.
/// </summary>
public float OrthogonalWidth = 800;
/// <summary>
/// The orthogonal height to use when drawing this layer, if Orthogonal is true;
/// </summary>
public float OrthogonalHeight = 600;
public float ExtraRotationZ = 0;
/// <summary>
/// Sets the top destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float TopDestination = -1;
/// <summary>
/// Sets the bottom destination for this Layer. Destination Y values increase when moving down the screen, so this value should be greater than TopDestination (if it is not -1).
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float BottomDestination = -1;
/// <summary>
/// Sets the left destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float LeftDestination = -1;
/// <summary>
/// Sets the right destination for this Layer.
/// </summary>
/// <remarks>
/// By default, this value is set to -1,
/// which means that the Layer will use its parent Camera's destination. All four destination
/// values must be greater than or equal to 0 to be applied. If any are less than -1, then the Camera's
/// destination values are used.
/// </remarks>
public float RightDestination = -1;
public PositionedObject OffsetParent { get; set; }
Vector3 mOldUpVector;
// We used to have
// a RotationMatrix
// but this caused a
// bug in Camera rotation.
// I'm not 100% certain what
// the issue is, but setting the
// individual rotation values seems
// to fix it.
// Update July 20, 2016
// In the current game I'm working on,
// saving and resetting the individual rotation
// components was resulting in a rotation matrix
// that wasn't quite right. To fix this, we're going
// to save and set both sets of values to make sure it
// works perfectly.
float storedRotationX;
float storedRotationY;
float storedRotationZ;
Matrix storedRotationMatrix;
public LayerCameraSettings Clone()
{
return (LayerCameraSettings)this.MemberwiseClone();
}
public void SetFromCamera(Camera camera)
{
mOldUpVector = camera.UpVector;
Orthogonal = camera.Orthogonal;
OrthogonalHeight = camera.OrthogonalHeight;
OrthogonalWidth = camera.OrthogonalWidth;
FieldOfView = camera.FieldOfView;
storedRotationX = camera.RotationX;
storedRotationY = camera.RotationY;
storedRotationZ = camera.RotationZ;
storedRotationMatrix = camera.RotationMatrix;
}
//public void SetCamera(Camera camera, SetCameraOptions options)
//{
//}
public void ApplyValuesToCamera(Camera camera, SetCameraOptions options, LayerCameraSettings lastToModify, RenderTarget2D renderTarget = null)
{
var viewport = camera.GetViewport(this, renderTarget);
Renderer.GraphicsDevice.Viewport = viewport;
camera.Orthogonal = Orthogonal;
camera.OrthogonalHeight = OrthogonalHeight;
camera.OrthogonalWidth = OrthogonalWidth;
if (lastToModify == null)
{
// January 11, 2014
// We used to only do
// offsets if the Layer
// was both orthogonal and
// if its orthogonal width and
// height matched the destination.
// Baron runs on multiple resolutions
// and introduced situations where the
// ortho width/height may not match the
// destination rectangles because we may
// scale everything up on larrger resolutions.
// In that situation we still want to have the layers
// offset properly.
// bool offsetOrthogonal = Orthogonal && OrthogonalWidth == RightDestination - LeftDestination &&
// OrthogonalHeight == BottomDestination - TopDestination;
bool offsetOrthogonal = Orthogonal;
// But don't do this if we're on a render target, because render targets render full-screen:
if (offsetOrthogonal && renderTarget == null)
{
int differenceX;
int differenceY;
DetermineOffsetDifference(camera, this, out differenceX, out differenceY);
camera.X += differenceX;
camera.Y -= differenceY;
}
}
else
{
bool offsetOrthogonal = lastToModify.Orthogonal;
// Undo what we did before
if (offsetOrthogonal && renderTarget == null)
{
int differenceX;
int differenceY;
DetermineOffsetDifference(camera, lastToModify, out differenceX, out differenceY);
camera.X -= differenceX;
camera.Y += differenceY;
}
}
if (options == SetCameraOptions.ApplyMatrix)
{
// This will set the matrix and individual values...
camera.RotationMatrix = storedRotationMatrix;
// ...now set individual values to make sure they dont change:
camera.mRotationX = storedRotationX;
camera.mRotationY = storedRotationY;
camera.mRotationZ = storedRotationZ;
camera.UpVector = mOldUpVector;
}
else
{
if (ExtraRotationZ != 0)
{
camera.RotationMatrix *= Matrix.CreateFromAxisAngle(camera.RotationMatrix.Backward, ExtraRotationZ);
}
camera.UpVector = camera.RotationMatrix.Up;
}
if (this.OffsetParent != null)
{
camera.Position -= this.OffsetParent.Position;
}
// Set FieldOfView last so it updates the matrices
camera.FieldOfView = FieldOfView;
}
private static void DetermineOffsetDifference(Camera camera, LayerCameraSettings settingsToUse, out int differenceX, out int differenceY)
{
int desiredCenterX = camera.DestinationRectangle.Width / 2;
int actualCenterX = (int)((settingsToUse.LeftDestination + settingsToUse.RightDestination) / 2);
differenceX = actualCenterX - desiredCenterX;
if (settingsToUse.RightDestination != settingsToUse.LeftDestination)
{
float xDifferenceMultipier = settingsToUse.OrthogonalWidth / (settingsToUse.RightDestination - settingsToUse.LeftDestination);
differenceX = (int)(differenceX * xDifferenceMultipier);
}
else
{
differenceX = 0;
}
int desiredCenterY = camera.DestinationRectangle.Height / 2;
int actualCenterY = (int)((settingsToUse.BottomDestination + settingsToUse.TopDestination) / 2);
differenceY = actualCenterY - desiredCenterY;
if (settingsToUse.TopDestination != settingsToUse.BottomDestination)
{
float yDifferenceMultipier = settingsToUse.OrthogonalHeight / (settingsToUse.BottomDestination - settingsToUse.TopDestination);
differenceY = (int)(differenceY * yDifferenceMultipier);
}
else
{
differenceY = 0;
}
}
public void UsePixelCoordinates(Camera valuesToPullFrom)
{
Orthogonal = true;
OrthogonalWidth = valuesToPullFrom.DestinationRectangle.Width;
OrthogonalHeight = valuesToPullFrom.DestinationRectangle.Height;
}
public override string ToString()
{
if (Orthogonal)
{
return "Orthogonal, Destination(" +
TopDestination +", " + LeftDestination + ", " + BottomDestination + ", " + RightDestination + ")";
}
else
{
return "Not Orthogonal";
}
}
}
#endregion
#region XML Docs
/// <summary>
/// Layers are objects which can contain other graphical objects for drawing. Layers
/// are used to create specific ordering and can be used to override depth buffer and
/// z-sorted ordering.
/// </summary>
#endregion
public partial class Layer : INameable, IEquatable<Layer>
{
#region Fields
#region XML Docs
/// <summary>
/// List of Sprites that belong to this layer. Sprites should be added
/// through SpriteManager.AddToLayer or the AddSprite overloads which
/// include a Layer argument.
/// </summary>
#endregion
internal SpriteList mSprites = new SpriteList();
internal SpriteList mZBufferedSprites = new SpriteList();
internal PositionedObjectList<Text> mTexts = new PositionedObjectList<Text>();
internal List<IDrawableBatch> mBatches = new List<IDrawableBatch>();
ReadOnlyCollection<Sprite> mSpritesReadOnlyCollection;
ReadOnlyCollection<Sprite> mZBufferedSpritesReadOnly;
ReadOnlyCollection<Text> mTextsReadOnlyCollection;
ReadOnlyCollection<IDrawableBatch> mBatchesReadOnlyCollection;
// internal so the Renderer can access the lists for drawing
internal PositionedObjectList<AxisAlignedRectangle> mRectangles;
internal PositionedObjectList<Circle> mCircles;
internal PositionedObjectList<Polygon> mPolygons;
internal PositionedObjectList<Line> mLines;
internal PositionedObjectList<Sphere> mSpheres;
internal PositionedObjectList<AxisAlignedCube> mCubes;
internal PositionedObjectList<Capsule2D> mCapsule2Ds;
//ListBuffer<Sprite> mSpriteBuffer;
//ListBuffer<Text> mTextBuffer;
//ListBuffer<PositionedModel> mModelBuffer;
//ListBuffer<IDrawableBatch> mBatchBuffer;
bool mVisible;
bool mRelativeToCamera;
internal SortType mSortType = SortType.Z;
internal Camera mCameraBelongingTo = null;
/// <summary>
/// Used by the Renderer to override the camera's FieldOfView
/// when drawing the layer. This can be used to give each layer
/// a different field of view.
/// </summary>
internal float mOverridingFieldOfView = float.NaN;
string mName;
#endregion
#region Properties
#region XML Docs
/// <summary>
/// The Batches referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular IDrawableBatch PositionedObjectList
/// internally. Since this internal list is used for drawing
/// the layer the engine sorts it every frame.
///
/// For efficiency purposes the internal IDrawableBatch PositionedObjectList
/// cannot be sorted.
/// </remarks>
#endregion
public ReadOnlyCollection<IDrawableBatch> Batches
{
get { return mBatchesReadOnlyCollection; }
}
/// <summary>
/// Stores values which are used to override the camera's properties when this Layer is rendered. By default
/// this is null, indicating the Layer should match the Camera view.
/// </summary>
/// <remarks>
/// A new instance of LayerCameraSettings will be assigned if the UsePixelCoordiantes is called.
/// </remarks>
public LayerCameraSettings LayerCameraSettings
{
get;
set;
}
public Camera CameraBelongingTo
{
get { return mCameraBelongingTo; }
}
public bool IsEmpty
{
get
{
return mSprites.Count == 0 &&
mTexts.Count == 0 &&
mBatches.Count == 0 &&
mRectangles.Count == 0 &&
mCircles.Count == 0 &&
mPolygons.Count == 0 &&
mLines.Count == 0 &&
mSpheres.Count == 0 &&
mCubes.Count == 0 &&
mCapsule2Ds.Count == 0;
}
}
public string Name
{
get { return mName; }
set
{
mName = value;
mSprites.Name = value + " Sprites";
mTexts.Name = value + " Texts";
}
}
//#region XML Docs
///// <summary>
///// The FieldOfView to use when drawing this Layer. If the value is
///// float.NaN (default) then the Camera's FieldOfView is used.
///// </summary>
//#endregion
//public float OverridingFieldOfView
//{
// get { return mOverridingFieldOfView; }
// set { mOverridingFieldOfView = value; }
//}
/// <summary>
/// Controls whether all objects on this layer are drawn relative to the camera. If this value is true, then objects
/// with a position of 0,0 will be positioned at the center of the camera. This value is false by default, which means
/// objects on this layer will be positioned relative to world coordinates.
/// </summary>
/// <remarks>
/// Setting this value to true is an alternative to attaching all objects to the camera. Using this value has a number of
/// benefits:
/// - It removes the overhead of attachment if dealing with a large number of objects
/// - It removes "jittering" which can occur when attaching to a rotating camera
/// </remarks>
public bool RelativeToCamera
{
get { return mRelativeToCamera; }
set { mRelativeToCamera = value; }
}
/// <summary>
/// The Sprites referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular SpriteList internally. Since
/// this internal list is used for drawing the layer the engine
/// sorts it every frame.
/// </remarks>
public ReadOnlyCollection<Sprite> Sprites
{
get { return mSpritesReadOnlyCollection; }
}
public ReadOnlyCollection<Sprite> ZBufferedSprites
{
get { return mZBufferedSpritesReadOnly; }
set { mZBufferedSpritesReadOnly = value; }
}
#region XML Docs
/// <summary>
/// The Texts referenced by and drawn on the Layer.
/// </summary>
/// <remarks>
/// The Layer stores a regular Text PositionedObjectList
/// internally. Since this internal list is used for drawing
/// the layer the engine sorts it every frame.
///
/// For efficiency purposes the internal Text PositionedObjectList
/// cannot be sorted.
/// </remarks>
#endregion
public ReadOnlyCollection<Text> Texts
{
get { return mTextsReadOnlyCollection; }
}
public IEnumerable<AxisAlignedCube> AxisAlignedCubes
{
get
{
return mCubes;
}
}
public IEnumerable<AxisAlignedRectangle> AxisAlignedRectangles
{
get
{
return mRectangles;
}
}
public IEnumerable<Capsule2D> Capsule2Ds
{
get
{
return mCapsule2Ds;
}
}
public IEnumerable<Circle> Circles
{
get
{
return mCircles;
}
}
public IEnumerable<Line> Lines
{
get
{
return mLines;
}
}
public IEnumerable<Polygon> Polygons
{
get
{
return mPolygons;
}
}
public IEnumerable<Sphere> Spheres
{
get
{
return mSpheres;
}
}
/// <summary>
/// The SortType used for visible objects placed on this layer.
/// Only objects on this layer will use this sort type. Each layer
/// can have its own sort type, and unlayered visible objects will use
/// the SpriteManager.OrderedSortType SortType.
/// </summary>
public SortType SortType
{
get { return mSortType; }
set { mSortType = value; }
}
/// <summary>
/// Whether the SpriteLayer is visible.
/// </summary>
/// <remarks>
/// This does not set the contained Sprite's visible value to false.
/// </remarks>
public bool Visible
{
get { return mVisible; }
set { mVisible = value; }
}
/// <summary>
/// The render target to render to. If this is null (default), then the layer
/// will render to whatever render target has been set before FlatRedBall's drawing
/// code starts. If this is non-null, then the layer will render to the RenderTarget.
/// If multiple layers use the same RenderTarget, they will all render to it without clearing
/// it.
/// </summary>
/// <remarks>
/// If a Layer uses a RenderTarget, it will clear the render target if:
/// - It is the UnderAll layer
/// - It is the first Layer on a camera
/// - It uses a different RenderTarget than the previous Layer.
/// </remarks>
public RenderTarget2D RenderTarget
{
get;
set;
}
#endregion
#region Methods
#region Constructor
// This used to be internal, but
// Glue needs to be able to instantiate
// Layers before adding them to managers
// so that it can be done in Initialize before
// we set properties on the Layer like Visible.
public Layer()
{
mSprites.Name = "Layer SpriteList";
mZBufferedSprites.Name = "Layered ZBuffered SpriteList";
mTexts.Name = "Layer Text PositionedObjectList";
mSpritesReadOnlyCollection = new ReadOnlyCollection<Sprite>(mSprites);
mZBufferedSpritesReadOnly = new ReadOnlyCollection<Sprite>(mZBufferedSprites);
mTextsReadOnlyCollection = new ReadOnlyCollection<Text>(mTexts);
mBatchesReadOnlyCollection = new ReadOnlyCollection<IDrawableBatch>(mBatches);
//mSpriteBuffer = new ListBuffer<Sprite>(mSprites);
//mTextBuffer = new ListBuffer<Text>(mTexts);
//mModelBuffer = new ListBuffer<PositionedModel>(mModels);
//mBatchBuffer = new ListBuffer<IDrawableBatch>(mBatches);
mRectangles = new PositionedObjectList<AxisAlignedRectangle>();
mRectangles.Name = "Layered AxisAlignedRectangles";
mCircles = new PositionedObjectList<Circle>();
mCircles.Name = "Layered Circles";
mPolygons = new PositionedObjectList<Polygon>();
mPolygons.Name = "Layered Polygons";
mLines = new PositionedObjectList<Line>();
mLines.Name = "Layered Lines";
mSpheres = new PositionedObjectList<Sphere>();
mSpheres.Name = "Layered Spheres";
mCubes = new PositionedObjectList<AxisAlignedCube>();
mCubes.Name = "Layered Cubes";
mCapsule2Ds = new PositionedObjectList<Capsule2D>();
mCapsule2Ds.Name = "Layered Capsule2Ds";
mVisible = true;
}
#endregion
#region Public Methods
public float PixelsPerUnitAt(float absoluteZ)
{
Camera camera = Camera.Main;
if (this.mCameraBelongingTo != null)
{
camera = this.mCameraBelongingTo;
}
if (this.LayerCameraSettings != null)
{
Vector3 position = new Vector3();
position.Z = absoluteZ;
return camera.PixelsPerUnitAt(ref position, LayerCameraSettings.FieldOfView, LayerCameraSettings.Orthogonal, LayerCameraSettings.OrthogonalHeight);
}
else
{
return camera.PixelsPerUnitAt(absoluteZ);
}
}
public void SortYSpritesSecondary()
{
mSprites.SortYInsertionDescendingOnZBreaks();
}
/// <summary>
/// Directly adds a sprite to the sprite list for this layer.
/// This is faster than using the SpriteManager.AddToLayer method
/// but does no automatic updating and performs a one way add.
/// </summary>
/// <param name="spriteToAdd">The sprite to be added.</param>
public void AddManualSpriteOneWay(Sprite spriteToAdd)
{
mSprites.AddOneWay(spriteToAdd);
}
/// <summary>
/// Removes the argument Sprite from being drawn on this Layer. Note that this does not
/// remove the sprite from the SpriteManager. This method can be used to move a Sprite from
/// one layer to another.
/// </summary>
/// <param name="spriteToRemove">The Sprite to remove from this layer.</param>
public void Remove(Sprite spriteToRemove)
{
if (spriteToRemove.ListsBelongingTo.Contains(mSprites))
{
mSprites.Remove(spriteToRemove);
}
else
{
mZBufferedSprites.Remove(spriteToRemove);
}
}
public void Remove(SpriteFrame spriteFrame)
{
if (spriteFrame.mLayerBelongingTo == this)
{
if (spriteFrame.mCenter != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mCenter);
if (spriteFrame.mTop != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTop);
if (spriteFrame.mBottom != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottom);
if (spriteFrame.mLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mLeft);
if (spriteFrame.mRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mRight);
if (spriteFrame.mTopLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTopLeft);
if (spriteFrame.mTopRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mTopRight);
if (spriteFrame.mBottomLeft != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottomLeft);
if (spriteFrame.mBottomRight != null)
spriteFrame.mLayerBelongingTo.Remove(spriteFrame.mBottomRight);
}
}
public void Remove(Text textToRemove)
{
mTexts.Remove(textToRemove);
}
public void Remove(Scene scene)
{
for (int i = scene.Sprites.Count-1; i > -1; i--)
{
Remove(scene.Sprites[i]);
}
for (int i = scene.SpriteGrids.Count - 1; i > -1 ; i--)
{
SpriteGrid spriteGrid = scene.SpriteGrids[i];
spriteGrid.Layer = null;
}
for (int i = scene.SpriteFrames.Count - 1; i > -1; i--)
{
Remove(scene.SpriteFrames[i]);
}
for (int i = scene.Texts.Count - 1; i > -1; i--)
{
Remove(scene.Texts[i]);
}
}
public void Remove(Circle circle)
{
this.mCircles.Remove(circle);
circle.mLayerBelongingTo = null;
}
public void Remove(AxisAlignedRectangle rectangle)
{
this.mRectangles.Remove(rectangle);
rectangle.mLayerBelongingTo = null;
}
public void Remove(Polygon polygon)
{
this.mPolygons.Remove(polygon);
polygon.mLayerBelongingTo = null;
}
public void Remove(Line line)
{
this.mLines.Remove(line);
line.mLayerBelongingTo = null;
}
public void Remove(Sphere sphere)
{
this.mSpheres.Remove(sphere);
sphere.mLayerBelongingTo = null;
}
public void Remove(AxisAlignedCube cube)
{
this.mCubes.Remove(cube);
cube.mLayerBelongingTo = null;
}
public void Remove(Capsule2D capsule2D)
{
this.mCapsule2Ds.Remove(capsule2D);
capsule2D.mLayerBelongingTo = null;
}
public void Remove(ShapeCollection shapeCollection)
{
foreach (var item in shapeCollection.AxisAlignedCubes) Remove(item);
foreach (var item in shapeCollection.AxisAlignedRectangles) Remove(item);
foreach (var item in shapeCollection.Capsule2Ds) Remove(item);
foreach (var item in shapeCollection.Circles) Remove(item);
foreach (var item in shapeCollection.Lines) Remove(item);
foreach (var item in shapeCollection.Polygons) Remove(item);
foreach (var item in shapeCollection.Spheres) Remove(item);
}
public void Remove(IDrawableBatch batchToRemove)
{
mBatches.Remove(batchToRemove);
}
public void SetLayer(Layer otherLayerToSetPropertiesOn)
{
mSortType = otherLayerToSetPropertiesOn.SortType;
mOverridingFieldOfView = otherLayerToSetPropertiesOn.mOverridingFieldOfView;
if (otherLayerToSetPropertiesOn.LayerCameraSettings == null)
{
LayerCameraSettings = null;
}
else
{
LayerCameraSettings = otherLayerToSetPropertiesOn.LayerCameraSettings.Clone();
}
}
public override string ToString()
{
return "Name: " + mName;
}
/// <summary>
/// Instantiates a new LayerCameraSettings object to store pixel-perfect values.
/// </summary>
public void UsePixelCoordinates()
{
if (LayerCameraSettings == null)
{
LayerCameraSettings = new LayerCameraSettings();
}
if (mCameraBelongingTo != null)
{
LayerCameraSettings.UsePixelCoordinates(mCameraBelongingTo);
}
else
{
LayerCameraSettings.UsePixelCoordinates(SpriteManager.Camera);
}
}
public void WorldToLayerCoordinates(float worldX, float worldY, float worldZ, out float xOnLayer, out float yOnLayer)
{
xOnLayer = 0;
yOnLayer = 0;
int screenX = 0;
int screenY = 0;
MathFunctions.AbsoluteToWindow(worldX, worldY, worldZ, ref screenX, ref screenY, SpriteManager.Camera);
if(this.LayerCameraSettings == null)
{
MathFunctions.WindowToAbsolute(screenX, screenY, ref xOnLayer, ref yOnLayer, worldZ, SpriteManager.Camera, Camera.CoordinateRelativity.RelativeToWorld);
}
else
{
float xEdge = 0;
float yEdge = 0;
if (LayerCameraSettings.Orthogonal)
{
xEdge = LayerCameraSettings.OrthogonalWidth / 2.0f;
yEdge = LayerCameraSettings.OrthogonalHeight / 2.0f;
}
else
{
xEdge = (float)(100 * System.Math.Tan(LayerCameraSettings.FieldOfView / 2.0));
// Right now we just assume the same aspect ratio, but we may want the LayerCamerasettings
// to have its own AspectRatio - if so, this needs to be modified
yEdge = (float)(xEdge * SpriteManager.Camera.AspectRatio);
}
Rectangle destinationRectangle;
if (LayerCameraSettings.LeftDestination > 0 && LayerCameraSettings.TopDestination > 0)
{
destinationRectangle = new Rectangle(
MathFunctions.RoundToInt(LayerCameraSettings.LeftDestination),
MathFunctions.RoundToInt(LayerCameraSettings.RightDestination),
MathFunctions.RoundToInt(LayerCameraSettings.RightDestination - LayerCameraSettings.LeftDestination),
MathFunctions.RoundToInt(LayerCameraSettings.BottomDestination - LayerCameraSettings.TopDestination));
}
else
{
destinationRectangle = SpriteManager.Camera.DestinationRectangle;
}
if (LayerCameraSettings.Orthogonal)
{
Camera camera = SpriteManager.Camera;
float top = camera.Y + LayerCameraSettings.OrthogonalHeight/2.0f;
float left = camera.X - LayerCameraSettings.OrthogonalWidth/2.0f;
float distanceFromLeft = LayerCameraSettings.OrthogonalWidth * screenX / (float)camera.DestinationRectangle.Width;
float distanceFromTop = -LayerCameraSettings.OrthogonalHeight * screenY / (float)camera.DestinationRectangle.Height;
xOnLayer = left + distanceFromLeft;
yOnLayer = top + distanceFromTop;
}
else
{
MathFunctions.WindowToAbsolute(screenX, screenY,
ref xOnLayer, ref yOnLayer, worldZ,
SpriteManager.Camera.Position,
xEdge,
yEdge,
destinationRectangle,
Camera.CoordinateRelativity.RelativeToWorld);
}
}
}
#endregion
#region Internal Methods
internal void Add(Sprite sprite)
{
if (sprite.mOrdered)
{
#if DEBUG
if (mSprites.Contains(sprite))
{
throw new InvalidOperationException("Can't add the Sprite to this layer because it's already added");
}
#endif
mSprites.Add(sprite);
}
else
{
#if DEBUG
if (mZBufferedSprites.Contains(sprite))
{
throw new InvalidOperationException("Can't add the Sprite to this layer because it's already added");
}
#endif
mZBufferedSprites.Add(sprite);
}
}
internal void Add(Text text)
{
#if DEBUG
if (text.mListsBelongingTo.Contains(mTexts))
{
throw new InvalidOperationException("This text is already part of this layer.");
}
#endif
mTexts.Add(text);
}
internal void Add(IDrawableBatch drawableBatch)
{
mBatches.Add(drawableBatch);
}
//internal void Flush()
//{
// mSpriteBuffer.Flush();
// mTextBuffer.Flush();
// mModelBuffer.Flush();
// mBatchBuffer.Flush();
//}
#endregion
#endregion
#region IEquatable<Layer> Members
bool IEquatable<Layer>.Equals(Layer other)
{
return this == other;
}
#endregion
}
}
| |
using System.Windows.Forms;
namespace CslaGenerator.Controls
{
internal partial class GlobalSettings
{
/// <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();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.globalParametersBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.cmdImport = new System.Windows.Forms.Button();
this.cmdExport = new System.Windows.Forms.Button();
this.cmdResetToFactory = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdSave = new System.Windows.Forms.Button();
this.MainTabControl = new System.Windows.Forms.TabControl();
this.GenerationTab = new System.Windows.Forms.TabPage();
this.btnEditDbProviders = new System.Windows.Forms.Button();
this.chkRecompileTemplates = new System.Windows.Forms.CheckBox();
this.chkOverwriteExtendedFile = new System.Windows.Forms.CheckBox();
this.cboCodeEncoding = new System.Windows.Forms.ComboBox();
this.cboSprocEncoding = new System.Windows.Forms.ComboBox();
this.lblCodeEncoding = new System.Windows.Forms.Label();
this.lblSprocEncoding = new System.Windows.Forms.Label();
this.lblCodeEncodingDisplayName = new System.Windows.Forms.Label();
this.lblSprocEncodingDisplayName = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.globalParametersBindingSource)).BeginInit();
this.MainTabControl.SuspendLayout();
this.GenerationTab.SuspendLayout();
this.SuspendLayout();
//
// toolTip
//
this.toolTip.IsBalloon = true;
//this.toolTip.AutomaticDelay = 500;//500
this.toolTip.AutoPopDelay = 15000;//5000
//this.toolTip.InitialDelay = 500;//500
//this.toolTip.ReshowDelay = 100;//100
//
// globalParametersBindingSource
//
this.globalParametersBindingSource.DataSource = typeof(CslaGenerator.Metadata.GlobalParameters);
this.globalParametersBindingSource.CurrentItemChanged += new System.EventHandler(this.GlobalParametersBindingSourceCurrentItemChanged);
//
// cmdImport
//
this.cmdImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cmdImport.Location = new System.Drawing.Point(16, 396);
this.cmdImport.Name = "cmdImport";
this.cmdImport.Size = new System.Drawing.Size(75, 23);
this.cmdImport.TabIndex = 20;
this.cmdImport.Text = "&Import...";
this.cmdImport.UseVisualStyleBackColor = true;
this.cmdImport.Click += new System.EventHandler(this.CmdImportClick);
//
// cmdExport
//
this.cmdExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cmdExport.Location = new System.Drawing.Point(94, 396);
this.cmdExport.Name = "cmdExport";
this.cmdExport.Size = new System.Drawing.Size(75, 23);
this.cmdExport.TabIndex = 20;
this.cmdExport.Text = "&Export...";
this.cmdExport.UseVisualStyleBackColor = true;
this.cmdExport.Click += new System.EventHandler(this.CmdExportClick);
//
// CmdResetToFactory
//
this.cmdResetToFactory.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cmdResetToFactory.Location = new System.Drawing.Point(344, 396);
this.cmdResetToFactory.Name = "cmdResetToFactory";
this.cmdResetToFactory.Size = new System.Drawing.Size(100, 23);
this.cmdResetToFactory.TabIndex = 20;
this.cmdResetToFactory.Text = "&Factory default";
this.cmdResetToFactory.UseVisualStyleBackColor = true;
this.cmdResetToFactory.Click += new System.EventHandler(this.CmdResetToFactoryClick);
//
// cmdCancel
//
this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdCancel.Location = new System.Drawing.Point(391, 396);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(72, 24);
this.cmdCancel.TabIndex = 21;
this.cmdCancel.Text = "&Cancel";
this.cmdCancel.Click += new System.EventHandler(this.CmdCancelClick);
//
// cmdSave
//
this.cmdSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdSave.Location = new System.Drawing.Point(469, 396);
this.cmdSave.Name = "cmdSave";
this.cmdSave.Size = new System.Drawing.Size(72, 24);
this.cmdSave.TabIndex = 22;
this.cmdSave.Text = "&Save";
this.cmdSave.Click += new System.EventHandler(this.CmdSaveClick);
//
// MainTabControl
//
this.MainTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.MainTabControl.Controls.Add(this.GenerationTab);
this.MainTabControl.Location = new System.Drawing.Point(12, 16);
this.MainTabControl.Multiline = true;
this.MainTabControl.Name = "MainTabControl";
this.MainTabControl.SelectedIndex = 0;
this.MainTabControl.Size = new System.Drawing.Size(533, 378);
this.MainTabControl.TabIndex = 3;
//
// GenerationTab
//
this.GenerationTab.Controls.Add(this.lblSprocEncodingDisplayName);
this.GenerationTab.Controls.Add(this.lblCodeEncodingDisplayName);
this.GenerationTab.Controls.Add(this.lblSprocEncoding);
this.GenerationTab.Controls.Add(this.lblCodeEncoding);
this.GenerationTab.Controls.Add(this.cboSprocEncoding);
this.GenerationTab.Controls.Add(this.cboCodeEncoding);
this.GenerationTab.Controls.Add(this.chkOverwriteExtendedFile);
this.GenerationTab.Controls.Add(this.chkRecompileTemplates);
this.GenerationTab.Controls.Add(this.btnEditDbProviders);
this.GenerationTab.Location = new System.Drawing.Point(4, 22);
this.GenerationTab.Name = "GenerationTab";
this.GenerationTab.Size = new System.Drawing.Size(525, 352);
this.GenerationTab.TabIndex = 1;
this.GenerationTab.Text = "Generation";
this.GenerationTab.UseVisualStyleBackColor = true;
//
// lblCodeEncoding
//
this.lblCodeEncoding.Location = new System.Drawing.Point(15, 17);
this.lblCodeEncoding.Name = "lblCodeEncoding";
this.lblCodeEncoding.Size = new System.Drawing.Size(100, 20);
this.lblCodeEncoding.TabIndex = 3;
this.lblCodeEncoding.Text = "Code encoding:";
//
// lblSprocEncoding
//
this.lblSprocEncoding.Location = new System.Drawing.Point(15, 45);
this.lblSprocEncoding.Name = "lblSprocEncoding";
this.lblSprocEncoding.Size = new System.Drawing.Size(100, 20);
this.lblSprocEncoding.TabIndex = 4;
this.lblSprocEncoding.Text = "SProc encoding:";
//
// chkOverwriteExtendedFile
//
this.chkOverwriteExtendedFile.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.globalParametersBindingSource, "OverwriteExtendedFile", true, DataSourceUpdateMode.OnPropertyChanged));
this.chkOverwriteExtendedFile.AutoSize = true;
this.chkOverwriteExtendedFile.Location = new System.Drawing.Point(15, 71);
this.chkOverwriteExtendedFile.Name = "chkOverwriteExtendedFile";
this.chkOverwriteExtendedFile.Size = new System.Drawing.Size(138, 17);
this.chkOverwriteExtendedFile.TabIndex = 0;
this.chkOverwriteExtendedFile.Text = "Overwrite Extended File";
this.chkOverwriteExtendedFile.UseVisualStyleBackColor = true;
this.toolTip.SetToolTip(this.chkOverwriteExtendedFile, "If checked, extended files will be overwritten.\r\n" +
"Unless you use source control, you should backup the extended files before using this option.");
//
// chkRecompileTemplates
//
this.chkRecompileTemplates.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.globalParametersBindingSource, "RecompileTemplates", true, DataSourceUpdateMode.OnPropertyChanged));
this.chkRecompileTemplates.AutoSize = true;
this.chkRecompileTemplates.Location = new System.Drawing.Point(15, 97);
this.chkRecompileTemplates.Name = "chkRecompileTemplates";
this.chkRecompileTemplates.Size = new System.Drawing.Size(138, 17);
this.chkRecompileTemplates.TabIndex = 0;
this.chkRecompileTemplates.Text = "Recompile templates (template development)";
this.chkRecompileTemplates.UseVisualStyleBackColor = true;
this.toolTip.SetToolTip(this.chkRecompileTemplates, "If checked, templates will be recompiled on every generation.\r\n" +
"Unless you are changing the templates, you should uncheck this option.");
//
// btnEditDbProviders
//
this.btnEditDbProviders.AutoSize = true;
this.btnEditDbProviders.Location = new System.Drawing.Point(15, 123);
this.btnEditDbProviders.Name = "btnEditDbProviders";
this.btnEditDbProviders.Size = new System.Drawing.Size(138, 17);
this.btnEditDbProviders.TabIndex = 0;
this.btnEditDbProviders.Text = "Edit DB Providers";
this.btnEditDbProviders.UseVisualStyleBackColor = true;
this.btnEditDbProviders.Click += new System.EventHandler(this.EditDbProvidersClick);
//
// cboCodeEncoding
//
this.cboCodeEncoding.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.cboCodeEncoding.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cboCodeEncoding.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.globalParametersBindingSource, "CodeEncoding", true, DataSourceUpdateMode.OnPropertyChanged));
this.cboCodeEncoding.FormattingEnabled = true;
this.cboCodeEncoding.Location = new System.Drawing.Point(115, 15);
this.cboCodeEncoding.Name = "cboCodeEncoding";
this.cboCodeEncoding.Size = new System.Drawing.Size(155, 21);
this.cboCodeEncoding.TabIndex = 1;
this.toolTip.SetToolTip(this.cboCodeEncoding, "Select the encoding to use for code generation (.cs or .vb files).");
//
// cboSprocEncoding
//
this.cboSprocEncoding.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.cboSprocEncoding.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cboSprocEncoding.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.globalParametersBindingSource, "SprocEncoding", true, DataSourceUpdateMode.OnPropertyChanged));
this.cboSprocEncoding.FormattingEnabled = true;
this.cboSprocEncoding.Location = new System.Drawing.Point(115, 43);
this.cboSprocEncoding.Name = "cboSprocEncoding";
this.cboSprocEncoding.Size = new System.Drawing.Size(155, 21);
this.cboSprocEncoding.TabIndex = 2;
this.toolTip.SetToolTip(this.cboSprocEncoding, "Select the encoding to use for stored procedures generation (.sql files).");
//
// lblCodeEncodingDisplayName
//
this.lblCodeEncodingDisplayName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.globalParametersBindingSource, "CodeEncodingDisplayName", true, DataSourceUpdateMode.OnPropertyChanged));
this.lblCodeEncodingDisplayName.Location = new System.Drawing.Point(290, 17);
this.lblCodeEncodingDisplayName.Name = "lblCodeEncodingDisplayName";
this.lblCodeEncodingDisplayName.Size = new System.Drawing.Size(300, 20);
this.lblCodeEncodingDisplayName.TabIndex = 5;
//
// lblSprocEncodingDisplayName
//
this.lblSprocEncodingDisplayName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.globalParametersBindingSource, "SprocEncodingDisplayName", true, DataSourceUpdateMode.OnPropertyChanged));
this.lblSprocEncodingDisplayName.Location = new System.Drawing.Point(290, 45);
this.lblSprocEncodingDisplayName.Name = "lblSprocEncodingDisplayName";
this.lblSprocEncodingDisplayName.Size = new System.Drawing.Size(300, 20);
this.lblSprocEncodingDisplayName.TabIndex = 6;
//
// GlobalSettings
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(557, 425);
this.Controls.Add(this.cmdSave);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdResetToFactory);
this.Controls.Add(this.cmdExport);
this.Controls.Add(this.cmdImport);
this.Controls.Add(this.MainTabControl);
this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.Document)));
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "GlobalSettings";
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document;
this.TabText = "Global Settings";
this.Text = "Global Settings";
this.Shown += new System.EventHandler(this.GlobalSettings_Shown);
this.ResizeBegin += new System.EventHandler(this.GlobalSettings_ResizeBegin);
this.ResizeEnd += new System.EventHandler(this.GlobalSettings_ResizeEnd);
((System.ComponentModel.ISupportInitialize)(this.globalParametersBindingSource)).EndInit();
this.MainTabControl.ResumeLayout(false);
this.GenerationTab.ResumeLayout(false);
this.GenerationTab.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.Button cmdImport;
private System.Windows.Forms.Button cmdExport;
internal System.Windows.Forms.Button cmdResetToFactory;
private System.Windows.Forms.Button cmdCancel;
internal System.Windows.Forms.Button cmdSave;
private System.Windows.Forms.TabControl MainTabControl;
private System.Windows.Forms.TabPage GenerationTab;
private System.Windows.Forms.BindingSource globalParametersBindingSource;
private Label lblSprocEncodingDisplayName;
private Label lblCodeEncodingDisplayName;
private Label lblSprocEncoding;
private Label lblCodeEncoding;
private ComboBox cboSprocEncoding;
private ComboBox cboCodeEncoding;
private CheckBox chkOverwriteExtendedFile;
private CheckBox chkRecompileTemplates;
private Button btnEditDbProviders;
}
}
| |
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Models;
using AllReady.Services;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Moq;
using Xunit;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
using AllReady.Extensions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using AllReady.Areas.Admin.ViewModels.Campaign;
using AllReady.Areas.Admin.ViewModels.Shared;
using Shouldly;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class CampaignAdminControllerTests
{
[Fact]
public async Task IndexSendsIndexQueryWithCorrectData_WhenUserIsOrgAdmin()
{
const int organizationId = 99;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.Index();
mockMediator.Verify(mock => mock.SendAsync(It.Is<IndexQuery>(q => q.OrganizationId == organizationId)));
}
[Fact]
public async Task IndexSendsIndexQueryWithCorrectData_WhenUserIsNotOrgAdmin()
{
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserNotAnOrgAdmin();
await sut.Index();
mockMediator.Verify(mock => mock.SendAsync(It.Is<IndexQuery>(q => q.OrganizationId == null)));
}
[Fact]
public async Task DetailsSendsCampaignDetailQueryWithCorrectCampaignId()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
await sut.Details(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == campaignId)));
}
[Fact]
public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull()
{
CampaignController sut;
MockMediatorCampaignDetailQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin()
{
var sut = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
var sut = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewModelWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
const int campaignId = 100;
const int organizationId = 99;
var mockMediator = new Mock<IMediator>();
// model is not null
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId, Id = campaignId }).Verifiable();
// user is org admin
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var view = (ViewResult)(await sut.Details(campaignId));
var viewModel = (CampaignDetailViewModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, campaignId);
Assert.Equal(viewModel.OrganizationId, organizationId);
}
[Fact]
public void CreateReturnsCorrectViewWithCorrectViewModel()
{
var sut = new CampaignController(null, null);
var view = (ViewResult) sut.Create();
var viewModel = (CampaignSummaryViewModel)view.ViewData.Model;
Assert.Equal(view.ViewName, "Edit");
Assert.NotNull(viewModel);
}
[Fact]
public void CreateReturnsCorrectDataOnViewModel()
{
var dateTimeNow = DateTime.Now;
var sut = new CampaignController(null, null) { DateTimeNow = () => dateTimeNow };
var view = (ViewResult)sut.Create();
var viewModel = (CampaignSummaryViewModel)view.ViewData.Model;
Assert.Equal(viewModel.StartDate, dateTimeNow);
Assert.Equal(viewModel.EndDate, dateTimeNow.AddMonths(1));
}
[Fact]
public async Task EditGetSendsCampaignSummaryQueryWithCorrectCampaignId()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
await sut.Edit(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == campaignId)));
}
[Fact]
public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull()
{
CampaignController sut;
MockMediatorCampaignSummaryQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditPostReturnsBadRequestWhenCampaignIsNull()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await sut.Edit(null, null);
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task EditPostAddsCorrectKeyAndErrorMessageToModelStateWhenCampaignEndDateIsLessThanCampainStartDate()
{
var campaignSummaryModel = new CampaignSummaryViewModel { OrganizationId = 1, StartDate = DateTime.Now.AddDays(1), EndDate = DateTime.Now.AddDays(-1) };
var sut = new CampaignController(null, null);
sut.MakeUserAnOrgAdmin(campaignSummaryModel.OrganizationId.ToString());
await sut.Edit(campaignSummaryModel, null);
var modelStateErrorCollection = sut.ModelState.GetErrorMessagesByKey(nameof(CampaignSummaryViewModel.EndDate));
Assert.Equal(modelStateErrorCollection.Single().ErrorMessage, "The end date must fall on or after the start date.");
}
[Fact]
public async Task EditPostInsertsCampaign()
{
const int organizationId = 99;
const int newCampaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>())).ReturnsAsync(newCampaignId);
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var model = MassiveTrafficLightOutageModel;
model.OrganizationId = organizationId;
// verify the model is valid
var validationContext = new ValidationContext(model, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(model, validationContext, validationResults);
Assert.Equal(0, validationResults.Count());
var file = FormFile("image/jpeg");
var view = (RedirectToActionResult)await sut.Edit(model, file);
// verify the edit(add) is called
mockMediator.Verify(mock => mock.SendAsync(It.Is<EditCampaignCommand>(c => c.Campaign.OrganizationId == organizationId)));
// verify that the next route
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], newCampaignId);
}
[Fact]
public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
var result = await sut.Edit(new CampaignSummaryViewModel { OrganizationId = It.IsAny<int>() }, null);
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>())).ReturnsAsync(campaignId);
var sut = new CampaignController(mockMediator.Object, new Mock<IImageService>().Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var result = (RedirectToActionResult)await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId }, null);
Assert.Equal(result.ActionName, "Details");
Assert.Equal(result.RouteValues["area"], "Admin");
Assert.Equal(result.RouteValues["id"], campaignId);
}
[Fact]
public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var file = FormFile("");
await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file);
Assert.False(sut.ModelState.IsValid);
Assert.Equal(sut.ModelState["ImageUrl"].Errors.Single().ErrorMessage, "You must upload a valid image file for the logo (.jpg, .png, .gif)");
}
[Fact]
public async Task EditPostReturnsCorrectViewModelWhenInvalidImageFormatIsSupplied()
{
const int organizationId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var file = FormFile("audio/mpeg3");
var model = MassiveTrafficLightOutageModel;
model.OrganizationId = organizationId;
var view = await sut.Edit(model, file) as ViewResult;
var viewModel = view.ViewData.Model as CampaignSummaryViewModel;
Assert.True(ReferenceEquals(model, viewModel));
}
[Fact]
public async Task EditPostInvokesUploadCampaignImageAsyncWithTheCorrectParameters_WhenFileUploadIsNotNull_AndFileIsAcceptableContentType()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var file = FormFile("image/jpeg");
await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId }, file);
mockImageService.Verify(mock => mock.UploadCampaignImageAsync(
It.Is<int>(i => i == organizationId),
It.Is<int>(i => i == campaignId),
It.Is<IFormFile>(i => i == file)), Times.Once);
}
[Fact]
public async Task EditPostInvokesDeleteImageAsync_WhenCampaignHasAnImage()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var file = FormFile("image/jpeg");
mockImageService.Setup(x => x.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), file)).ReturnsAsync("newImageUrl");
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = organizationId,
ImageUrl = "existingImageUrl",
Id = campaignId,
StartDate = new DateTimeOffset(new DateTime(2016, 2, 13)),
EndDate = new DateTimeOffset(new DateTime(2016, 2, 14)),
};
await sut.Edit(campaignSummaryViewModel, file);
mockImageService.Verify(mock => mock.DeleteImageAsync(It.Is<string>(x => x == "existingImageUrl")), Times.Once);
}
[Fact]
public async Task EditPostDoesNotInvokeDeleteImageAsync__WhenCampaignDoesNotHaveAnImage()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var file = FormFile("image/jpeg");
mockImageService.Setup(x => x.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), file)).ReturnsAsync("newImageUrl");
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = organizationId,
Id = campaignId,
StartDate = new DateTimeOffset(new DateTime(2016, 2, 13)),
EndDate = new DateTimeOffset(new DateTime(2016, 2, 14)),
};
await sut.Edit(campaignSummaryViewModel, file);
mockImageService.Verify(mock => mock.DeleteImageAsync(It.IsAny<string>()), Times.Never);
}
[Fact]
public void EditPostHasHttpPostAttribute()
{
var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void EditPostHasValidateAntiForgeryTokenttribute()
{
var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
[Fact]
public async Task PublishSendsPublishQueryWithCorrectCampaignId()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<PublishViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new PublishViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.Publish(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<PublishViewModelQuery>(c => c.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task PublishReturnsHttpNotFoundResultWhenCampaignIsNotFound()
{
CampaignController sut;
MockMediatorCampaignSummaryQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Publish(It.IsAny<int>()));
}
[Fact]
public async Task PublishReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<PublishViewModelQuery>())).ReturnsAsync(new PublishViewModel());
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserNotAnOrgAdmin();
Assert.IsType<UnauthorizedResult>(await sut.Publish(It.IsAny<int>()));
}
[Fact]
public async Task PublishReturnsCorrectViewWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<PublishViewModelQuery>())).ReturnsAsync(new PublishViewModel { OrganizationId = organizationId });
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
Assert.IsType<ViewResult>(await sut.Publish(It.IsAny<int>()));
}
[Fact]
public async Task PublishReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<PublishViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new PublishViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var view = (ViewResult)await sut.Publish(campaignId);
var viewModel = (PublishViewModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, campaignId);
}
[Fact]
public async Task DeleteSendsDeleteQueryWithCorrectCampaignId()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new DeleteViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.Delete(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound()
{
CampaignController sut;
MockMediatorCampaignSummaryQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<DeleteViewModelQuery>())).ReturnsAsync(new DeleteViewModel());
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserNotAnOrgAdmin();
Assert.IsType<UnauthorizedResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<DeleteViewModelQuery>())).ReturnsAsync(new DeleteViewModel { OrganizationId = organizationId });
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
Assert.IsType<ViewResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new DeleteViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var view = (ViewResult)await sut.Delete(campaignId);
var viewModel = (DeleteViewModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, campaignId);
}
[Fact]
public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfNotFound()
{
var mediatorMock = new Mock<IMediator>();
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
var result = await sut.DeleteCampaignImage(It.IsAny<int>());
result.ShouldNotBeNull();
result.ShouldBeOfType<JsonResult>();
result.Value.GetType()
.GetProperty("status")
.GetValue(result.Value)
.ShouldBe("NotFound");
}
[Fact]
public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfUnauthorizedIfUserIsNotOrganizationAdmin()
{
var mediatorMock = new Mock<IMediator>();
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryViewModel());
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserNotAnOrgAdmin();
var result = await sut.DeleteCampaignImage(It.IsAny<int>());
result.Value.GetType()
.GetProperty("status")
.GetValue(result.Value)
.ShouldBe("Unauthorized");
}
[Fact]
public async Task DeleteCampaignSendsTheCorrectIdToCampaignSummaryQuery()
{
var mediatorMock = new Mock<IMediator>();
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
const int campaignId = 2;
await sut.DeleteCampaignImage(campaignId);
mediatorMock.Verify(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>()), Times.Once);
mediatorMock.Verify(m => m.SendAsync(It.Is<CampaignSummaryQuery>(s => s.CampaignId == campaignId)));
}
[Fact]
public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfDateInvalidIfCampaignEndDateIsLessThanStartDate()
{
var mediatorMock = new Mock<IMediator>();
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = 1,
StartDate = DateTimeOffset.Now.AddDays(10),
EndDate = DateTimeOffset.Now
};
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());
var result = await sut.DeleteCampaignImage(It.IsAny<int>());
result.Value.GetType()
.GetProperty("status")
.GetValue(result.Value)
.ShouldBe("DateInvalid");
result.Value.GetType()
.GetProperty("message")
.GetValue(result.Value)
.ShouldBe("The end date must fall on or after the start date.");
}
[Fact]
public async Task DeleteCampaignImageCallsDeleteImageAsyncWithCorrectData()
{
var mediatorMock = new Mock<IMediator>();
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = 1,
ImageUrl = "URL!"
};
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());
await sut.DeleteCampaignImage(It.IsAny<int>());
imageServiceMock.Verify(i => i.DeleteImageAsync(It.Is<string>(f => f == "URL!")), Times.Once);
}
[Fact]
public async Task DeleteCampaignImageCallsEditCampaignCommandWithCorrectData()
{
var mediatorMock = new Mock<IMediator>();
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = 1,
ImageUrl = "URL!"
};
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());
await sut.DeleteCampaignImage(It.IsAny<int>());
mediatorMock.Verify(m => m.SendAsync(It.Is<EditCampaignCommand>(s => s.Campaign == campaignSummaryViewModel)), Times.Once);
}
[Fact]
public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfSuccessIfImageDeletedSuccessfully()
{
var mediatorMock = new Mock<IMediator>();
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = 1,
ImageUrl = "URL!"
};
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());
var result = await sut.DeleteCampaignImage(It.IsAny<int>());
result.Value.GetType()
.GetProperty("status")
.GetValue(result.Value)
.ShouldBe("Success");
}
[Fact]
public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfNothingToDeleteIfThereWasNoExistingImage()
{
var mediatorMock = new Mock<IMediator>();
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = 1
};
mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);
var imageServiceMock = new Mock<IImageService>();
var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());
var result = await sut.DeleteCampaignImage(It.IsAny<int>());
result.Value.GetType()
.GetProperty("status")
.GetValue(result.Value)
.ShouldBe("NothingToDelete");
}
[Fact(Skip ="Broken Test")]
public async Task DeleteConfirmedSendsDeleteCampaignCommandWithCorrectCampaignId()
{
var viewModel = new DeleteViewModel {Id = 1 , OrganizationId = 1};
var mediator = new Mock<IMediator>();
mediator.Setup(a => a.SendAsync(It.IsAny<DeleteCampaignCommand>())).Verifiable();
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserAnOrgAdmin(viewModel.OrganizationId.ToString());
await sut.DeleteConfirmed(viewModel);
mediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var sut = new CampaignController(Mock.Of<IMediator>(), null);
Assert.IsType<UnauthorizedResult>(await sut.DeleteConfirmed(new DeleteViewModel { UserIsOrgAdmin = false }));
}
[Fact]
public async Task DetailConfirmedSendsDeleteCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mockMediator = new Mock<IMediator>();
var viewModel = new DeleteViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.DeleteConfirmed(viewModel);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task DetailConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var viewModel = new DeleteViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(Mock.Of<IMediator>(), null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var routeValues = new Dictionary<string, object> { ["area"] = "Admin" };
var result = await sut.DeleteConfirmed(viewModel) as RedirectToActionResult;
Assert.Equal(result.ActionName, nameof(CampaignController.Index));
Assert.Equal(result.RouteValues, routeValues);
}
[Fact]
public void DeleteConfirmedHasHttpPostAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void DeleteConfirmedHasActionNameAttributeWithCorrectName()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<ActionNameAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(attribute.Name, "Delete");
}
[Fact]
public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact(Skip = "Broken Test")]
public async Task PublishConfirmedSendsPublishCampaignCommandWithCorrectCampaignId()
{
var viewModel = new PublishViewModel { Id = 1 };
var mediator = new Mock<IMediator>();
var sut = new CampaignController(mediator.Object, null);
await sut.PublishConfirmed(viewModel);
mediator.Verify(mock => mock.SendAsync(It.Is<PublishCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task PublishConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var sut = new CampaignController(Mock.Of<IMediator>(), null);
Assert.IsType<UnauthorizedResult>(await sut.PublishConfirmed(new PublishViewModel { UserIsOrgAdmin = false }));
}
[Fact]
public async Task PublishConfirmedSendsPublishCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mockMediator = new Mock<IMediator>();
var viewModel = new PublishViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.PublishConfirmed(viewModel);
mockMediator.Verify(mock => mock.SendAsync(It.Is<PublishCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task PublishConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var viewModel = new PublishViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(Mock.Of<IMediator>(), null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var routeValues = new Dictionary<string, object> { ["area"] = "Admin" };
var result = await sut.PublishConfirmed(viewModel) as RedirectToActionResult;
Assert.Equal(result.ActionName, nameof(CampaignController.Index));
Assert.Equal(result.RouteValues, routeValues);
}
[Fact]
public void PublishConfirmedHasHttpPostAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.PublishConfirmed(It.IsAny<PublishViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void PublishConfirmedHasActionNameAttributeWithCorrectName()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.PublishConfirmed(It.IsAny<PublishViewModel>())).OfType<ActionNameAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(attribute.Name, "Publish");
}
[Fact]
public void PublishConfirmedHasValidateAntiForgeryTokenAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.PublishConfirmed(It.IsAny<PublishViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task LockUnlockReturnsHttpUnauthorizedResultWhenUserIsNotSiteAdmin()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
sut.MakeUserAnOrgAdmin("1");
Assert.IsType<UnauthorizedResult>(await sut.LockUnlock(100));
}
[Fact]
public async Task LockUnlockSendsLockUnlockCampaignCommandWithCorrectCampaignIdWhenUserIsSiteAdmin()
{
const int campaignId = 99;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserASiteAdmin();
await sut.LockUnlock(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<LockUnlockCampaignCommand>(q => q.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task LockUnlockRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsSiteAdmin()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserASiteAdmin();
var view = (RedirectToActionResult)await sut.LockUnlock(campaignId);
// verify the next route
Assert.Equal(view.ActionName, nameof(CampaignController.Details));
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], campaignId);
}
[Fact]
public void LockUnlockHasHttpPostAttribute()
{
var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void LockUnlockdHasValidateAntiForgeryTokenAttribute()
{
var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
private static CampaignController CreateCampaignControllerWithNoInjectedDependencies()
{
return new CampaignController(null, null);
}
private static Mock<IMediator> MockMediatorCampaignDetailQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static Mock<IMediator> MockMediatorCampaignSummaryQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static CampaignController CampaignControllerWithDetailQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId }).Verifiable();
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return sut;
}
private static CampaignController CampaignControllerWithSummaryQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel { OrganizationId = organizationId, Location = new LocationEditViewModel() }).Verifiable();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return sut;
}
private static IFormFile FormFile(string fileType)
{
var mockFormFile = new Mock<IFormFile>();
mockFormFile.Setup(mock => mock.ContentType).Returns(fileType);
return mockFormFile.Object;
}
private static LocationEditViewModel BogusAveModel => new LocationEditViewModel
{
Address1 = "25 Bogus Ave",
City = "Agincourt",
State = "Ontario",
Country = "Canada",
PostalCode = "M1T2T9"
};
private static CampaignSummaryViewModel MassiveTrafficLightOutageModel => new CampaignSummaryViewModel
{
Description = "Preparations to be ready to deal with a wide-area traffic outage.",
EndDate = DateTime.Today.AddMonths(1),
ExternalUrl = "http://agincourtaware.trafficlightoutage.com",
ExternalUrlText = "Agincourt Aware: Traffic Light Outage",
Featured = false,
FileUpload = null,
FullDescription = "<h1><strong>Massive Traffic Light Outage Plan</strong></h1>\r\n<p>The Massive Traffic Light Outage Plan (MTLOP) is the official plan to handle a major traffic light failure.</p>\r\n<p>In the event of a wide-area traffic light outage, an alternative method of controlling traffic flow will be necessary. The MTLOP calls for the recruitment and training of volunteers to be ready to direct traffic at designated intersections and to schedule and follow-up with volunteers in the event of an outage.</p>",
Id = 0,
ImageUrl = null,
Location = BogusAveModel,
Locked = false,
Name = "Massive Traffic Light Outage Plan",
PrimaryContactEmail = "[email protected]",
PrimaryContactFirstName = "Miles",
PrimaryContactLastName = "Long",
PrimaryContactPhoneNumber = "416-555-0119",
StartDate = DateTime.Today,
TimeZoneId = "Eastern Standard Time",
};
}
}
| |
// 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.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_InvalidParametersAndStrangeFiles
{
private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, String Message) where TException : Exception
{
try
{
Assert.Throws<TException>(() =>
{
using (ZipArchive archive = constructor()) { }
});
}
catch (Exception e)
{
Console.WriteLine(string.Format("{0}: {1}", Message, e.ToString()));
throw;
}
}
[Fact]
public static async Task InvalidInstanceMethods()
{
Stream zipFile = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
{
//non-existent entry
Assert.True(null == archive.GetEntry("nonExistentEntry")); //"Should return null on non-existent entry name"
//null/empty string
Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); //"Should throw on null entry name"
ZipArchiveEntry entry = archive.GetEntry("first.txt");
//null/empty string
Assert.Throws<ArgumentException>(() => archive.CreateEntry("")); //"Should throw on empty entry name"
Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); //"should throw on null entry name"
}
}
[Fact]
public static void InvalidConstructors()
{
//out of range enum values
ConstructorThrows<ArgumentOutOfRangeException>(() =>
new ZipArchive(new MemoryStream(), (ZipArchiveMode)(-1)), "Out of range enum");
ConstructorThrows<ArgumentOutOfRangeException>(() =>
new ZipArchive(new MemoryStream(), (ZipArchiveMode)(4)), "out of range enum");
ConstructorThrows<ArgumentOutOfRangeException>(() =>
new ZipArchive(new MemoryStream(), (ZipArchiveMode)(10)), "Out of range enum");
//null/closed stream
ConstructorThrows<ArgumentNullException>(() =>
new ZipArchive((Stream)null, ZipArchiveMode.Read), "Null/closed stream");
ConstructorThrows<ArgumentNullException>(() =>
new ZipArchive((Stream)null, ZipArchiveMode.Create), "Null/closed stream");
ConstructorThrows<ArgumentNullException>(() =>
new ZipArchive((Stream)null, ZipArchiveMode.Update), "Null/closed stream");
MemoryStream ms = new MemoryStream();
ms.Dispose();
ConstructorThrows<ArgumentException>(() =>
new ZipArchive(ms, ZipArchiveMode.Read), "Disposed Base Stream");
ConstructorThrows<ArgumentException>(() =>
new ZipArchive(ms, ZipArchiveMode.Create), "Disposed Base Stream");
ConstructorThrows<ArgumentException>(() =>
new ZipArchive(ms, ZipArchiveMode.Update), "Disposed Base Stream");
//non-seekable to update
using (LocalMemoryStream nonReadable = new LocalMemoryStream(),
nonWriteable = new LocalMemoryStream(),
nonSeekable = new LocalMemoryStream())
{
nonReadable.SetCanRead(false);
nonWriteable.SetCanWrite(false);
nonSeekable.SetCanSeek(false);
ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Read), "Non readable stream");
ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Create), "Non-writable stream");
ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Update), "Non-readable stream");
ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Update), "Non-writable stream");
ConstructorThrows<ArgumentException>(() => new ZipArchive(nonSeekable, ZipArchiveMode.Update), "Non-seekable stream");
}
}
[Theory]
[InlineData("LZMA.zip")]
[InlineData("invalidDeflate.zip")]
public static async Task ZipArchiveEntry_InvalidUpdate(String zipname)
{
string filename = ZipTest.bad(zipname);
Stream updatedCopy = await StreamHelpers.CreateTempCopyStream(filename);
String name;
Int64 length, compressedLength;
DateTimeOffset lastWriteTime;
using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update, true))
{
ZipArchiveEntry e = archive.Entries[0];
name = e.FullName;
lastWriteTime = e.LastWriteTime;
length = e.Length;
compressedLength = e.CompressedLength;
Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open"
}
//make sure that update mode preserves that unreadable file
using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update))
{
ZipArchiveEntry e = archive.Entries[0];
Assert.Equal(name, e.FullName); //"Name isn't the same"
Assert.Equal(lastWriteTime, e.LastWriteTime); //"LastWriteTime not the same"
Assert.Equal(length, e.Length); //"Length isn't the same"
Assert.Equal(compressedLength, e.CompressedLength); //"CompressedLength isn't the same"
Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open"
}
}
[Theory]
[InlineData("CDoffsetOutOfBounds.zip")]
[InlineData("EOCDmissing.zip")]
public static async Task ZipArchive_InvalidStream(String zipname)
{
string filename = ZipTest.bad(zipname);
using (var stream = await StreamHelpers.CreateTempCopyStream(filename))
Assert.Throws<InvalidDataException>(() => new ZipArchive(stream, ZipArchiveMode.Read));
}
[Theory]
[InlineData("CDoffsetInBoundsWrong.zip")]
[InlineData("numberOfEntriesDifferent.zip")]
public static async Task ZipArchive_InvalidEntryTable(String zipname)
{
string filename = ZipTest.bad(zipname);
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read))
Assert.Throws<InvalidDataException>(() => archive.Entries[0]);
}
[Theory]
[InlineData("compressedSizeOutOfBounds.zip", true)]
[InlineData("localFileHeaderSignatureWrong.zip", true)]
[InlineData("localFileOffsetOutOfBounds.zip", true)]
[InlineData("LZMA.zip", true)]
[InlineData("invalidDeflate.zip", false)]
public static async Task ZipArchive_InvalidEntry(String zipname, Boolean throwsOnOpen)
{
string filename = ZipTest.bad(zipname);
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read))
{
ZipArchiveEntry e = archive.Entries[0];
if (throwsOnOpen)
{
Assert.Throws<InvalidDataException>(() => e.Open()); //"should throw on open"
}
else
{
using (Stream s = e.Open())
{
Assert.Throws<InvalidDataException>(() => s.ReadByte()); //"Unreadable stream"
}
}
}
}
[Fact]
public static async Task ZipArchiveEntry_InvalidLastWriteTime_Read()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(
ZipTest.bad("invaliddate.zip")), ZipArchiveMode.Read))
{
Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); //"Date isn't correct on invalid date"
}
}
[Fact]
public static void ZipArchiveEntry_InvalidLastWriteTime_Write()
{
using (ZipArchive archive = new ZipArchive(new MemoryStream(), ZipArchiveMode.Create))
{
ZipArchiveEntry entry = archive.CreateEntry("test");
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
//"should throw on bad date"
entry.LastWriteTime = new DateTimeOffset(1979, 12, 3, 5, 6, 2, new TimeSpan());
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
//"Should throw on bad date"
entry.LastWriteTime = new DateTimeOffset(2980, 12, 3, 5, 6, 2, new TimeSpan());
});
}
}
[Theory]
[InlineData("extradata/extraDataLHandCDentryAndArchiveComments.zip", "verysmall", false)]
[InlineData("extradata/extraDataThenZip64.zip", "verysmall", false)]
[InlineData("extradata/zip64ThenExtraData.zip", "verysmall", false)]
[InlineData("dataDescriptor.zip", "normalWithoutBinary", true)]
[InlineData("filenameTimeAndSizesDifferentInLH.zip", "verysmall", true)]
public static async Task StrangeFiles(string zipFile, string zipFolder, bool dontRequireExplicit)
{
ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(ZipTest.strange(zipFile)), ZipTest.zfolder(zipFolder), ZipArchiveMode.Update, dontRequireExplicit, dontCheckTimes: 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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.libc.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.libc.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
// has varying degrees of support on different systems.
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
const int bufferSize = FileStream.DefaultBufferSize;
const bool useAsync = false;
using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
src.CopyTo(dst);
}
// Now copy over relevant read/write/execute permissions from the source to the destination
Interop.libcoreclr.fileinfo fileinfo;
while (Interop.CheckIo(Interop.libcoreclr.GetFileInformationFromPath(sourceFullPath, out fileinfo), sourceFullPath)) ;
int newMode = fileinfo.mode & (int)Interop.libc.Permissions.Mask;
while (Interop.CheckIo(Interop.libc.chmod(destFullPath, newMode), destFullPath)) ;
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
while (Interop.libc.link(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again
{
continue;
}
else if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
break;
}
else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
while (Interop.libc.unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again
{
continue;
}
else if (errorInfo.Error == Interop.Error.ENOENT) // already doesn't exist; nop
{
break;
}
else
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
Interop.ErrorInfo errorInfo = default(Interop.ErrorInfo);
while ((result = Interop.libc.mkdir(name, (int)Interop.libc.Permissions.S_IRWXU)) < 0 && (errorInfo = Interop.Sys.GetLastErrorInfo()).Error == Interop.Error.EINTR) ;
if (result < 0 && firstError.Error == 0)
{
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
while (Interop.libc.rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EINTR: // interrupted; try again
continue;
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
while (Interop.libc.rmdir(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EINTR: // interrupted; try again
continue;
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Interop.libcoreclr.fileinfo fileinfo;
while (true)
{
errorInfo = default(Interop.ErrorInfo);
int result = Interop.libcoreclr.GetFileInformationFromPath(fullPath, out fileinfo);
if (result < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR)
{
continue;
}
return false;
}
return (fileinfo.mode & Interop.libcoreclr.FileTypes.S_IFMT) == fileType;
}
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, new UnixFileSystemObject(path, isDir)));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)) :
(FileSystemInfo)new FileInfo(path, new UnixFileSystemObject(path, isDir)));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Interop.libc.SafeDirHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
IntPtr curEntry;
while ((curEntry = Interop.libc.readdir(dirHandle)) != IntPtr.Zero) // no validation needed for readdir
{
string name = Interop.libc.GetDirEntName(curEntry);
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory,
// e.g. a FIFO will be classified as a file.
bool isDir;
switch (Interop.libc.GetDirEntType(curEntry))
{
case Interop.libc.DType.DT_DIR:
// We know it's a directory.
isDir = true;
break;
case Interop.libc.DType.DT_LNK:
case Interop.libc.DType.DT_UNKNOWN:
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, name), out errnoIgnored);
break;
default:
// Otherwise, treat it as a file. This includes regular files,
// FIFOs, etc.
isDir = false;
break;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(name))
{
if (_includeDirectories &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/true);
}
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
toExplore.Push(new PathPair(Path.Combine(dirPath.UserPath, name), Path.Combine(dirPath.FullPath, name)));
}
}
}
else if (_includeFiles &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Interop.libc.SafeDirHandle OpenDirectory(string fullPath)
{
Interop.libc.SafeDirHandle handle = Interop.libc.opendir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.libc.getcwd();
}
public override void SetCurrentDirectory(string fullPath)
{
while (Interop.CheckIo(Interop.libc.chdir(fullPath), fullPath)) ;
}
public override FileAttributes GetAttributes(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new UnixFileSystemObject(fullPath, false).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return new UnixFileSystemObject(fullPath, asDirectory);
}
}
}
| |
using UnityEngine;
using System.Collections;
public class phone_Transform_localPosition : MonoBehaviour {
Vector3[] animVar;
float deltaTime;
float startTime;
void Start(){
startTime = Time.time;
deltaTime = 1f/60f;
animVar = new Vector3[560];
animVar[0] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[1] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[2] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[3] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[4] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[5] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[6] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[7] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[8] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[9] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[10] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[11] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[12] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[13] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[14] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[15] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[16] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[17] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[18] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[19] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[20] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[21] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[22] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[23] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[24] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[25] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[26] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[27] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[28] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[29] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[30] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[31] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[32] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[33] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[34] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[35] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[36] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[37] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[38] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[39] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[40] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[41] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[42] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[43] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[44] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[45] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[46] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[47] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[48] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[49] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[50] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[51] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[52] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[53] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[54] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[55] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[56] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[57] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[58] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[59] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[60] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[61] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[62] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[63] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[64] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[65] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[66] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[67] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[68] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[69] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[70] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[71] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[72] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[73] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[74] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[75] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[76] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[77] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[78] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[79] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[80] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[81] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[82] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[83] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[84] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[85] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[86] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[87] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[88] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[89] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[90] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[91] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[92] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[93] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[94] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[95] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[96] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[97] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[98] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[99] = new Vector3(0.872000f,0.000000f,0.000000f);
animVar[100] = new Vector3(0.871999f,0.000000f,0.000000f);
animVar[101] = new Vector3(0.871147f,0.000000f,0.000000f);
animVar[102] = new Vector3(0.868791f,0.000000f,0.000000f);
animVar[103] = new Vector3(0.865022f,0.000000f,0.000000f);
animVar[104] = new Vector3(0.859930f,0.000000f,0.000000f);
animVar[105] = new Vector3(0.853607f,0.000000f,0.000000f);
animVar[106] = new Vector3(0.846144f,0.000000f,0.000000f);
animVar[107] = new Vector3(0.837631f,0.000000f,0.000000f);
animVar[108] = new Vector3(0.828158f,0.000000f,0.000000f);
animVar[109] = new Vector3(0.817818f,0.000000f,0.000000f);
animVar[110] = new Vector3(0.806701f,0.000000f,0.000000f);
animVar[111] = new Vector3(0.794897f,0.000000f,0.000000f);
animVar[112] = new Vector3(0.782498f,0.000000f,0.000000f);
animVar[113] = new Vector3(0.769595f,0.000000f,0.000000f);
animVar[114] = new Vector3(0.756278f,0.000000f,0.000000f);
animVar[115] = new Vector3(0.742638f,0.000000f,0.000000f);
animVar[116] = new Vector3(0.728767f,0.000000f,0.000000f);
animVar[117] = new Vector3(0.714754f,0.000000f,0.000000f);
animVar[118] = new Vector3(0.700692f,0.000000f,0.000000f);
animVar[119] = new Vector3(0.686670f,0.000000f,0.000000f);
animVar[120] = new Vector3(0.672779f,0.000000f,0.000000f);
animVar[121] = new Vector3(0.659112f,0.000000f,0.000000f);
animVar[122] = new Vector3(0.645757f,0.000000f,0.000000f);
animVar[123] = new Vector3(0.632807f,0.000000f,0.000000f);
animVar[124] = new Vector3(0.620352f,0.000000f,0.000000f);
animVar[125] = new Vector3(0.608483f,0.000000f,0.000000f);
animVar[126] = new Vector3(0.597291f,0.000000f,0.000000f);
animVar[127] = new Vector3(0.586867f,0.000000f,0.000000f);
animVar[128] = new Vector3(0.577301f,0.000000f,0.000000f);
animVar[129] = new Vector3(0.568685f,0.000000f,0.000000f);
animVar[130] = new Vector3(0.561109f,0.000000f,0.000000f);
animVar[131] = new Vector3(0.554665f,0.000000f,0.000000f);
animVar[132] = new Vector3(0.549443f,0.000000f,0.000000f);
animVar[133] = new Vector3(0.545533f,0.000000f,0.000000f);
animVar[134] = new Vector3(0.543028f,0.000000f,0.000000f);
animVar[135] = new Vector3(0.542017f,0.000000f,0.000000f);
animVar[136] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[137] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[138] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[139] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[140] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[141] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[142] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[143] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[144] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[145] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[146] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[147] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[148] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[149] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[150] = new Vector3(0.542000f,0.000000f,0.000000f);
animVar[151] = new Vector3(0.541934f,0.000000f,0.000000f);
animVar[152] = new Vector3(0.541035f,0.000000f,0.000000f);
animVar[153] = new Vector3(0.539116f,0.000000f,0.000000f);
animVar[154] = new Vector3(0.536217f,0.000000f,0.000000f);
animVar[155] = new Vector3(0.532377f,0.000000f,0.000000f);
animVar[156] = new Vector3(0.527636f,0.000000f,0.000000f);
animVar[157] = new Vector3(0.522034f,0.000000f,0.000000f);
animVar[158] = new Vector3(0.515610f,0.000000f,0.000000f);
animVar[159] = new Vector3(0.508405f,0.000000f,0.000000f);
animVar[160] = new Vector3(0.500458f,0.000000f,0.000000f);
animVar[161] = new Vector3(0.491808f,0.000000f,0.000000f);
animVar[162] = new Vector3(0.482496f,0.000000f,0.000000f);
animVar[163] = new Vector3(0.472561f,0.000000f,0.000000f);
animVar[164] = new Vector3(0.462043f,0.000000f,0.000000f);
animVar[165] = new Vector3(0.450982f,0.000000f,0.000000f);
animVar[166] = new Vector3(0.439417f,0.000000f,0.000000f);
animVar[167] = new Vector3(0.427388f,0.000000f,0.000000f);
animVar[168] = new Vector3(0.414935f,0.000000f,0.000000f);
animVar[169] = new Vector3(0.402097f,0.000000f,0.000000f);
animVar[170] = new Vector3(0.388915f,0.000000f,0.000000f);
animVar[171] = new Vector3(0.375427f,0.000000f,0.000000f);
animVar[172] = new Vector3(0.361675f,0.000000f,0.000000f);
animVar[173] = new Vector3(0.347696f,0.000000f,0.000000f);
animVar[174] = new Vector3(0.333532f,0.000000f,0.000000f);
animVar[175] = new Vector3(0.319222f,0.000000f,0.000000f);
animVar[176] = new Vector3(0.304805f,0.000000f,0.000000f);
animVar[177] = new Vector3(0.290322f,0.000000f,0.000000f);
animVar[178] = new Vector3(0.275811f,0.000000f,0.000000f);
animVar[179] = new Vector3(0.261314f,0.000000f,0.000000f);
animVar[180] = new Vector3(0.246869f,0.000000f,0.000000f);
animVar[181] = new Vector3(0.232516f,0.000000f,0.000000f);
animVar[182] = new Vector3(0.218295f,0.000000f,0.000000f);
animVar[183] = new Vector3(0.204246f,0.000000f,0.000000f);
animVar[184] = new Vector3(0.190408f,0.000000f,0.000000f);
animVar[185] = new Vector3(0.176821f,0.000000f,0.000000f);
animVar[186] = new Vector3(0.163525f,0.000000f,0.000000f);
animVar[187] = new Vector3(0.150560f,0.000000f,0.000000f);
animVar[188] = new Vector3(0.137965f,0.000000f,0.000000f);
animVar[189] = new Vector3(0.125780f,0.000000f,0.000000f);
animVar[190] = new Vector3(0.114044f,0.000000f,0.000000f);
animVar[191] = new Vector3(0.102799f,0.000000f,0.000000f);
animVar[192] = new Vector3(0.092082f,0.000000f,0.000000f);
animVar[193] = new Vector3(0.081934f,0.000000f,0.000000f);
animVar[194] = new Vector3(0.072395f,0.000000f,0.000000f);
animVar[195] = new Vector3(0.063504f,0.000000f,0.000000f);
animVar[196] = new Vector3(0.055302f,0.000000f,0.000000f);
animVar[197] = new Vector3(0.047827f,0.000000f,0.000000f);
animVar[198] = new Vector3(0.041120f,0.000000f,0.000000f);
animVar[199] = new Vector3(0.035220f,0.000000f,0.000000f);
animVar[200] = new Vector3(0.030166f,0.000000f,0.000000f);
animVar[201] = new Vector3(0.026000f,0.000000f,0.000000f);
animVar[202] = new Vector3(0.022434f,0.000000f,0.000000f);
animVar[203] = new Vector3(0.019151f,0.000000f,0.000000f);
animVar[204] = new Vector3(0.016141f,0.000000f,0.000000f);
animVar[205] = new Vector3(0.013395f,0.000000f,0.000000f);
animVar[206] = new Vector3(0.010904f,0.000000f,0.000000f);
animVar[207] = new Vector3(0.008660f,0.000000f,0.000000f);
animVar[208] = new Vector3(0.006654f,0.000000f,0.000000f);
animVar[209] = new Vector3(0.004876f,0.000000f,0.000000f);
animVar[210] = new Vector3(0.003317f,0.000000f,0.000000f);
animVar[211] = new Vector3(0.001969f,0.000000f,0.000000f);
animVar[212] = new Vector3(0.000823f,0.000000f,0.000000f);
animVar[213] = new Vector3(-0.000130f,0.000000f,0.000000f);
animVar[214] = new Vector3(-0.000900f,0.000000f,0.000000f);
animVar[215] = new Vector3(-0.001495f,0.000000f,0.000000f);
animVar[216] = new Vector3(-0.001924f,0.000000f,0.000000f);
animVar[217] = new Vector3(-0.002196f,0.000000f,0.000000f);
animVar[218] = new Vector3(-0.002320f,0.000000f,0.000000f);
animVar[219] = new Vector3(-0.002305f,0.000000f,0.000000f);
animVar[220] = new Vector3(-0.002160f,0.000000f,0.000000f);
animVar[221] = new Vector3(-0.001894f,0.000000f,0.000000f);
animVar[222] = new Vector3(-0.001516f,0.000000f,0.000000f);
animVar[223] = new Vector3(-0.001035f,0.000000f,0.000000f);
animVar[224] = new Vector3(-0.000459f,0.000000f,0.000000f);
animVar[225] = new Vector3(0.000202f,0.000000f,0.000000f);
animVar[226] = new Vector3(0.000939f,0.000000f,0.000000f);
animVar[227] = new Vector3(0.001744f,0.000000f,0.000000f);
animVar[228] = new Vector3(0.002607f,0.000000f,0.000000f);
animVar[229] = new Vector3(0.003519f,0.000000f,0.000000f);
animVar[230] = new Vector3(0.004472f,0.000000f,0.000000f);
animVar[231] = new Vector3(0.005457f,0.000000f,0.000000f);
animVar[232] = new Vector3(0.006464f,0.000000f,0.000000f);
animVar[233] = new Vector3(0.007486f,0.000000f,0.000000f);
animVar[234] = new Vector3(0.008511f,0.000000f,0.000000f);
animVar[235] = new Vector3(0.009533f,0.000000f,0.000000f);
animVar[236] = new Vector3(0.010541f,0.000000f,0.000000f);
animVar[237] = new Vector3(0.011528f,0.000000f,0.000000f);
animVar[238] = new Vector3(0.012483f,0.000000f,0.000000f);
animVar[239] = new Vector3(0.013398f,0.000000f,0.000000f);
animVar[240] = new Vector3(0.014264f,0.000000f,0.000000f);
animVar[241] = new Vector3(0.015072f,0.000000f,0.000000f);
animVar[242] = new Vector3(0.015814f,0.000000f,0.000000f);
animVar[243] = new Vector3(0.016479f,0.000000f,0.000000f);
animVar[244] = new Vector3(0.017060f,0.000000f,0.000000f);
animVar[245] = new Vector3(0.017547f,0.000000f,0.000000f);
animVar[246] = new Vector3(0.017932f,0.000000f,0.000000f);
animVar[247] = new Vector3(0.018204f,0.000000f,0.000000f);
animVar[248] = new Vector3(0.018357f,0.000000f,0.000000f);
animVar[249] = new Vector3(0.018379f,0.000000f,0.000000f);
animVar[250] = new Vector3(0.018263f,0.000000f,0.000000f);
animVar[251] = new Vector3(0.018000f,0.000000f,0.000000f);
animVar[252] = new Vector3(0.017624f,0.000000f,0.000000f);
animVar[253] = new Vector3(0.017182f,0.000000f,0.000000f);
animVar[254] = new Vector3(0.016681f,0.000000f,0.000000f);
animVar[255] = new Vector3(0.016127f,0.000000f,0.000000f);
animVar[256] = new Vector3(0.015528f,0.000000f,0.000000f);
animVar[257] = new Vector3(0.014891f,0.000000f,0.000000f);
animVar[258] = new Vector3(0.014223f,0.000000f,0.000000f);
animVar[259] = new Vector3(0.013531f,0.000000f,0.000000f);
animVar[260] = new Vector3(0.012822f,0.000000f,0.000000f);
animVar[261] = new Vector3(0.012104f,0.000000f,0.000000f);
animVar[262] = new Vector3(0.011383f,0.000000f,0.000000f);
animVar[263] = new Vector3(0.010667f,0.000000f,0.000000f);
animVar[264] = new Vector3(0.009962f,0.000000f,0.000000f);
animVar[265] = new Vector3(0.009276f,0.000000f,0.000000f);
animVar[266] = new Vector3(0.008616f,0.000000f,0.000000f);
animVar[267] = new Vector3(0.007989f,0.000000f,0.000000f);
animVar[268] = new Vector3(0.007402f,0.000000f,0.000000f);
animVar[269] = new Vector3(0.006862f,0.000000f,0.000000f);
animVar[270] = new Vector3(0.006376f,0.000000f,0.000000f);
animVar[271] = new Vector3(0.005952f,0.000000f,0.000000f);
animVar[272] = new Vector3(0.005596f,0.000000f,0.000000f);
animVar[273] = new Vector3(0.005316f,0.000000f,0.000000f);
animVar[274] = new Vector3(0.005119f,0.000000f,0.000000f);
animVar[275] = new Vector3(0.005011f,0.000000f,0.000000f);
animVar[276] = new Vector3(0.005000f,0.000000f,0.000000f);
animVar[277] = new Vector3(0.005074f,0.000000f,0.000000f);
animVar[278] = new Vector3(0.005214f,0.000000f,0.000000f);
animVar[279] = new Vector3(0.005417f,0.000000f,0.000000f);
animVar[280] = new Vector3(0.005681f,0.000000f,0.000000f);
animVar[281] = new Vector3(0.006002f,0.000000f,0.000000f);
animVar[282] = new Vector3(0.006378f,0.000000f,0.000000f);
animVar[283] = new Vector3(0.006806f,0.000000f,0.000000f);
animVar[284] = new Vector3(0.007284f,0.000000f,0.000000f);
animVar[285] = new Vector3(0.007808f,0.000000f,0.000000f);
animVar[286] = new Vector3(0.008376f,0.000000f,0.000000f);
animVar[287] = new Vector3(0.008985f,0.000000f,0.000000f);
animVar[288] = new Vector3(0.009632f,0.000000f,0.000000f);
animVar[289] = new Vector3(0.010314f,0.000000f,0.000000f);
animVar[290] = new Vector3(0.011029f,0.000000f,0.000000f);
animVar[291] = new Vector3(0.011774f,0.000000f,0.000000f);
animVar[292] = new Vector3(0.012546f,0.000000f,0.000000f);
animVar[293] = new Vector3(0.013342f,0.000000f,0.000000f);
animVar[294] = new Vector3(0.014160f,0.000000f,0.000000f);
animVar[295] = new Vector3(0.014996f,0.000000f,0.000000f);
animVar[296] = new Vector3(0.015848f,0.000000f,0.000000f);
animVar[297] = new Vector3(0.016713f,0.000000f,0.000000f);
animVar[298] = new Vector3(0.017589f,0.000000f,0.000000f);
animVar[299] = new Vector3(0.018472f,0.000000f,0.000000f);
animVar[300] = new Vector3(0.019360f,0.000000f,0.000000f);
animVar[301] = new Vector3(0.020250f,0.000000f,0.000000f);
animVar[302] = new Vector3(0.021139f,0.000000f,0.000000f);
animVar[303] = new Vector3(0.022025f,0.000000f,0.000000f);
animVar[304] = new Vector3(0.022904f,0.000000f,0.000000f);
animVar[305] = new Vector3(0.023774f,0.000000f,0.000000f);
animVar[306] = new Vector3(0.024632f,0.000000f,0.000000f);
animVar[307] = new Vector3(0.025475f,0.000000f,0.000000f);
animVar[308] = new Vector3(0.026301f,0.000000f,0.000000f);
animVar[309] = new Vector3(0.027107f,0.000000f,0.000000f);
animVar[310] = new Vector3(0.027889f,0.000000f,0.000000f);
animVar[311] = new Vector3(0.028646f,0.000000f,0.000000f);
animVar[312] = new Vector3(0.029374f,0.000000f,0.000000f);
animVar[313] = new Vector3(0.030071f,0.000000f,0.000000f);
animVar[314] = new Vector3(0.030733f,0.000000f,0.000000f);
animVar[315] = new Vector3(0.031358f,0.000000f,0.000000f);
animVar[316] = new Vector3(0.031944f,0.000000f,0.000000f);
animVar[317] = new Vector3(0.032487f,0.000000f,0.000000f);
animVar[318] = new Vector3(0.032985f,0.000000f,0.000000f);
animVar[319] = new Vector3(0.033434f,0.000000f,0.000000f);
animVar[320] = new Vector3(0.033833f,0.000000f,0.000000f);
animVar[321] = new Vector3(0.034178f,0.000000f,0.000000f);
animVar[322] = new Vector3(0.034467f,0.000000f,0.000000f);
animVar[323] = new Vector3(0.034696f,0.000000f,0.000000f);
animVar[324] = new Vector3(0.034863f,0.000000f,0.000000f);
animVar[325] = new Vector3(0.034965f,0.000000f,0.000000f);
animVar[326] = new Vector3(0.035000f,0.000000f,0.000000f);
animVar[327] = new Vector3(0.034941f,0.000000f,0.000000f);
animVar[328] = new Vector3(0.034772f,0.000000f,0.000000f);
animVar[329] = new Vector3(0.034499f,0.000000f,0.000000f);
animVar[330] = new Vector3(0.034132f,0.000000f,0.000000f);
animVar[331] = new Vector3(0.033680f,0.000000f,0.000000f);
animVar[332] = new Vector3(0.033151f,0.000000f,0.000000f);
animVar[333] = new Vector3(0.032554f,0.000000f,0.000000f);
animVar[334] = new Vector3(0.031897f,0.000000f,0.000000f);
animVar[335] = new Vector3(0.031190f,0.000000f,0.000000f);
animVar[336] = new Vector3(0.030440f,0.000000f,0.000000f);
animVar[337] = new Vector3(0.029657f,0.000000f,0.000000f);
animVar[338] = new Vector3(0.028848f,0.000000f,0.000000f);
animVar[339] = new Vector3(0.028024f,0.000000f,0.000000f);
animVar[340] = new Vector3(0.027191f,0.000000f,0.000000f);
animVar[341] = new Vector3(0.026360f,0.000000f,0.000000f);
animVar[342] = new Vector3(0.025538f,0.000000f,0.000000f);
animVar[343] = new Vector3(0.024735f,0.000000f,0.000000f);
animVar[344] = new Vector3(0.023958f,0.000000f,0.000000f);
animVar[345] = new Vector3(0.023217f,0.000000f,0.000000f);
animVar[346] = new Vector3(0.022520f,0.000000f,0.000000f);
animVar[347] = new Vector3(0.021876f,0.000000f,0.000000f);
animVar[348] = new Vector3(0.021293f,0.000000f,0.000000f);
animVar[349] = new Vector3(0.020780f,0.000000f,0.000000f);
animVar[350] = new Vector3(0.020347f,0.000000f,0.000000f);
animVar[351] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[352] = new Vector3(0.019720f,0.000000f,0.000000f);
animVar[353] = new Vector3(0.019480f,0.000000f,0.000000f);
animVar[354] = new Vector3(0.019277f,0.000000f,0.000000f);
animVar[355] = new Vector3(0.019109f,0.000000f,0.000000f);
animVar[356] = new Vector3(0.018973f,0.000000f,0.000000f);
animVar[357] = new Vector3(0.018869f,0.000000f,0.000000f);
animVar[358] = new Vector3(0.018793f,0.000000f,0.000000f);
animVar[359] = new Vector3(0.018743f,0.000000f,0.000000f);
animVar[360] = new Vector3(0.018718f,0.000000f,0.000000f);
animVar[361] = new Vector3(0.018715f,0.000000f,0.000000f);
animVar[362] = new Vector3(0.018732f,0.000000f,0.000000f);
animVar[363] = new Vector3(0.018766f,0.000000f,0.000000f);
animVar[364] = new Vector3(0.018816f,0.000000f,0.000000f);
animVar[365] = new Vector3(0.018880f,0.000000f,0.000000f);
animVar[366] = new Vector3(0.018955f,0.000000f,0.000000f);
animVar[367] = new Vector3(0.019040f,0.000000f,0.000000f);
animVar[368] = new Vector3(0.019131f,0.000000f,0.000000f);
animVar[369] = new Vector3(0.019228f,0.000000f,0.000000f);
animVar[370] = new Vector3(0.019327f,0.000000f,0.000000f);
animVar[371] = new Vector3(0.019427f,0.000000f,0.000000f);
animVar[372] = new Vector3(0.019525f,0.000000f,0.000000f);
animVar[373] = new Vector3(0.019620f,0.000000f,0.000000f);
animVar[374] = new Vector3(0.019709f,0.000000f,0.000000f);
animVar[375] = new Vector3(0.019790f,0.000000f,0.000000f);
animVar[376] = new Vector3(0.019861f,0.000000f,0.000000f);
animVar[377] = new Vector3(0.019919f,0.000000f,0.000000f);
animVar[378] = new Vector3(0.019963f,0.000000f,0.000000f);
animVar[379] = new Vector3(0.019991f,0.000000f,0.000000f);
animVar[380] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[381] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[382] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[383] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[384] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[385] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[386] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[387] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[388] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[389] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[390] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[391] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[392] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[393] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[394] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[395] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[396] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[397] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[398] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[399] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[400] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[401] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[402] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[403] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[404] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[405] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[406] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[407] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[408] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[409] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[410] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[411] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[412] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[413] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[414] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[415] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[416] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[417] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[418] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[419] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[420] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[421] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[422] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[423] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[424] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[425] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[426] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[427] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[428] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[429] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[430] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[431] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[432] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[433] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[434] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[435] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[436] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[437] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[438] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[439] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[440] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[441] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[442] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[443] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[444] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[445] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[446] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[447] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[448] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[449] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[450] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[451] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[452] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[453] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[454] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[455] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[456] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[457] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[458] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[459] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[460] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[461] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[462] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[463] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[464] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[465] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[466] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[467] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[468] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[469] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[470] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[471] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[472] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[473] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[474] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[475] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[476] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[477] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[478] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[479] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[480] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[481] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[482] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[483] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[484] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[485] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[486] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[487] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[488] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[489] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[490] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[491] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[492] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[493] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[494] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[495] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[496] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[497] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[498] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[499] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[500] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[501] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[502] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[503] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[504] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[505] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[506] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[507] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[508] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[509] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[510] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[511] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[512] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[513] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[514] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[515] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[516] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[517] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[518] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[519] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[520] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[521] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[522] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[523] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[524] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[525] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[526] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[527] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[528] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[529] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[530] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[531] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[532] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[533] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[534] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[535] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[536] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[537] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[538] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[539] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[540] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[541] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[542] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[543] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[544] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[545] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[546] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[547] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[548] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[549] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[550] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[551] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[552] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[553] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[554] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[555] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[556] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[557] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[558] = new Vector3(0.020000f,0.000000f,0.000000f);
animVar[559] = new Vector3(0.020000f,0.000000f,0.000000f);
comp = gameObject.GetComponent<Transform>();
}
Transform comp;
public float numFrame;
void Update () {
numFrame = (Time.time-startTime)/deltaTime;
if( numFrame>=(float)animVar.Length-1 ) {numFrame=(float)animVar.Length-1.01f;}
float alpha = numFrame-Mathf.Floor(numFrame)/deltaTime;
comp.localPosition = Vector3.Lerp(animVar[Mathf.FloorToInt(numFrame)],animVar[Mathf.CeilToInt(numFrame)],alpha);
}
}
| |
/*
* 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.Data;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
private string m_connectionString;
protected static SqliteConnection m_Connection;
private static bool m_initialized = false;
public SQLiteAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
if (!m_initialized)
{
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
Migration m = new Migration(m_Connection, GetType().Assembly, "AuthStore");
m.Update();
m_initialized = true;
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID");
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
IDataReader result = ExecuteReader(cmd, m_Connection);
try
{
if (result.Read())
{
ret.PrincipalID = principalID;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
catch
{
}
finally
{
//CloseCommand(cmd);
}
return null;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
string[] values = new string[data.Data.Count];
int i = 0;
foreach (object o in data.Data.Values)
values[i++] = o.ToString();
SqliteCommand cmd = new SqliteCommand();
if (Get(data.PrincipalID) != null)
{
string update = "update `" + m_Realm + "` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = :" + field;
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
first = false;
}
update += " where UUID = :UUID";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
cmd.CommandText = update;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
//CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
m_log.Error("[SQLITE]: Exception storing authentication data", e);
//CloseCommand(cmd);
return false;
}
}
else
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (:UUID, :" + String.Join(", :", fields) + ")";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
foreach (string field in fields)
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
cmd.CommandText = insert;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
//CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
//CloseCommand(cmd);
return false;
}
}
//CloseCommand(cmd);
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
SqliteCommand cmd = new SqliteCommand("update `" + m_Realm +
"` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
"', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
" minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
private void DoExpire()
{
SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')");
ExecuteNonQuery(cmd, m_Connection);
cmd.Dispose();
m_LastExpire = System.Environment.TickCount;
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, 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.UnitTests.Conditions
{
using NLog.Internal;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using Xunit;
public class ConditionParserTests : NLogTestBase
{
[Fact]
public void ParseNullText()
{
Assert.Null(ConditionParser.ParseExpression(null));
}
[Fact]
public void ParseEmptyText()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression(""));
}
[Fact]
public void ImplicitOperatorTest()
{
ConditionExpression cond = "true and true";
Assert.IsType<ConditionAndExpression>(cond);
}
[Fact]
public void NullLiteralTest()
{
Assert.Equal("null", ConditionParser.ParseExpression("null").ToString());
}
[Fact]
public void BooleanLiteralTest()
{
Assert.Equal("True", ConditionParser.ParseExpression("true").ToString());
Assert.Equal("True", ConditionParser.ParseExpression("tRuE").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("false").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("fAlSe").ToString());
}
[Fact]
public void AndTest()
{
Assert.Equal("(True and True)", ConditionParser.ParseExpression("true and true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE AND true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("true and true && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE AND true and true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE && true AND true").ToString());
}
[Fact]
public void OrTest()
{
Assert.Equal("(True or True)", ConditionParser.ParseExpression("true or true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE OR true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("true or true || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE OR true or true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE || true OR true").ToString());
}
[Fact]
public void NotTest()
{
Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString());
Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString());
Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString());
}
[Fact]
public void StringTest()
{
Assert.Equal("''", ConditionParser.ParseExpression("''").ToString());
Assert.Equal("'Foo'", ConditionParser.ParseExpression("'Foo'").ToString());
Assert.Equal("'Bar'", ConditionParser.ParseExpression("'Bar'").ToString());
Assert.Equal("'d'Artagnan'", ConditionParser.ParseExpression("'d''Artagnan'").ToString());
var cle = ConditionParser.ParseExpression("'${message} ${level}'") as ConditionLayoutExpression;
Assert.NotNull(cle);
SimpleLayout sl = cle.Layout as SimpleLayout;
Assert.NotNull(sl);
Assert.Equal(3, sl.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(sl.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(sl.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(sl.Renderers[2]);
}
[Fact]
public void LogLevelTest()
{
var result = ConditionParser.ParseExpression("LogLevel.Info") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Info, result.LiteralValue);
result = ConditionParser.ParseExpression("LogLevel.Trace") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Trace, result.LiteralValue);
}
[Fact]
public void RelationalOperatorTest()
{
RelationalOperatorTestInner("=", "==");
RelationalOperatorTestInner("==", "==");
RelationalOperatorTestInner("!=", "!=");
RelationalOperatorTestInner("<>", "!=");
RelationalOperatorTestInner("<", "<");
RelationalOperatorTestInner(">", ">");
RelationalOperatorTestInner("<=", "<=");
RelationalOperatorTestInner(">=", ">=");
}
[Fact]
public void NumberTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("3.141592").ToString());
Assert.Equal("42", ConditionParser.ParseExpression("42").ToString());
Assert.Equal("-42", ConditionParser.ParseExpression("-42").ToString());
Assert.Equal("-3.141592", ConditionParser.ParseExpression("-3.141592").ToString());
}
[Fact]
public void ExtraParenthesisTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString());
}
[Fact]
public void MessageTest()
{
var result = ConditionParser.ParseExpression("message");
Assert.IsType<ConditionMessageExpression>(result);
Assert.Equal("message", result.ToString());
}
[Fact]
public void LevelTest()
{
var result = ConditionParser.ParseExpression("level");
Assert.IsType<ConditionLevelExpression>(result);
Assert.Equal("level", result.ToString());
}
[Fact]
public void LoggerTest()
{
var result = ConditionParser.ParseExpression("logger");
Assert.IsType<ConditionLoggerNameExpression>(result);
Assert.Equal("logger", result.ToString());
}
[Fact]
public void ConditionFunctionTests()
{
var result = ConditionParser.ParseExpression("starts-with(logger, 'x${message}')") as ConditionMethodExpression;
Assert.NotNull(result);
Assert.Equal("starts-with(logger, 'x${message}')", result.ToString());
Assert.Equal("StartsWith", result.MethodInfo.Name);
Assert.Equal(typeof(ConditionMethods), result.MethodInfo.DeclaringType);
}
[Fact]
public void CustomNLogFactoriesTest()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory);
}
[Fact]
public void MethodNameWithUnderscores()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory);
}
[Fact]
public void UnbalancedParenthesis1Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("check("));
}
[Fact]
public void UnbalancedParenthesis2Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("((1)"));
}
[Fact]
public void UnbalancedParenthesis3Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("(1))"));
}
[Fact]
public void LogLevelWithoutAName()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("LogLevel.'somestring'"));
}
[Fact]
public void InvalidNumberWithUnaryMinusTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-a31"));
}
[Fact]
public void InvalidNumberTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-123.4a"));
}
[Fact]
public void UnclosedString()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("'Hello world"));
}
[Fact]
public void UnrecognizedToken()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("somecompletelyunrecognizedtoken"));
}
[Fact]
public void UnrecognizedPunctuation()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("#"));
}
[Fact]
public void UnrecognizedUnicodeChar()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0090"));
}
[Fact]
public void UnrecognizedUnicodeChar2()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0015"));
}
[Fact]
public void UnrecognizedMethod()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("unrecognized-method()"));
}
[Fact]
public void TokenizerEOFTest()
{
var tokenizer = new ConditionTokenizer(new SimpleStringReader(string.Empty));
Assert.Throws<ConditionParseException>(() => tokenizer.GetNextToken());
}
private void RelationalOperatorTestInner(string op, string result)
{
string operand1 = "3";
string operand2 = "7";
string input = operand1 + " " + op + " " + operand2;
string expectedOutput = "(" + operand1 + " " + result + " " + operand2 + ")";
var condition = ConditionParser.ParseExpression(input);
Assert.Equal(expectedOutput, condition.ToString());
}
public class FooLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
throw new System.NotImplementedException();
}
}
public class MyConditionMethods
{
public static bool CheckIt(string s)
{
return s == "X";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
namespace UnitTests.GrainInterfaces
{
public interface IGenericGrain<T, U> : IGrainWithIntegerKey
{
Task SetT(T a);
Task<U> MapT2U();
}
public interface ISimpleGenericGrain1<T> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, T b);
Task SetA(T a);
Task SetB(T b);
}
/// <summary>
/// Long named grain type, which can cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISimpleGenericGrainUsingAzureTableStorage<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
/// <summary>
/// Short named grain type, which shouldn't cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITinyNameGrain<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
public interface ISimpleGenericGrainU<U> : IGrainWithIntegerKey
{
Task<U> GetA();
Task<string> GetAxB();
Task<string> GetAxB(U a, U b);
Task SetA(U a);
Task SetB(U b);
}
public interface ISimpleGenericGrain2<T, in U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IGenericGrainWithNoProperties<in T> : IGrainWithIntegerKey
{
Task<string> GetAxB(T a, T b);
}
public interface IGrainWithNoProperties : IGrainWithIntegerKey
{
Task<string> GetAxB(int a, int b);
}
public interface IGrainWithListFields : IGrainWithIntegerKey
{
Task AddItem(string item);
Task<IList<string>> GetItems();
}
public interface IGenericGrainWithListFields<T> : IGrainWithIntegerKey
{
Task AddItem(T item);
Task<IList<T>> GetItems();
}
public interface IGenericReader1<T> : IGrainWithIntegerKey
{
Task<T> GetValue();
}
public interface IGenericWriter1<in T> : IGrainWithIntegerKey
{
Task SetValue(T value);
}
public interface IGenericReaderWriterGrain1<T> : IGenericWriter1<T>, IGenericReader1<T>
{
}
public interface IGenericReader2<TOne, TTwo> : IGrainWithIntegerKey
{
Task<TOne> GetValue1();
Task<TTwo> GetValue2();
}
public interface IGenericWriter2<in TOne, in TTwo> : IGrainWithIntegerKey
{
Task SetValue1(TOne value);
Task SetValue2(TTwo value);
}
public interface IGenericReaderWriterGrain2<TOne, TTwo> : IGenericWriter2<TOne, TTwo>, IGenericReader2<TOne, TTwo>
{
}
public interface IGenericReader3<TOne, TTwo, TThree> : IGenericReader2<TOne, TTwo>
{
Task<TThree> GetValue3();
}
public interface IGenericWriter3<in TOne, in TTwo, in TThree> : IGenericWriter2<TOne, TTwo>
{
Task SetValue3(TThree value);
}
public interface IGenericReaderWriterGrain3<TOne, TTwo, TThree> : IGenericWriter3<TOne, TTwo, TThree>, IGenericReader3<TOne, TTwo, TThree>
{
}
public interface IBasicGenericGrain<T, U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IHubGrain<TKey, T1, T2> : IGrainWithIntegerKey
{
Task Bar(TKey key, T1 message1, T2 message2);
}
public interface IEchoHubGrain<TKey, TMessage> : IHubGrain<TKey, TMessage, TMessage>
{
Task Foo(TKey key, TMessage message, int x);
Task<int> GetX();
}
public interface IEchoGenericChainGrain<T> : IGrainWithIntegerKey
{
Task<T> Echo(T item);
Task<T> Echo2(T item);
Task<T> Echo3(T item);
Task<T> Echo4(T item);
Task<T> Echo5(T item);
Task<T> Echo6(T item);
}
public interface INonGenericBase : IGrainWithGuidKey
{
Task Ping();
}
public interface IGeneric1Argument<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
}
public interface IGeneric2Arguments<T, U> : IGrainWithIntegerKey
{
Task<Tuple<T, U>> Ping(T t, U u);
}
public interface IDbGrain<T> : IGrainWithIntegerKey
{
Task SetValue(T value);
Task<T> GetValue();
}
public interface IGenericPingSelf<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
Task<T> PingSelf(T t);
Task<T> PingOther(IGenericPingSelf<T> target, T t);
Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t);
Task<T> GetLastValue();
Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay);
Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay);
}
public interface ILongRunningTaskGrain<T> : IGrainWithGuidKey
{
Task<string> GetRuntimeInstanceId();
Task<T> LongRunningTask(T t, TimeSpan delay);
Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay);
}
public interface IGenericGrainWithConstraints<A, B, C> : IGrainWithStringKey
where A : ICollection<B>, new() where B : struct where C : class
{
Task<int> GetCount();
Task Add(B item);
Task<C> RoundTrip(C value);
}
public interface INonGenericCastableGrain : IGrainWithGuidKey
{
Task DoSomething();
}
public interface IGenericCastableGrain<T> : IGrainWithGuidKey
{ }
public interface IGrainSayingHello : IGrainWithGuidKey
{
Task<string> Hello();
}
public interface ISomeGenericGrain<T> : IGrainSayingHello
{ }
public interface INonGenericCastGrain : IGrainSayingHello
{ }
public interface IIndependentlyConcretizedGrain : ISomeGenericGrain<string>
{ }
public interface IIndependentlyConcretizedGenericGrain<T> : ISomeGenericGrain<T>
{ }
namespace Generic.EdgeCases
{
public interface IBasicGrain : IGrainWithGuidKey
{
Task<string> Hello();
Task<string[]> ConcreteGenArgTypeNames();
}
public interface IGrainWithTwoGenArgs<T1, T2> : IBasicGrain
{ }
public interface IGrainWithThreeGenArgs<T1, T2, T3> : IBasicGrain
{ }
public interface IGrainReceivingRepeatedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IPartiallySpecifyingInterface<T> : IGrainWithTwoGenArgs<T, int>
{ }
public interface IReceivingRepeatedGenArgsAmongstOthers<T1, T2, T3> : IBasicGrain
{ }
public interface IReceivingRepeatedGenArgsFromOtherInterface<T1, T2, T3> : IBasicGrain
{ }
public interface ISpecifyingGenArgsRepeatedlyToParentInterface<T> : IReceivingRepeatedGenArgsFromOtherInterface<T, T, T>
{ }
public interface IReceivingRearrangedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IReceivingRearrangedGenArgsViaCast<T1, T2> : IBasicGrain
{ }
public interface ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> : IReceivingRearrangedGenArgsViaCast<T2, T1>
{ }
public interface IArbitraryInterface<T1, T2> : IBasicGrain
{ }
public interface IInterfaceUnrelatedToConcreteGenArgs<T> : IBasicGrain
{ }
public interface IInterfaceTakingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IAnotherReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IYetOneMoreReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
}
}
| |
/*
* 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 System.Threading;
using System.Timers;
using Timer=System.Timers.Timer;
using Nini.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Scene presence tests
/// </summary>
[TestFixture]
public class ScenePresenceTests
{
public Scene scene, scene2, scene3;
public UUID agent1, agent2, agent3;
public static Random random;
public ulong region1,region2,region3;
public TestCommunicationsManager cm;
public AgentCircuitData acd1;
public SceneObjectGroup sog1, sog2, sog3;
public TestClient testclient;
[TestFixtureSetUp]
public void Init()
{
cm = new TestCommunicationsManager();
scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000, cm);
scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000, cm);
scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000, cm);
ISharedRegionModule interregionComms = new RESTInterregionComms();
interregionComms.Initialise(new IniConfigSource());
interregionComms.PostInitialise();
SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms);
SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms);
SceneSetupHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms);
agent1 = UUID.Random();
agent2 = UUID.Random();
agent3 = UUID.Random();
random = new Random();
sog1 = NewSOG(UUID.Random(), scene, agent1);
sog2 = NewSOG(UUID.Random(), scene, agent1);
sog3 = NewSOG(UUID.Random(), scene, agent1);
//ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
region1 = scene.RegionInfo.RegionHandle;
region2 = scene2.RegionInfo.RegionHandle;
region3 = scene3.RegionInfo.RegionHandle;
}
/// <summary>
/// Test adding a root agent to a scene. Doesn't yet actually complete crossing the agent into the scene.
/// </summary>
[Test]
public void T010_TestAddRootAgent()
{
TestHelper.InMethod();
string firstName = "testfirstname";
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = agent1;
agent.firstname = firstName;
agent.lastname = "testlastname";
agent.SessionID = UUID.Zero;
agent.SecureSessionID = UUID.Zero;
agent.circuitcode = 123;
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = Vector3.Zero;
agent.CapsPath = GetRandomCapsObjectPath();
agent.ChildrenCapSeeds = new Dictionary<ulong, string>();
agent.child = true;
string reason;
scene.NewUserConnection(agent, out reason);
testclient = new TestClient(agent, scene);
scene.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence, Is.Not.Null, "presence is null");
Assert.That(presence.Firstname, Is.EqualTo(firstName), "First name not same");
acd1 = agent;
}
/// <summary>
/// Test removing an uncrossed root agent from a scene.
/// </summary>
[Test]
public void T011_TestRemoveRootAgent()
{
TestHelper.InMethod();
scene.RemoveClient(agent1);
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence, Is.Null, "presence is not null");
}
[Test]
public void T012_TestAddNeighbourRegion()
{
TestHelper.InMethod();
string reason;
if (acd1 == null)
fixNullPresence();
scene.NewUserConnection(acd1, out reason);
if (testclient == null)
testclient = new TestClient(acd1, scene);
scene.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
presence.MakeRootAgent(new Vector3(90,90,90),false);
string cap = presence.ControllingClient.RequestClientInfo().CapsPath;
presence.AddNeighbourRegion(region2, cap);
presence.AddNeighbourRegion(region3, cap);
List<ulong> neighbours = presence.GetKnownRegionList();
Assert.That(neighbours.Count, Is.EqualTo(2));
}
public void fixNullPresence()
{
string firstName = "testfirstname";
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = agent1;
agent.firstname = firstName;
agent.lastname = "testlastname";
agent.SessionID = UUID.Zero;
agent.SecureSessionID = UUID.Zero;
agent.circuitcode = 123;
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = Vector3.Zero;
agent.CapsPath = GetRandomCapsObjectPath();
acd1 = agent;
}
[Test]
public void T013_TestRemoveNeighbourRegion()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.RemoveNeighbourRegion(region3);
List<ulong> neighbours = presence.GetKnownRegionList();
Assert.That(neighbours.Count,Is.EqualTo(1));
/*
presence.MakeChildAgent;
presence.MakeRootAgent;
CompleteAvatarMovement
*/
}
// I'm commenting this test, because this is not supposed to happen here
//[Test]
public void T020_TestMakeRootAgent()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence.IsChildAgent, Is.False, "Starts out as a root agent");
presence.MakeChildAgent();
Assert.That(presence.IsChildAgent, Is.True, "Did not change to child agent after MakeChildAgent");
// Accepts 0 but rejects Constants.RegionSize
Vector3 pos = new Vector3(0,Constants.RegionSize-1,0);
presence.MakeRootAgent(pos,true);
Assert.That(presence.IsChildAgent, Is.False, "Did not go back to root agent");
Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered");
}
// I'm commenting this test because it does not represent
// crossings. The Thread.Sleep's in here are not meaningful mocks,
// and they sometimes fail in panda.
// We need to talk in order to develop a test
// that really tests region crossings. There are 3 async components,
// but things are synchronous among them. So there should be
// 3 threads in here.
//[Test]
public void T021_TestCrossToNewRegion()
{
TestHelper.InMethod();
scene.RegisterRegionWithGrid();
scene2.RegisterRegionWithGrid();
// Adding child agent to region 1001
string reason;
scene2.NewUserConnection(acd1, out reason);
scene2.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
presence.MakeRootAgent(new Vector3(0,Constants.RegionSize-1,0), true);
ScenePresence presence2 = scene2.GetScenePresence(agent1);
// Adding neighbour region caps info to presence2
string cap = presence.ControllingClient.RequestClientInfo().CapsPath;
presence2.AddNeighbourRegion(region1, cap);
Assert.That(presence.IsChildAgent, Is.False, "Did not start root in origin region.");
Assert.That(presence2.IsChildAgent, Is.True, "Is not a child on destination region.");
// Cross to x+1
presence.AbsolutePosition = new Vector3(Constants.RegionSize+1,3,100);
presence.Update();
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
// Mimicking communication between client and server, by waiting OK from client
// sent by TestClient.CrossRegion call. Originally, this is network comm.
if (!wh.WaitOne(5000,false))
{
presence.Update();
if (!wh.WaitOne(8000,false))
throw new ArgumentException("1 - Timeout waiting for signal/variable.");
}
// This is a TestClient specific method that fires OnCompleteMovementToRegion event, which
// would normally be fired after receiving the reply packet from comm. done on the last line.
testclient.CompleteMovement();
// Crossings are asynchronous
int timer = 10;
// Make sure cross hasn't already finished
if (!presence.IsInTransit && !presence.IsChildAgent)
{
// If not and not in transit yet, give it some more time
Thread.Sleep(5000);
}
// Enough time, should at least be in transit by now.
while (presence.IsInTransit && timer > 0)
{
Thread.Sleep(1000);
timer-=1;
}
Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 2->1.");
Assert.That(presence.IsChildAgent, Is.True, "Did not complete region cross as expected.");
Assert.That(presence2.IsChildAgent, Is.False, "Did not receive root status after receiving agent.");
// Cross Back
presence2.AbsolutePosition = new Vector3(-10, 3, 100);
presence2.Update();
if (!wh.WaitOne(5000,false))
{
presence2.Update();
if (!wh.WaitOne(8000,false))
throw new ArgumentException("2 - Timeout waiting for signal/variable.");
}
testclient.CompleteMovement();
if (!presence2.IsInTransit && !presence2.IsChildAgent)
{
// If not and not in transit yet, give it some more time
Thread.Sleep(5000);
}
// Enough time, should at least be in transit by now.
while (presence2.IsInTransit && timer > 0)
{
Thread.Sleep(1000);
timer-=1;
}
Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 1->2.");
Assert.That(presence2.IsChildAgent, Is.True, "Did not return from region as expected.");
Assert.That(presence.IsChildAgent, Is.False, "Presence was not made root in old region again.");
}
[Test]
public void T030_TestAddAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.AddAttachment(sog1);
presence.AddAttachment(sog2);
presence.AddAttachment(sog3);
Assert.That(presence.HasAttachments(), Is.True);
Assert.That(presence.ValidateAttachments(), Is.True);
}
[Test]
public void T031_RemoveAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.RemoveAttachment(sog1);
presence.RemoveAttachment(sog2);
presence.RemoveAttachment(sog3);
Assert.That(presence.HasAttachments(), Is.False);
}
// I'm commenting this test because scene setup NEEDS InventoryService to
// be non-null
//[Test]
public void T032_CrossAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
ScenePresence presence2 = scene2.GetScenePresence(agent1);
presence2.AddAttachment(sog1);
presence2.AddAttachment(sog2);
ISharedRegionModule serialiser = new SerialiserModule();
SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser);
SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser);
Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross");
Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful");
Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted");
Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects");
}
[TearDown]
public void TearDown()
{
if (MainServer.Instance != null) MainServer.Instance.Stop();
}
public static string GetRandomCapsObjectPath()
{
TestHelper.InMethod();
UUID caps = UUID.Random();
string capsPath = caps.ToString();
capsPath = capsPath.Remove(capsPath.Length - 4, 4);
return capsPath;
}
private SceneObjectGroup NewSOG(UUID uuid, Scene scene, UUID agent)
{
SceneObjectPart sop = new SceneObjectPart();
sop.Name = RandomName();
sop.Description = RandomName();
sop.Text = RandomName();
sop.SitName = RandomName();
sop.TouchName = RandomName();
sop.UUID = uuid;
sop.Shape = PrimitiveBaseShape.Default;
sop.Shape.State = 1;
sop.OwnerID = agent;
SceneObjectGroup sog = new SceneObjectGroup(sop);
sog.SetScene(scene);
return sog;
}
private static string RandomName()
{
StringBuilder name = new StringBuilder();
int size = random.Next(5,12);
char ch ;
for (int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
name.Append(ch);
}
return name.ToString();
}
}
}
| |
// 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.
/*============================================================
**
** Classes: NativeObjectSecurity class
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using FileNotFoundException = System.IO.FileNotFoundException;
namespace System.Security.AccessControl
{
public abstract class NativeObjectSecurity : CommonObjectSecurity
{
#region Private Members
private readonly ResourceType _resourceType;
private ExceptionFromErrorCode _exceptionFromErrorCode = null;
private object _exceptionContext = null;
private readonly uint ProtectedDiscretionaryAcl = 0x80000000;
private readonly uint ProtectedSystemAcl = 0x40000000;
private readonly uint UnprotectedDiscretionaryAcl = 0x20000000;
private readonly uint UnprotectedSystemAcl = 0x10000000;
#endregion
#region Delegates
protected internal delegate System.Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context);
#endregion
#region Constructors
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType)
: base(isContainer)
{
_resourceType = resourceType;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(isContainer, resourceType)
{
_exceptionContext = exceptionContext;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor)
: this(resourceType, securityDescriptor, null)
{
}
internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode)
: base(securityDescriptor)
{
_resourceType = resourceType;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(resourceType, CreateInternal(resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections)
: this(isContainer, resourceType, name, includeSections, null, null)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(resourceType, CreateInternal(resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections)
: this(isContainer, resourceType, handle, includeSections, null, null)
{
}
#endregion
#region Private Methods
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
{
int error;
RawSecurityDescriptor rawSD;
if (createByName && name == null)
{
throw new ArgumentNullException(nameof(name));
}
else if (!createByName && handle == null)
{
throw new ArgumentNullException(nameof(handle));
}
error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD);
if (error != Interop.Errors.ERROR_SUCCESS)
{
System.Exception exception = null;
if (exceptionFromErrorCode != null)
{
exception = exceptionFromErrorCode(error, name, handle, exceptionContext);
}
if (exception == null)
{
if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
exception = new UnauthorizedAccessException();
}
else if (error == Interop.Errors.ERROR_INVALID_OWNER)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
}
else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
}
else if (error == Interop.Errors.ERROR_INVALID_PARAMETER)
{
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
else if (error == Interop.Errors.ERROR_INVALID_NAME)
{
exception = new ArgumentException(
SR.Argument_InvalidName,
nameof(name));
}
else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND)
{
exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name));
}
else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
}
else if (error == Interop.Errors.ERROR_PIPE_NOT_CONNECTED)
{
exception = new InvalidOperationException(SR.InvalidOperation_DisconnectedPipe);
}
else
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error));
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
throw exception;
}
return new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true);
}
//
// Attempts to persist the security descriptor onto the object
//
private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
{
WriteLock();
try
{
int error;
SecurityInfos securityInfo = 0;
SecurityIdentifier owner = null, group = null;
SystemAcl sacl = null;
DiscretionaryAcl dacl = null;
if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null)
{
securityInfo |= SecurityInfos.Owner;
owner = _securityDescriptor.Owner;
}
if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null)
{
securityInfo |= SecurityInfos.Group;
group = _securityDescriptor.Group;
}
if ((includeSections & AccessControlSections.Audit) != 0)
{
securityInfo |= SecurityInfos.SystemAcl;
if (_securityDescriptor.IsSystemAclPresent &&
_securityDescriptor.SystemAcl != null &&
_securityDescriptor.SystemAcl.Count > 0)
{
sacl = _securityDescriptor.SystemAcl;
}
else
{
sacl = null;
}
if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0)
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
}
}
if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent)
{
securityInfo |= SecurityInfos.DiscretionaryAcl;
// if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
{
dacl = null;
}
else
{
dacl = _securityDescriptor.DiscretionaryAcl;
}
if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0)
{
securityInfo = unchecked((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl));
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
}
}
if (securityInfo == 0)
{
//
// Nothing to persist
//
return;
}
error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl);
if (error != Interop.Errors.ERROR_SUCCESS)
{
System.Exception exception = null;
if (_exceptionFromErrorCode != null)
{
exception = _exceptionFromErrorCode(error, name, handle, exceptionContext);
}
if (exception == null)
{
if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
exception = new UnauthorizedAccessException();
}
else if (error == Interop.Errors.ERROR_INVALID_OWNER)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
}
else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
}
else if (error == Interop.Errors.ERROR_INVALID_NAME)
{
exception = new ArgumentException(
SR.Argument_InvalidName,
nameof(name));
}
else if (error == Interop.Errors.ERROR_INVALID_HANDLE)
{
exception = new NotSupportedException(SR.AccessControl_InvalidHandle);
}
else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND)
{
exception = new FileNotFoundException();
}
else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
}
else
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error));
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
throw exception;
}
//
// Everything goes well, let us clean the modified flags.
// We are in proper write lock, so just go ahead
//
this.OwnerModified = false;
this.GroupModified = false;
this.AccessRulesModified = false;
this.AuditRulesModified = false;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Protected Methods
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a name of an existing object
//
protected sealed override void Persist(string name, AccessControlSections includeSections)
{
Persist(name, includeSections, _exceptionContext);
}
protected void Persist(string name, AccessControlSections includeSections, object exceptionContext)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Persist(name, null, includeSections, exceptionContext);
}
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a handle to an existing object
//
protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections)
{
Persist(handle, includeSections, _exceptionContext);
}
protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
{
if (handle == null)
{
throw new ArgumentNullException(nameof(handle));
}
Persist(null, handle, includeSections, exceptionContext);
}
#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.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Linq.Parallel.Tests
{
public static class UnorderedSources
{
/// <summary>
/// Returns a default ParallelQuery source.
/// </summary>
/// For most instances when dealing with unordered input, the individual source does not matter.
///
/// Instead, that is reserved for ordered, where partitioning and dealing with indices has important
/// secondary effects. The goal of unordered input, then, is mostly to make sure the query works.
/// <param name="count">The count of elements.</param>
/// <returns>A ParallelQuery with elements running from 0 to count - 1</returns>
public static ParallelQuery<int> Default(int count)
{
return Default(0, count);
}
/// <summary>
/// Returns a default ParallelQuery source.
/// </summary>
/// For most instances when dealing with unordered input, the individual source does not matter.
///
/// Instead, that is reserved for ordered, where partitioning and dealing with indices has important
/// secondary effects. The goal of unordered input, then, is mostly to make sure the query works.
/// <param name="start">The starting element.</param>
/// <param name="count">The count of elements.</param>
/// <returns>A ParallelQuery with elements running from 0 to count - 1</returns>
public static ParallelQuery<int> Default(int start, int count)
{
// Of the underlying types used elsewhere, some have "problems",
// in the sense that they may be too-easily indexible.
// For instance, Array and List are both trivially range partitionable and indexible.
// A parallelized Enumerable.Range is being used (not easily partitionable or indexible),
// but at the moment ParallelEnumerable.Range is being used for speed and ease of use.
// ParallelEnumerable.Range is not trivially indexible, but is easily range partitioned.
return ParallelEnumerable.Range(start, count);
}
// Get a set of ranges, of each count in `counts`.
// The start of each range is determined by passing the count into the `start` predicate.
public static IEnumerable<object[]> Ranges(Func<int, int> start, IEnumerable<int> counts)
{
foreach (int count in counts)
{
int s = start(count);
foreach (Labeled<ParallelQuery<int>> query in LabeledRanges(s, count))
{
yield return new object[] { query, count, s };
}
}
}
/// <summary>
/// Get a set of ranges, starting at `start`, and running for each count in `counts`.
/// </summary>
/// <param name="start">The starting element of the range.</param>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and the third is the start.</returns>
public static IEnumerable<object[]> Ranges(int start, IEnumerable<int> counts)
{
foreach (object[] parms in Ranges(x => start, counts)) yield return parms;
}
/// <summary>
/// Get a set of ranges, starting at 0, and running for each count in `counts`.
/// </summary>
/// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// and the second element is the count</returns>
public static IEnumerable<object[]> Ranges(int[] counts)
{
foreach (object[] parms in Ranges(counts.Cast<int>())) yield return parms;
}
/// <summary>
/// Get a set of ranges, starting at 0, and having OuterLoopCount elements.
/// </summary>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// and the second element is the count</returns>
public static IEnumerable<object[]> OuterLoopRanges()
{
foreach (object[] parms in Ranges(new[] { Sources.OuterLoopCount })) yield return parms;
}
/// <summary>
/// Get a set of ranges, starting at `start`, and running for each count in `counts`.
/// </summary>
/// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks>
/// <param name="start">The starting element of the range.</param>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and the third is the start.</returns>
public static IEnumerable<object[]> Ranges(int start, int[] counts)
{
foreach (object[] parms in Ranges(start, counts.Cast<int>())) yield return parms;
}
/// <summary>
/// Return pairs of ranges, both from 0 to each respective count in `counts`.
/// </summary>
/// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks>
/// <param name="leftCounts">The sizes of left ranges to return.</param>
/// <param name="rightCounts">The sizes of right ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count,
/// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count, .</returns>
public static IEnumerable<object[]> BinaryRanges(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in BinaryRanges(leftCounts.Cast<int>(), rightCounts.Cast<int>())) yield return parms;
}
/// <summary>
/// Get a set of ranges, starting at 0, and running for each count in `counts`.
/// </summary>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// and the second element is the count</returns>
public static IEnumerable<object[]> Ranges(IEnumerable<int> counts)
{
foreach (object[] parms in Ranges(x => 0, counts)) yield return parms.Take(2).ToArray();
}
/// <summary>
/// Return pairs of ranges, both from 0 to each respective count in `counts`.
/// </summary>
/// <param name="leftCounts">The sizes of left ranges to return.</param>
/// <param name="rightCounts">The sizes of right ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count,
/// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count.</returns>
public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, IEnumerable<int> rightCounts)
{
IEnumerable<object[]> rightRanges = Ranges(rightCounts);
foreach (object[] left in Ranges(leftCounts))
{
foreach (object[] right in rightRanges)
{
yield return left.Concat(right).ToArray();
}
}
}
/// <summary>
/// Return pairs of ranges, for each respective count in `counts`.
/// </summary>
/// <param name="leftCounts">The sizes of left ranges to return.</param>
/// <param name="rightStart">A predicate to determine the start of the right range, by passing the left and right range size.</param>
/// <param name="rightCounts">The sizes of right ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count,
/// the third element is the right Labeled{ParallelQuery{int}} range, the fourth element is the right count,
/// and the fifth is the right start.</returns>
public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, Func<int, int, int> rightStart, IEnumerable<int> rightCounts)
{
foreach (object[] left in Ranges(leftCounts))
{
foreach (object[] right in Ranges(right => rightStart((int)left[1], right), rightCounts))
{
yield return left.Concat(right).ToArray();
}
}
}
/// <summary>
/// Get a set of ranges, starting at 0, and running for each count in `counts`.
/// </summary>
/// <remarks>
/// This is useful for things like showing an average (via the use of `x => (double)SumRange(0, x) / x`)
/// </remarks>
/// <param name="counts">The sizes of ranges to return.</param>
/// <param name="modifiers">A set of modifiers to return as additional parameters.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and one additional element for each modifier.</returns>
public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, T> modifiers)
{
foreach (object[] parms in Ranges(counts))
{
int count = (int)parms[1];
yield return parms.Concat(new object[] { modifiers(count) }).ToArray();
}
}
/// <summary>
/// Get a set of ranges, starting at 0, and running for each count in `counts`.
/// </summary>
/// <remarks>
/// This is useful for things like dealing with `Max(predicate)`,
/// allowing multiple predicate values for the same source count to be tested.
/// The number of variations is equal to the longest modifier enumeration (all others will cycle).
/// </remarks>
/// <param name="counts">The sizes of ranges to return.</param>
/// <param name="modifiers">A set of modifiers to return as additional parameters.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and one additional element for each modifier.</returns>
public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, IEnumerable<T>> modifiers)
{
foreach (object[] parms in Ranges(counts))
{
foreach (T mod in modifiers((int)parms[1]))
{
yield return parms.Concat(new object[] { mod }).ToArray();
}
}
}
// Return an enumerable which throws on first MoveNext.
// Useful for testing promptness of cancellation.
public static IEnumerable<object[]> ThrowOnFirstEnumeration()
{
yield return new object[] { Labeled.Label("ThrowOnFirstEnumeration", Enumerables<int>.ThrowOnEnumeration().AsParallel()), 8 };
}
private static IEnumerable<Labeled<ParallelQuery<int>>> LabeledRanges(int start, int count)
{
yield return Labeled.Label("ParallelEnumerable.Range", ParallelEnumerable.Range(start, count));
yield return Labeled.Label("Enumerable.Range", Enumerable.Range(start, count).AsParallel());
int[] rangeArray = Enumerable.Range(start, count).ToArray();
yield return Labeled.Label("Array", rangeArray.AsParallel());
IList<int> rangeList = rangeArray.ToList();
yield return Labeled.Label("List", rangeList.AsParallel());
yield return Labeled.Label("Partitioner", Partitioner.Create(rangeArray).AsParallel());
// PLINQ doesn't currently have any special code paths for readonly collections. If it ever does, this should be uncommented.
// yield return Labeled.Label("ReadOnlyCollection", new ReadOnlyCollection<int>(rangeList).AsParallel());
}
}
}
| |
// 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.Runtime.InteropServices;
struct SingleByte
{
public byte Byte;
public static SingleByte Get()
{
return new SingleByte { Byte = 42 };
}
public bool Equals(SingleByte other)
{
return Byte == other.Byte;
}
}
struct SingleLong
{
public ulong Long;
public static SingleLong Get()
{
return new SingleLong { Long = 0xfeedfaceabadf00d };
}
public bool Equals(SingleLong other)
{
return Long == other.Long;
}
}
struct SingleFloat
{
public float Float;
public static SingleFloat Get()
{
return new SingleFloat { Float = 3.14159f };
}
public bool Equals(SingleFloat other)
{
return Float == other.Float;
}
}
struct SingleDouble
{
public double Double;
public static SingleDouble Get()
{
return new SingleDouble { Double = 3.14159d };
}
public bool Equals(SingleDouble other)
{
return Double == other.Double;
}
}
struct ByteAndFloat
{
public byte Byte;
public float Float;
public static ByteAndFloat Get()
{
return new ByteAndFloat { Byte = 42, Float = 3.14159f };
}
public bool Equals(ByteAndFloat other)
{
return Byte == other.Byte && Float == other.Float;
}
}
struct FloatAndByte
{
public float Float;
public byte Byte;
public static FloatAndByte Get()
{
return new FloatAndByte { Byte = 42, Float = 3.14159f };
}
public bool Equals(FloatAndByte other)
{
return Byte == other.Byte && Float == other.Float;
}
}
struct LongAndFloat
{
public ulong Long;
public float Float;
public static LongAndFloat Get()
{
return new LongAndFloat { Long = 0xfeedfaceabadf00d, Float = 3.14159f };
}
public bool Equals(LongAndFloat other)
{
return Long == other.Long && Float == other.Float;
}
}
struct ByteAndDouble
{
public byte Byte;
public double Double;
public static ByteAndDouble Get()
{
return new ByteAndDouble { Byte = 42, Double = 3.14159d };
}
public bool Equals(ByteAndDouble other)
{
return Byte == other.Byte && Double == other.Double;
}
}
struct DoubleAndByte
{
public double Double;
public byte Byte;
public static DoubleAndByte Get()
{
return new DoubleAndByte { Byte = 42, Double = 3.14159d };
}
public bool Equals(DoubleAndByte other)
{
return Byte == other.Byte && Double == other.Double;
}
}
unsafe struct PointerAndByte
{
public void* Pointer;
public byte Byte;
public static PointerAndByte Get()
{
byte unused;
return new PointerAndByte { Pointer = &unused, Byte = 42 };
}
public bool Equals(PointerAndByte other)
{
return Pointer == other.Pointer && Byte == other.Byte;
}
}
unsafe struct ByteAndPointer
{
public byte Byte;
public void* Pointer;
public static ByteAndPointer Get()
{
byte unused;
return new ByteAndPointer { Pointer = &unused, Byte = 42 };
}
public bool Equals(ByteAndPointer other)
{
return Pointer == other.Pointer && Byte == other.Byte;
}
}
unsafe struct ByteFloatAndPointer
{
public byte Byte;
public float Float;
public void* Pointer;
public static ByteFloatAndPointer Get()
{
byte unused;
return new ByteFloatAndPointer { Pointer = &unused, Float = 3.14159f, Byte = 42 };
}
public bool Equals(ByteFloatAndPointer other)
{
return Pointer == other.Pointer && Float == other.Float && Byte == other.Byte;
}
}
unsafe struct PointerFloatAndByte
{
public void* Pointer;
public float Float;
public byte Byte;
public static PointerFloatAndByte Get()
{
byte unused;
return new PointerFloatAndByte { Pointer = &unused, Float = 3.14159f, Byte = 42 };
}
public bool Equals(PointerFloatAndByte other)
{
return Pointer == other.Pointer && Float == other.Float && Byte == other.Byte;
}
}
struct TwoFloats
{
public float Float1;
public float Float2;
public static TwoFloats Get()
{
return new TwoFloats { Float1 = 3.14159f, Float2 = 2.71828f };
}
public bool Equals(TwoFloats other)
{
return Float1 == other.Float1 && Float2 == other.Float2;
}
}
struct TwoDoubles
{
public double Double1;
public double Double2;
public static TwoDoubles Get()
{
return new TwoDoubles { Double1 = 3.14159d, Double2 = 2.71828d };
}
public bool Equals(TwoDoubles other)
{
return Double1 == other.Double1 && Double2 == other.Double2;
}
}
unsafe struct InlineArray1
{
public fixed byte Array[16];
public static InlineArray1 Get()
{
var val = new InlineArray1();
for (int i = 0; i < 16; i++)
{
val.Array[i] = (byte)(i + 1);
}
return val;
}
public bool Equals(InlineArray1 other)
{
fixed (byte* arr = Array)
{
for (int i = 0; i < 16; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
unsafe struct InlineArray2
{
public fixed float Array[4];
public static InlineArray2 Get()
{
var val = new InlineArray2();
for (int i = 0; i < 4; i++)
{
val.Array[i] = (float)(i + 1);
}
return val;
}
public bool Equals(InlineArray2 other)
{
fixed (float* arr = Array)
{
for (int i = 0; i < 4; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
unsafe struct InlineArray3
{
public fixed float Array[3];
public static InlineArray3 Get()
{
var val = new InlineArray3();
for (int i = 0; i < 3; i++)
{
val.Array[i] = (float)(i + 1);
}
return val;
}
public bool Equals(InlineArray3 other)
{
fixed (float* arr = Array)
{
for (int i = 0; i < 3; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
unsafe struct InlineArray4
{
public fixed ushort Array[5];
public static InlineArray4 Get()
{
var val = new InlineArray4();
for (int i = 0; i < 5; i++)
{
val.Array[i] = (ushort)(i + 1);
}
return val;
}
public bool Equals(InlineArray4 other)
{
fixed (ushort* arr = Array)
{
for (int i = 0; i < 5; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
unsafe struct InlineArray5
{
public fixed byte Array[9];
public static InlineArray5 Get()
{
var val = new InlineArray5();
for (int i = 0; i < 9; i++)
{
val.Array[i] = (byte)(i + 1);
}
return val;
}
public bool Equals(InlineArray5 other)
{
fixed (byte* arr = Array)
{
for (int i = 0; i < 9; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
unsafe struct InlineArray6
{
public fixed double Array[1];
public static InlineArray6 Get()
{
var val = new InlineArray6();
for (int i = 0; i < 1; i++)
{
val.Array[i] = (double)(i + 1);
}
return val;
}
public bool Equals(InlineArray6 other)
{
fixed (double* arr = Array)
{
for (int i = 0; i < 1; i++)
{
if (arr[i] != other.Array[i])
{
return false;
}
}
}
return true;
}
}
struct Nested1
{
public LongAndFloat Field1;
public LongAndFloat Field2;
public static Nested1 Get()
{
return new Nested1
{
Field1 = new LongAndFloat { Long = 0xfeedfaceabadf00d, Float = 3.14159f },
Field2 = new LongAndFloat { Long = 0xbeeff00fdeadcafe, Float = 2.71928f }
};
}
public bool Equals(Nested1 other)
{
return Field1.Equals(other.Field1) && Field2.Equals(other.Field2);
}
}
struct Nested2
{
public ByteAndFloat Field1;
public FloatAndByte Field2;
public static Nested2 Get()
{
return new Nested2
{
Field1 = new ByteAndFloat { Byte = 42, Float = 3.14159f },
Field2 = new FloatAndByte { Byte = 24, Float = 2.71928f }
};
}
public bool Equals(Nested2 other)
{
return Field1.Equals(other.Field1) && Field2.Equals(other.Field2);
}
}
unsafe struct Nested3
{
public void* Field1;
public FloatAndByte Field2;
public static Nested3 Get()
{
byte unused;
return new Nested3 { Field1 = &unused, Field2 = FloatAndByte.Get() };
}
public bool Equals(Nested3 other)
{
return Field1 == other.Field1 && Field2.Equals(other.Field2);
}
}
struct Nested4
{
public InlineArray5 Field1;
public ushort Field2;
public static Nested4 Get()
{
return new Nested4 { Field1 = InlineArray5.Get(), Field2 = 0xcafe };
}
public bool Equals(Nested4 other)
{
return Field1.Equals(other.Field1) && Field2 == other.Field2;
}
}
struct Nested5
{
public ushort Field1;
public InlineArray5 Field2;
public static Nested5 Get()
{
return new Nested5 { Field2 = InlineArray5.Get(), Field1 = 0xcafe };
}
public bool Equals(Nested5 other)
{
return Field1 == other.Field1 && Field2.Equals(other.Field2);
}
}
struct Nested6
{
public InlineArray4 Field1;
public uint Field2;
public static Nested6 Get()
{
return new Nested6 { Field1 = InlineArray4.Get(), Field2 = 0xcafef00d };
}
public bool Equals(Nested6 other)
{
return Field1.Equals(other.Field1) && Field2 == other.Field2;
}
}
struct Nested7
{
public uint Field1;
public InlineArray4 Field2;
public static Nested7 Get()
{
return new Nested7 { Field2 = InlineArray4.Get(), Field1 = 0xcafef00d };
}
public bool Equals(Nested7 other)
{
return Field1 == other.Field1 && Field2.Equals(other.Field2);
}
}
struct Nested8
{
public InlineArray4 Field1;
public ushort Field2;
public static Nested8 Get()
{
return new Nested8 { Field1 = InlineArray4.Get(), Field2 = 0xcafe };
}
public bool Equals(Nested8 other)
{
return Field1.Equals(other.Field1) && Field2 == other.Field2;
}
}
struct Nested9
{
public ushort Field1;
public InlineArray4 Field2;
public static Nested9 Get()
{
return new Nested9 { Field2 = InlineArray4.Get(), Field1 = 0xcafe };
}
public bool Equals(Nested9 other)
{
return Field1 == other.Field1 && Field2.Equals(other.Field2);
}
}
public static partial class StructABI
{
[DllImport(StructABILib)]
static extern SingleByte EchoSingleByte(SingleByte value);
[DllImport(StructABILib)]
static extern SingleLong EchoSingleLong(SingleLong value);
[DllImport(StructABILib)]
static extern SingleFloat EchoSingleFloat(SingleFloat value);
[DllImport(StructABILib)]
static extern SingleDouble EchoSingleDouble(SingleDouble value);
[DllImport(StructABILib)]
static extern ByteAndFloat EchoByteAndFloat(ByteAndFloat value);
[DllImport(StructABILib)]
static extern LongAndFloat EchoLongAndFloat(LongAndFloat value);
[DllImport(StructABILib)]
static extern ByteAndDouble EchoByteAndDouble(ByteAndDouble value);
[DllImport(StructABILib)]
static extern DoubleAndByte EchoDoubleAndByte(DoubleAndByte value);
[DllImport(StructABILib)]
static extern PointerAndByte EchoPointerAndByte(PointerAndByte value);
[DllImport(StructABILib)]
static extern ByteAndPointer EchoByteAndPointer(ByteAndPointer value);
[DllImport(StructABILib)]
static extern ByteFloatAndPointer EchoByteFloatAndPointer(ByteFloatAndPointer value);
[DllImport(StructABILib)]
static extern PointerFloatAndByte EchoPointerFloatAndByte(PointerFloatAndByte value);
[DllImport(StructABILib)]
static extern TwoFloats EchoTwoFloats(TwoFloats value);
[DllImport(StructABILib)]
static extern TwoDoubles EchoTwoDoubles(TwoDoubles value);
[DllImport(StructABILib)]
static extern InlineArray1 EchoInlineArray1(InlineArray1 value);
[DllImport(StructABILib)]
static extern InlineArray2 EchoInlineArray2(InlineArray2 value);
[DllImport(StructABILib)]
static extern InlineArray3 EchoInlineArray3(InlineArray3 value);
[DllImport(StructABILib)]
static extern InlineArray4 EchoInlineArray4(InlineArray4 value);
[DllImport(StructABILib)]
static extern InlineArray5 EchoInlineArray5(InlineArray5 value);
[DllImport(StructABILib)]
static extern InlineArray6 EchoInlineArray6(InlineArray6 value);
[DllImport(StructABILib)]
static extern Nested1 EchoNested1(Nested1 value);
[DllImport(StructABILib)]
static extern Nested2 EchoNested2(Nested2 value);
[DllImport(StructABILib)]
static extern Nested3 EchoNested3(Nested3 value);
[DllImport(StructABILib)]
static extern Nested4 EchoNested4(Nested4 value);
[DllImport(StructABILib)]
static extern Nested5 EchoNested5(Nested5 value);
[DllImport(StructABILib)]
static extern Nested6 EchoNested6(Nested6 value);
[DllImport(StructABILib)]
static extern Nested7 EchoNested7(Nested7 value);
[DllImport(StructABILib)]
static extern Nested8 EchoNested8(Nested8 value);
[DllImport(StructABILib)]
static extern Nested9 EchoNested9(Nested9 value);
static int Main()
{
var ok = true;
SingleByte expectedSingleByte = SingleByte.Get();
SingleByte actualSingleByte = EchoSingleByte(expectedSingleByte);
if (!expectedSingleByte.Equals(actualSingleByte))
{
Console.WriteLine("EchoSingleByte failed");
ok = false;
}
SingleLong expectedSingleLong = SingleLong.Get();
SingleLong actualSingleLong = EchoSingleLong(expectedSingleLong);
if (!expectedSingleLong.Equals(actualSingleLong))
{
Console.WriteLine("EchoSingleLong failed");
ok = false;
}
SingleFloat expectedSingleFloat = SingleFloat.Get();
SingleFloat actualSingleFloat = EchoSingleFloat(expectedSingleFloat);
if (!expectedSingleFloat.Equals(actualSingleFloat))
{
Console.WriteLine("EchoSingleFloat failed");
ok = false;
}
SingleDouble expectedSingleDouble = SingleDouble.Get();
SingleDouble actualSingleDouble = EchoSingleDouble(expectedSingleDouble);
if (!expectedSingleDouble.Equals(actualSingleDouble))
{
Console.WriteLine("EchoSingleDouble failed");
ok = false;
}
ByteAndFloat expectedByteAndFloat = ByteAndFloat.Get();
ByteAndFloat actualByteAndFloat = EchoByteAndFloat(expectedByteAndFloat);
if (!expectedByteAndFloat.Equals(actualByteAndFloat))
{
Console.WriteLine("EchoByteAndFloat failed");
ok = false;
}
LongAndFloat expectedLongAndFloat = LongAndFloat.Get();
LongAndFloat actualLongAndFloat = EchoLongAndFloat(expectedLongAndFloat);
if (!expectedLongAndFloat.Equals(actualLongAndFloat))
{
Console.WriteLine("EchoLongAndFloat failed");
ok = false;
}
ByteAndDouble expectedByteAndDouble = ByteAndDouble.Get();
ByteAndDouble actualByteAndDouble = EchoByteAndDouble(expectedByteAndDouble);
if (!expectedByteAndDouble.Equals(actualByteAndDouble))
{
Console.WriteLine("EchoByteAndDouble failed");
ok = false;
}
DoubleAndByte expectedDoubleAndByte = DoubleAndByte.Get();
DoubleAndByte actualDoubleAndByte = EchoDoubleAndByte(expectedDoubleAndByte);
if (!expectedDoubleAndByte.Equals(actualDoubleAndByte))
{
Console.WriteLine("EchoDoubleAndByte failed");
ok = false;
}
PointerAndByte expectedPointerAndByte = PointerAndByte.Get();
PointerAndByte actualPointerAndByte = EchoPointerAndByte(expectedPointerAndByte);
if (!expectedPointerAndByte.Equals(actualPointerAndByte))
{
Console.WriteLine("EchoPointerAndByte failed");
ok = false;
}
ByteAndPointer expectedByteAndPointer = ByteAndPointer.Get();
ByteAndPointer actualByteAndPointer = EchoByteAndPointer(expectedByteAndPointer);
if (!expectedByteAndPointer.Equals(actualByteAndPointer))
{
Console.WriteLine("EchoByteAndPointer failed");
ok = false;
}
ByteFloatAndPointer expectedByteFloatAndPointer = ByteFloatAndPointer.Get();
ByteFloatAndPointer actualByteFloatAndPointer = EchoByteFloatAndPointer(expectedByteFloatAndPointer);
if (!expectedByteFloatAndPointer.Equals(actualByteFloatAndPointer))
{
Console.WriteLine("EchoByteFloatAndPointer failed");
ok = false;
}
PointerFloatAndByte expectedPointerFloatAndByte = PointerFloatAndByte.Get();
PointerFloatAndByte actualPointerFloatAndByte = EchoPointerFloatAndByte(expectedPointerFloatAndByte);
if (!expectedPointerFloatAndByte.Equals(actualPointerFloatAndByte))
{
Console.WriteLine("EchoPointerFloatAndByte failed");
ok = false;
}
TwoFloats expectedTwoFloats = TwoFloats.Get();
TwoFloats actualTwoFloats = EchoTwoFloats(expectedTwoFloats);
if (!expectedTwoFloats.Equals(actualTwoFloats))
{
Console.WriteLine("EchoTwoFloats failed");
ok = false;
}
TwoDoubles expectedTwoDoubles = TwoDoubles.Get();
TwoDoubles actualTwoDoubles = EchoTwoDoubles(expectedTwoDoubles);
if (!expectedTwoDoubles.Equals(actualTwoDoubles))
{
Console.WriteLine("EchoTwoDoubles failed");
ok = false;
}
InlineArray1 expectedInlineArray1 = InlineArray1.Get();
InlineArray1 actualInlineArray1 = EchoInlineArray1(expectedInlineArray1);
if (!expectedInlineArray1.Equals(actualInlineArray1))
{
Console.WriteLine("EchoInlineArray1 failed");
ok = false;
}
InlineArray2 expectedInlineArray2 = InlineArray2.Get();
InlineArray2 actualInlineArray2 = EchoInlineArray2(expectedInlineArray2);
if (!expectedInlineArray2.Equals(actualInlineArray2))
{
Console.WriteLine("EchoInlineArray2 failed");
ok = false;
}
InlineArray3 expectedInlineArray3 = InlineArray3.Get();
InlineArray3 actualInlineArray3 = EchoInlineArray3(expectedInlineArray3);
if (!expectedInlineArray3.Equals(actualInlineArray3))
{
Console.WriteLine("EchoInlineArray3 failed");
ok = false;
}
InlineArray4 expectedInlineArray4 = InlineArray4.Get();
InlineArray4 actualInlineArray4 = EchoInlineArray4(expectedInlineArray4);
if (!expectedInlineArray4.Equals(actualInlineArray4))
{
Console.WriteLine("EchoInlineArray4 failed");
ok = false;
}
InlineArray5 expectedInlineArray5 = InlineArray5.Get();
InlineArray5 actualInlineArray5 = EchoInlineArray5(expectedInlineArray5);
if (!expectedInlineArray5.Equals(actualInlineArray5))
{
Console.WriteLine("EchoInlineArray5 failed");
ok = false;
}
InlineArray6 expectedInlineArray6 = InlineArray6.Get();
InlineArray6 actualInlineArray6 = EchoInlineArray6(expectedInlineArray6);
if (!expectedInlineArray6.Equals(actualInlineArray6))
{
Console.WriteLine("EchoInlineArray6 failed");
ok = false;
}
Nested1 expectedNested1 = Nested1.Get();
Nested1 actualNested1 = EchoNested1(expectedNested1);
if (!expectedNested1.Equals(actualNested1))
{
Console.WriteLine("EchoNested1 failed");
ok = false;
}
Nested2 expectedNested2 = Nested2.Get();
Nested2 actualNested2 = EchoNested2(expectedNested2);
if (!expectedNested2.Equals(actualNested2))
{
Console.WriteLine("EchoNested2 failed");
ok = false;
}
Nested3 expectedNested3 = Nested3.Get();
Nested3 actualNested3 = EchoNested3(expectedNested3);
if (!expectedNested3.Equals(actualNested3))
{
Console.WriteLine("EchoNested3 failed");
ok = false;
}
Nested4 expectedNested4 = Nested4.Get();
Nested4 actualNested4 = EchoNested4(expectedNested4);
if (!expectedNested4.Equals(actualNested4))
{
Console.WriteLine("EchoNested4 failed");
ok = false;
}
Nested5 expectedNested5 = Nested5.Get();
Nested5 actualNested5 = EchoNested5(expectedNested5);
if (!expectedNested5.Equals(actualNested5))
{
Console.WriteLine("EchoNested5 failed");
ok = false;
}
Nested6 expectedNested6 = Nested6.Get();
Nested6 actualNested6 = EchoNested6(expectedNested6);
if (!expectedNested6.Equals(actualNested6))
{
Console.WriteLine("EchoNested6 failed");
ok = false;
}
Nested7 expectedNested7 = Nested7.Get();
Nested7 actualNested7 = EchoNested7(expectedNested7);
if (!expectedNested7.Equals(actualNested7))
{
Console.WriteLine("EchoNested7 failed");
ok = false;
}
Nested8 expectedNested8 = Nested8.Get();
Nested8 actualNested8 = EchoNested8(expectedNested8);
if (!expectedNested8.Equals(actualNested8))
{
Console.WriteLine("EchoNested8 failed");
ok = false;
}
Nested9 expectedNested9 = Nested9.Get();
Nested9 actualNested9 = EchoNested9(expectedNested9);
if (!expectedNested9.Equals(actualNested9))
{
Console.WriteLine("EchoNested9 failed");
ok = false;
}
return ok ? 100 : -1;
}
}
| |
using System;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using UnityEngine.UI.Extensions;
namespace UnityEngine.UI.Windows {
[RequireComponent(typeof(Canvas))]
[RequireComponent(typeof(CanvasUpdater))]
public class WindowLayout : WindowObjectElement, ICanvasElement, IWindowEventsAsync {
public enum ScaleMode : byte {
Normal,
Fixed,
Custom,
};
public CanvasScaler canvasScaler;
[ReadOnly]
public WindowLayoutRoot root;
[ReadOnly]
public List<WindowLayoutElement> elements = new List<WindowLayoutElement>();
public bool showGrid = false;
public Vector2 gridSize = Vector2.one * 5f;
[HideInInspector][SerializeField]
public Canvas canvas;
[HideInInspector][SerializeField]
public UnityEngine.EventSystems.BaseRaycaster raycaster;
[HideInInspector][SerializeField]
public CanvasUpdater canvasUpdater;
[HideInInspector][SerializeField]
public bool initialized = false;
[HideInInspector][SerializeField]
private bool isAlive = false;
public override bool NeedToInactive() {
return false;
}
#if UNITY_EDITOR
[HideInInspector]
public float editorScale;
public override void OnValidateEditor() {
base.OnValidateEditor();
if (Application.isPlaying == true) return;
if (ME.EditorUtilities.IsPrefab(this.gameObject) == true) {
this.transform.localScale = Vector3.one * this.editorScale;
}
if (this.canvasUpdater == null || this.GetComponents<CanvasUpdater>().Length > 1) {
if (this.GetComponent<CanvasUpdater>() != null) Component.DestroyImmediate(this.GetComponent<CanvasUpdater>());
this.canvasUpdater = this.GetComponent<CanvasUpdater>();
if (this.canvasUpdater == null) this.canvasUpdater = this.gameObject.AddComponent<CanvasUpdater>();
if (this.canvasUpdater != null) this.canvasUpdater.OnValidate();
}
if (this.canvasScaler == null || this.GetComponents<CanvasScaler>().Length > 1) {
if (this.GetComponent<CanvasScaler>() != null) Component.DestroyImmediate(this.GetComponent<CanvasScaler>());
this.canvasScaler = this.GetComponent<CanvasScaler>();
if (this.canvasScaler == null) this.canvasScaler = this.gameObject.AddComponent<CanvasScaler>();
}
/*var rectTransform = (this.transform as RectTransform);
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.pivot = Vector2.one * 0.5f;
rectTransform.localScale = Vector3.one;
rectTransform.localRotation = Quaternion.identity;
rectTransform.anchoredPosition3D = Vector3.zero;*/
}
#endif
public void Init(float depth, int raycastPriority, int orderInLayer, WindowLayout.ScaleMode scaleMode, Vector2 fixedScaleResolution) {
if (this.initialized == false) {
Debug.LogError("Can't initialize window instance because of some components was not installed properly.");
return;
}
this.transform.localScale = Vector3.zero;
this.canvas.sortingOrder = orderInLayer;
this.canvas.planeDistance = 10f;// * orderInLayer;
this.canvas.worldCamera = this.GetWindow().workCamera;
CanvasUpdater.ForceUpdate(this.canvas, this.canvasScaler);
this.SetScale(scaleMode, fixedScaleResolution);
for (int i = 0; i < this.elements.Count; ++i) this.elements[i].Setup(this.GetWindow());
this.root.Setup(this.GetWindow());
}
public Vector2 GetSize() {
this.ValidateCanvasScaler();
var scaleFactor = 1f;
var width = Screen.width;
var height = Screen.height;
if (this.canvasScaler != null) {
//scaleFactor = this.canvasScaler.scaleFactor;
if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ConstantPixelSize) {
scaleFactor = this.GetConstantPixelSize();
} else if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ConstantPhysicalSize) {
scaleFactor = this.GetConstantPhysicalSize();
} else if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ScaleWithScreenSize) {
scaleFactor = this.GetScaleWithScreenSize();
}
}
return new Vector2(width * scaleFactor, height * scaleFactor);
}
#region GET SIZE
protected float GetConstantPhysicalSize() {
float dpi = Screen.dpi;
float num = (dpi != 0f) ? dpi : this.canvasScaler.fallbackScreenDPI;
float num2 = 1f;
switch (this.canvasScaler.physicalUnit) {
case CanvasScaler.Unit.Centimeters:
num2 = 2.54f;
break;
case CanvasScaler.Unit.Millimeters:
num2 = 25.4f;
break;
case CanvasScaler.Unit.Inches:
num2 = 1f;
break;
case CanvasScaler.Unit.Points:
num2 = 72f;
break;
case CanvasScaler.Unit.Picas:
num2 = 6f;
break;
}
var scaleFactor = num / num2;
return scaleFactor;
}
protected float GetConstantPixelSize() {
return this.canvasScaler.scaleFactor;
}
protected float GetScaleWithScreenSize() {
Vector2 vector = new Vector2(Screen.width, Screen.height);
float scaleFactor = 0f;
switch (this.canvasScaler.screenMatchMode) {
case CanvasScaler.ScreenMatchMode.MatchWidthOrHeight:
{
float num = Mathf.Log (vector.x / this.canvasScaler.referenceResolution.x, 2f);
float num2 = Mathf.Log (vector.y / this.canvasScaler.referenceResolution.y, 2f);
float num3 = Mathf.Lerp (num, num2, this.canvasScaler.matchWidthOrHeight);
scaleFactor = Mathf.Pow (2f, num3);
break;
}
case CanvasScaler.ScreenMatchMode.Expand:
scaleFactor = Mathf.Min (vector.x / this.canvasScaler.referenceResolution.x, vector.y / this.canvasScaler.referenceResolution.y);
break;
case CanvasScaler.ScreenMatchMode.Shrink:
scaleFactor = Mathf.Max (vector.x / this.canvasScaler.referenceResolution.x, vector.y / this.canvasScaler.referenceResolution.y);
break;
}
return scaleFactor;
}
#endregion
public bool ValidateCanvasScaler() {
var changed = false;
if (this.canvasScaler == null) {
this.canvasScaler = this.GetComponent<CanvasScaler>();
changed = true;
}
if (this.canvasScaler == null) {
this.canvasScaler = this.gameObject.AddComponent<CanvasScaler>();
changed = true;
}
return changed;
}
public void SetNoScale() {
this.ValidateCanvasScaler();
this.canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ConstantPixelSize;
this.canvasScaler.enabled = false;
}
public void SetScale(WindowLayout.ScaleMode scaleMode, Vector2 fixedResolution) {
this.ValidateCanvasScaler();
if (scaleMode == ScaleMode.Normal) {
this.SetNoScale();
} else {
this.canvasScaler.enabled = true;
if (scaleMode == ScaleMode.Fixed) {
this.canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
this.canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
this.canvasScaler.matchWidthOrHeight = 0f;
this.canvasScaler.referenceResolution = new Vector2(fixedResolution.x, fixedResolution.y);
} else if (scaleMode == ScaleMode.Custom) {
// We should not do anything in canvasScaler
}
}
}
public void Rebuild(CanvasUpdate executing) {
if (this.root != null) this.root.Rebuild();
}
public bool IsDestroyed() {
return !this.isAlive;
}
public WindowLayoutElement GetRootByTag(LayoutTag tag) {
return this.elements.FirstOrDefault((element) => element.tag == tag);
}
public void GetTags(List<LayoutTag> tags) {
tags.Clear();
foreach (var element in this.elements) {
if (element == null) continue;
tags.Add(element.tag);
}
}
public override void OnShowBegin(System.Action callback, bool resetAnimation = true) {
this.isAlive = true;
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
this.SetComponentState(WindowObjectState.Showing);
ME.Utilities.CallInSequence(() => base.OnShowBegin(callback, resetAnimation), this.subComponents, (e, c) => e.OnShowBegin(c, resetAnimation));
}
public override void OnHideBegin(System.Action callback, bool immediately = false) {
this.SetComponentState(WindowObjectState.Hiding);
ME.Utilities.CallInSequence(() => base.OnHideBegin(callback, immediately), this.subComponents, (e, c) => e.OnHideBegin(c, immediately));
}
public override void OnHideEnd() {
this.isAlive = false;
CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this);
base.OnHideEnd();
}
/*public virtual void OnInit() {}
public virtual void OnDeinit() {}
public virtual void OnShowEnd() {}
public virtual void OnHideBegin(System.Action callback, bool immediately = false) { if (callback != null) callback(); }*/
/*
public virtual void OnShowBeginEvent() {}
public virtual void OnHideEndEvent() {}
*/
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ODataMessage.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
#endregion Namespaces
/// <summary>
/// Base class for the internal wrappers around IODataRequestMessageAsync and IODataResponseMessageAsync.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "This class does not own the BufferingReadStream instance.")]
internal abstract class ODataMessage
{
/// <summary>true if the message is being written; false when it is read.</summary>
private readonly bool writing;
/// <summary>true if the stream returned should ignore dispose calls.</summary>
private readonly bool disableMessageStreamDisposal;
/// <summary>The maximum size of the message in bytes (or null if no maximum applies).</summary>
private readonly long maxMessageSize;
/// <summary>true to use a buffering read stream wrapper around the actual message stream; otherwise false.</summary>
private bool? useBufferingReadStream;
/// <summary>The buffering read stream used for payload kind detection; only non-null inside of payload kind detection.</summary>
private BufferingReadStream bufferingReadStream;
/// <summary>
/// Constructs a new ODataMessage.
/// </summary>
/// <param name="writing">true if the message is being written; false when it is read.</param>
/// <param name="disableMessageStreamDisposal">true if the stream returned should ignore dispose calls.</param>
/// <param name="maxMessageSize">The maximum size of the message in bytes (or a negative value if no maximum applies).</param>
protected ODataMessage(bool writing, bool disableMessageStreamDisposal, long maxMessageSize)
{
this.writing = writing;
this.disableMessageStreamDisposal = disableMessageStreamDisposal;
this.maxMessageSize = maxMessageSize;
}
/// <summary>
/// Returns an enumerable over all the headers for this message.
/// </summary>
public abstract IEnumerable<KeyValuePair<string, string>> Headers
{
// TODO: do we want to impose a certain order of the headers?
get;
}
/// <summary>
/// true to use a buffering read stream wrapper around the actual message stream; otherwise false.
/// </summary>
protected internal BufferingReadStream BufferingReadStream
{
get
{
return this.bufferingReadStream;
}
}
/// <summary>
/// true to use a buffering read stream wrapper around the actual message stream; otherwise false.
/// </summary>
protected internal bool? UseBufferingReadStream
{
get
{
return this.useBufferingReadStream;
}
set
{
Debug.Assert(!this.writing, "UseBufferingReadStream should only be set when reading.");
this.useBufferingReadStream = value;
}
}
/// <summary>
/// Returns a value of an HTTP header.
/// </summary>
/// <param name="headerName">The name of the header to get.</param>
/// <returns>The value of the HTTP header, or null if no such header was present on the message.</returns>
public abstract string GetHeader(string headerName);
/// <summary>
/// Sets the value of an HTTP header.
/// </summary>
/// <param name="headerName">The name of the header to set.</param>
/// <param name="headerValue">The value for the header with name <paramref name="headerName"/>.</param>
public abstract void SetHeader(string headerName, string headerValue);
/// <summary>
/// Get the stream backing this message.
/// </summary>
/// <returns>The stream for this message.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Intentionally a method.")]
public abstract Stream GetStream();
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously get the stream backing this message.
/// </summary>
/// <returns>The stream for this message.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Intentionally a method.")]
public abstract Task<Stream> GetStreamAsync();
#endif
/// <summary>
/// Queries the message for the specified interface type.
/// </summary>
/// <typeparam name="TInterface">The type of the interface to query for.</typeparam>
/// <returns>The instance of the interface asked for or null if it was not implemented by the message.</returns>
/// <remarks>We need this method since the input contexts don't get access to the actual instance of the message given to us by the user
/// instead they get this class, and thus they can't just cast to get to the interface they want.</remarks>
internal abstract TInterface QueryInterface<TInterface>() where TInterface : class;
/// <summary>
/// Synchronously get the stream backing this message.
/// </summary>
/// <param name="messageStreamFunc">A function that returns the stream backing the message.</param>
/// <param name="isRequest">true if the message is a request message; false for a response message.</param>
/// <returns>The <see cref="Stream"/> backing the message.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "We don't own the underlying stream, so we should not dispose the wrapper.")]
protected internal Stream GetStream(Func<Stream> messageStreamFunc, bool isRequest)
{
// Check whether we have an existing buffering read stream when reading
if (!this.writing)
{
BufferingReadStream existingBufferingReadStream = this.TryGetBufferingReadStream();
if (existingBufferingReadStream != null)
{
Debug.Assert(this.useBufferingReadStream.HasValue, "UseBufferingReadStream must have been set.");
return existingBufferingReadStream;
}
}
// Get the message stream
Stream messageStream = messageStreamFunc();
ValidateMessageStream(messageStream, isRequest);
// When reading, wrap the stream in a byte counting stream if a max message size was specified.
// When requested, wrap the stream in a non-disposing stream.
bool needByteCountingStream = !this.writing && this.maxMessageSize > 0;
if (this.disableMessageStreamDisposal && needByteCountingStream)
{
messageStream = MessageStreamWrapper.CreateNonDisposingStreamWithMaxSize(messageStream, this.maxMessageSize);
}
else if (this.disableMessageStreamDisposal)
{
messageStream = MessageStreamWrapper.CreateNonDisposingStream(messageStream);
}
else if (needByteCountingStream)
{
messageStream = MessageStreamWrapper.CreateStreamWithMaxSize(messageStream, this.maxMessageSize);
}
// If a buffering read stream is required, create it now
if (!this.writing && this.useBufferingReadStream == true)
{
Debug.Assert(!this.writing, "The buffering read stream should only be used when reading.");
this.bufferingReadStream = new BufferingReadStream(messageStream);
messageStream = this.bufferingReadStream;
}
return messageStream;
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously get the stream backing this message.
/// </summary>
/// <param name="streamFuncAsync">A function that returns a task for the stream backing the message.</param>
/// <param name="isRequest">true if the message is a request message; false for a response message.</param>
/// <returns>A task that when completed returns the stream backing the message.</returns>
protected internal Task<Stream> GetStreamAsync(Func<Task<Stream>> streamFuncAsync, bool isRequest)
{
// Check whether we have an existing buffering read stream when reading
if (!this.writing)
{
Stream existingBufferingReadStream = this.TryGetBufferingReadStream();
Debug.Assert(!this.writing || existingBufferingReadStream == null, "The buffering read stream should only be used when reading.");
if (existingBufferingReadStream != null)
{
Debug.Assert(this.useBufferingReadStream.HasValue, "UseBufferingReadStream must have been set.");
return TaskUtils.GetCompletedTask(existingBufferingReadStream);
}
}
Task<Stream> task = streamFuncAsync();
ValidateMessageStreamTask(task, isRequest);
// Wrap it in a non-disposing stream if requested
task = task.FollowOnSuccessWith(
streamTask =>
{
Stream messageStream = streamTask.Result;
ValidateMessageStream(messageStream, isRequest);
// When reading, wrap the stream in a byte counting stream if a max message size was specified.
// When requested, wrap the stream in a non-disposing stream.
bool needByteCountingStream = !this.writing && this.maxMessageSize > 0;
if (this.disableMessageStreamDisposal && needByteCountingStream)
{
messageStream = MessageStreamWrapper.CreateNonDisposingStreamWithMaxSize(messageStream, this.maxMessageSize);
}
else if (this.disableMessageStreamDisposal)
{
messageStream = MessageStreamWrapper.CreateNonDisposingStream(messageStream);
}
else if (needByteCountingStream)
{
messageStream = MessageStreamWrapper.CreateStreamWithMaxSize(messageStream, this.maxMessageSize);
}
return messageStream;
});
// When we are reading, also buffer the input stream
if (!this.writing)
{
task = task
.FollowOnSuccessWithTask(
streamTask =>
{
return BufferedReadStream.BufferStreamAsync(streamTask.Result);
})
.FollowOnSuccessWith(
streamTask =>
{
BufferedReadStream bufferedReadStream = streamTask.Result;
return (Stream)bufferedReadStream;
});
// If requested also create a buffering stream for payload kind detection
if (this.useBufferingReadStream == true)
{
task = task.FollowOnSuccessWith(
streamTask =>
{
Stream messageStream = streamTask.Result;
this.bufferingReadStream = new BufferingReadStream(messageStream);
messageStream = this.bufferingReadStream;
return messageStream;
});
}
}
return task;
}
#endif
/// <summary>
/// Verifies that setting a header is allowed
/// </summary>
/// <remarks>
/// We allow modifying the headers only if we are writing the message and we are not
/// detecting the payload kind.
/// </remarks>
protected void VerifyCanSetHeader()
{
if (!this.writing)
{
throw new ODataException(Strings.ODataMessage_MustNotModifyMessage);
}
Debug.Assert(this.bufferingReadStream == null, "The buffering stream should only be used when reading.");
}
/// <summary>
/// Validates that a given message stream can be used.
/// </summary>
/// <param name="stream">The stream to validate.</param>
/// <param name="isRequest">true if the message is a request message; false for a response message.</param>
private static void ValidateMessageStream(Stream stream, bool isRequest)
{
if (stream == null)
{
string error = isRequest
? Strings.ODataRequestMessage_MessageStreamIsNull
: Strings.ODataResponseMessage_MessageStreamIsNull;
throw new ODataException(error);
}
}
#if ODATALIB_ASYNC
/// <summary>
/// Validates that a given task providing the message stream can be used.
/// </summary>
/// <param name="streamTask">The task to validate.</param>
/// <param name="isRequest">true if the message is a request message; false for a response message.</param>
private static void ValidateMessageStreamTask(Task<Stream> streamTask, bool isRequest)
{
if (streamTask == null)
{
string error = isRequest
? Strings.ODataRequestMessage_StreamTaskIsNull
: Strings.ODataResponseMessage_StreamTaskIsNull;
throw new ODataException(error);
}
}
#endif
/// <summary>
/// Gets the buffering read stream if one is available; otherwise returns null.
/// </summary>
/// <returns>The <see cref="BufferingReadStream"/> currently being used or null if no buffering stream is currently being used.</returns>
private BufferingReadStream TryGetBufferingReadStream()
{
if (this.bufferingReadStream == null)
{
return null;
}
// We already have a buffering read stream; reset it if necessary and return it;
// if the stream is not buffering anymore we are done with payload kind detection
// and don't need the buffering stream anymore - we start the actual reading now.
BufferingReadStream stream = this.bufferingReadStream;
if (this.bufferingReadStream.IsBuffering)
{
this.bufferingReadStream.ResetStream();
}
else
{
this.bufferingReadStream = null;
}
return stream;
}
}
}
| |
// 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.Linq;
using System.Threading;
using Xunit;
namespace Test
{
public class SingleSingleOrDefaultTests
{
public static IEnumerable<object[]> SingleSpecificData(object[] counts)
{
Func<int, IEnumerable<int>> positions = x => new[] { 0, x / 2, Math.Max(0, x - 1) }.Distinct();
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), positions)) yield return results;
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), positions)) yield return results;
}
public static IEnumerable<object[]> SingleData(object[] elements, object[] counts)
{
foreach (int element in elements)
{
foreach (object[] results in UnorderedSources.Ranges(element, counts.Cast<int>()))
{
yield return new object[] { results[0], results[1], element };
}
foreach (object[] results in Sources.Ranges(element, counts.Cast<int>()))
{
yield return new object[] { results[0], results[1], element };
}
}
}
//
// Single and SingleOrDefault
//
[Theory]
[MemberData("SingleData", new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 1 })]
public static void Single(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(element, query.Single());
Assert.Equal(element, query.Single(x => true));
}
[Theory]
[MemberData("SingleData", new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 0, 1 })]
public static void SingleOrDefault(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault());
Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault(x => true));
}
[Theory]
[MemberData("SingleData", new int[] { 0, 1024 * 1024 }, new int[] { 0 })]
public static void Single_Empty(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.Single());
Assert.Throws<InvalidOperationException>(() => query.Single(x => true));
}
[Theory]
[MemberData("SingleData", new int[] { 0 }, new int[] { 0, 1, 2, 16 })]
public static void Single_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Throws<InvalidOperationException>(() => query.Single(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void Single_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_NoMatch(labeled, count, element);
}
[Theory]
[MemberData("SingleData", new int[] { 0 }, new int[] { 0, 1, 2, 16 })]
public static void SingleOrDefault_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(default(int), query.SingleOrDefault(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void SingleOrDefault_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_NoMatch(labeled, count, element);
}
[Theory]
[MemberData("SingleData", new int[] { 0 }, new int[] { 2, 16 })]
public static void Single_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.Single(x => true));
}
[Theory]
[OuterLoop]
[MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void Single_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_AllMatch(labeled, count, element);
}
[Theory]
[MemberData("SingleData", new int[] { 0 }, new int[] { 2, 16 })]
public static void SingleOrDefault_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<InvalidOperationException>(() => query.SingleOrDefault(x => true));
}
[Theory]
[OuterLoop]
[MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })]
public static void SingleOrDefault_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_AllMatch(labeled, count, element);
}
[Theory]
[MemberData("SingleSpecificData", (object)(new int[] { 1, 2, 16 }))]
public static void Single_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, query.Single(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SingleSpecificData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Single_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
Single_OneMatch(labeled, count, element);
}
[Theory]
[MemberData("SingleSpecificData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SingleOrDefault_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Equal(element, query.SingleOrDefault(x => seen.Add(x) && x == element));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SingleSpecificData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void SingleOrDefault_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element)
{
SingleOrDefault_OneMatch(labeled, count, element);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Single_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single());
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single(x => true));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault());
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault(x => true));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Single_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Single(x => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.SingleOrDefault(x => { throw new DeliberateTestException(); }));
}
[Fact]
public static void Single_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Single());
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SingleOrDefault());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().Single(null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().SingleOrDefault(null));
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security;
class ObjectToIdCache
{
internal int m_currentCount;
internal int[] m_ids;
internal Object[] m_objs;
bool[] m_isWrapped;
public ObjectToIdCache()
{
m_currentCount = 1;
m_ids = new int[GetPrime(1)];
m_objs = new Object[m_ids.Length];
m_isWrapped = new bool[m_ids.Length];
}
public int GetId(object obj, ref bool newId)
{
bool isEmpty, isWrapped;
int position = FindElement(obj, out isEmpty, out isWrapped);
if (!isEmpty)
{
newId = false;
return m_ids[position];
}
if (!newId)
return -1;
int id = m_currentCount++;
m_objs[position] = obj;
m_ids[position] = id;
m_isWrapped[position] = isWrapped;
if (m_currentCount >= (m_objs.Length - 1))
Rehash();
return id;
}
#if NotUsed
public bool Remove(object obj)
{
bool isEmpty;
int position = FindElement(obj, out isEmpty);
if(isEmpty)
return false;
RemoveAt(position);
return true;
}
#endif
// (oldObjId, oldObj-id, newObj-newObjId) => (oldObj-oldObjId, newObj-id, newObjId )
public int ReassignId(int oldObjId, object oldObj, object newObj)
{
bool isEmpty, isWrapped;
int position = FindElement(oldObj, out isEmpty, out isWrapped);
if (isEmpty)
return 0;
int id = m_ids[position];
if (oldObjId > 0)
m_ids[position] = oldObjId;
else
RemoveAt(position);
position = FindElement(newObj, out isEmpty, out isWrapped);
int newObjId = 0;
if (!isEmpty)
newObjId = m_ids[position];
m_objs[position] = newObj;
m_ids[position] = id;
m_isWrapped[position] = isWrapped;
return newObjId;
}
private int FindElement(object obj, out bool isEmpty, out bool isWrapped)
{
isWrapped = false;
int position = ComputeStartPosition(obj);
for (int i = position; i != (position - 1); i++)
{
if (m_objs[i] == null)
{
isEmpty = true;
return i;
}
if (m_objs[i] == obj)
{
isEmpty = false;
return i;
}
if (i == (m_objs.Length - 1))
{
isWrapped = true;
i = -1;
}
}
// m_obj must ALWAYS have atleast one slot empty (null).
Fx.Assert("Object table overflow");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ObjectTableOverflow)));
}
private void RemoveAt(int position)
{
int cacheSize = m_objs.Length;
int lastVacantPosition = position;
for (int next = (position == cacheSize - 1) ? 0 : position + 1; next != position; next++)
{
if (m_objs[next] == null)
{
m_objs[lastVacantPosition] = null;
m_ids[lastVacantPosition] = 0;
m_isWrapped[lastVacantPosition] = false;
return;
}
int nextStartPosition = ComputeStartPosition(m_objs[next]);
// If we wrapped while placing an object, then it must be that the start position wasn't wrapped to begin with
bool isNextStartPositionWrapped = next < position && !m_isWrapped[next];
bool isLastVacantPositionWrapped = lastVacantPosition < position;
// We want to avoid moving objects in the cache if the next bucket position is wrapped, but the last vacant position isn't
// and we want to make sure to move objects in the cache when the last vacant position is wrapped but the next bucket position isn't
if ((nextStartPosition <= lastVacantPosition && !(isNextStartPositionWrapped && !isLastVacantPositionWrapped)) ||
(isLastVacantPositionWrapped && !isNextStartPositionWrapped))
{
m_objs[lastVacantPosition] = m_objs[next];
m_ids[lastVacantPosition] = m_ids[next];
// A wrapped object might become unwrapped if it moves from the front of the array to the end of the array
m_isWrapped[lastVacantPosition] = m_isWrapped[next] && next > lastVacantPosition;
lastVacantPosition = next;
}
if (next == (cacheSize - 1))
{
next = -1;
}
}
// m_obj must ALWAYS have atleast one slot empty (null).
Fx.Assert("Object table overflow");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ObjectTableOverflow)));
}
private int ComputeStartPosition(object o)
{
return (RuntimeHelpers.GetHashCode(o) & 0x7FFFFFFF) % m_objs.Length;
}
private void Rehash()
{
int size = GetPrime(m_objs.Length * 2);
int[] oldIds = m_ids;
object[] oldObjs = m_objs;
m_ids = new int[size];
m_objs = new Object[size];
m_isWrapped = new bool[size];
for (int j = 0; j < oldObjs.Length; j++)
{
object obj = oldObjs[j];
if (obj != null)
{
bool found, isWrapped;
int position = FindElement(obj, out found, out isWrapped);
m_objs[position] = obj;
m_ids[position] = oldIds[j];
m_isWrapped[position] = isWrapped;
}
}
}
static int GetPrime(int min)
{
for (int i = 0; i < primes.Length; i++)
{
int prime = primes[i];
if (prime >= min) return prime;
}
//outside of our predefined table.
//compute the hard way.
for (int i = (min | 1); i < Int32.MaxValue; i += 2)
{
if (IsPrime(i))
return i;
}
return min;
}
static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int limit = (int)Math.Sqrt(candidate);
for (int divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return (candidate == 2);
}
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
internal static readonly int[] primes =
{
3, 7, 17, 37, 89, 197, 431, 919, 1931, 4049, 8419, 17519, 36353,
75431, 156437, 324449, 672827, 1395263, 2893249, 5999471,
};
}
}
| |
using System;
namespace Loon.Core.Geom {
public class TriangleNeat : Triangle {
private const long serialVersionUID = 1L;
private const float EPSILON = 1E-006F;
private float[] pointsX;
private float[] pointsY;
private int numPoints;
private Edge[] edges;
private int[] sV;
private int numEdges;
private Triangle[] triangles;
private int numTriangles;
private float offset;
public TriangleNeat() {
this.offset = EPSILON;
pointsX = new float[100];
pointsY = new float[100];
numPoints = 0;
edges = new Edge[100];
numEdges = 0;
triangles = new Triangle[100];
numTriangles = 0;
}
public void Clear() {
numPoints = 0;
numEdges = 0;
numTriangles = 0;
}
private int FindEdge(int i, int j) {
int k;
int l;
if (i < j) {
k = i;
l = j;
} else {
k = j;
l = i;
}
for (int i1 = 0; i1 < numEdges; i1++) {
if (edges[i1].v0 == k && edges[i1].v1 == l) {
return i1;
}
}
return -1;
}
private void AddEdge(int i, int j, int k) {
int l1 = FindEdge(i, j);
int j1;
int k1;
Edge edge;
if (l1 < 0) {
if (numEdges == edges.Length) {
Edge[] aedge = new Edge[edges.Length * 2];
System.Array.Copy((Array)(edges),0,(Array)(aedge),0,numEdges);
edges = aedge;
}
j1 = -1;
k1 = -1;
l1 = numEdges++;
edge = edges[l1] = new Edge();
} else {
edge = edges[l1];
j1 = edge.t0;
k1 = edge.t1;
}
int l;
int i1;
if (i < j) {
l = i;
i1 = j;
j1 = k;
} else {
l = j;
i1 = i;
k1 = k;
}
edge.v0 = l;
edge.v1 = i1;
edge.t0 = j1;
edge.t1 = k1;
edge.suspect = true;
}
internal void MarkSuspect(int i, int j, bool flag) {
int k;
if (0 > (k = FindEdge(i, j))) {
throw new Exception("Attempt to mark unknown edge");
} else {
edges[k].suspect = flag;
return;
}
}
private static bool InsideTriangle(float f, float f1, float f2,
float f3, float f4, float f5, float f6, float f7) {
float f8 = f4 - f2;
float f9 = f5 - f3;
float f10 = f - f4;
float f11 = f1 - f5;
float f12 = f2 - f;
float f13 = f3 - f1;
float f14 = f6 - f;
float f15 = f7 - f1;
float f16 = f6 - f2;
float f17 = f7 - f3;
float f18 = f6 - f4;
float f19 = f7 - f5;
float f22 = f8 * f17 - f9 * f16;
float f20 = f12 * f15 - f13 * f14;
float f21 = f10 * f19 - f11 * f18;
return f22 >= 0.0D && f21 >= 0.0D && f20 >= 0.0D;
}
private bool Snip(int i, int j, int k, int l) {
float f = pointsX[sV[i]];
float f1 = pointsY[sV[i]];
float f2 = pointsX[sV[j]];
float f3 = pointsY[sV[j]];
float f4 = pointsX[sV[k]];
float f5 = pointsY[sV[k]];
if (1E-006F > (f2 - f) * (f5 - f1) - (f3 - f1) * (f4 - f))
return false;
for (int i1 = 0; i1 < l; i1++)
if (i1 != i && i1 != j && i1 != k) {
float f6 = pointsX[sV[i1]];
float f7 = pointsY[sV[i1]];
if (InsideTriangle(f, f1, f2, f3, f4, f5, f6, f7))
return false;
}
return true;
}
private float Area() {
float f = 0.0F;
int i = numPoints - 1;
for (int j = 0; j < numPoints;) {
f += pointsX[i] * pointsY[j] - pointsY[i] * pointsX[j];
i = j++;
}
return f * 0.5F;
}
public void BasicTriangulation() {
int i = numPoints;
if (i < 3)
return;
numEdges = 0;
numTriangles = 0;
sV = new int[i];
if (0.0D < Area()) {
for (int k = 0; k < i; k++)
sV[k] = k;
} else {
for (int l = 0; l < i; l++)
sV[l] = numPoints - 1 - l;
}
int k1 = 2 * i;
int i1 = i - 1;
while (i > 2) {
if (0 >= k1--) {
throw new Exception("Bad polygon");
}
int j = i1;
if (i <= j)
j = 0;
i1 = j + 1;
if (i <= i1)
i1 = 0;
int j1 = i1 + 1;
if (i <= j1)
j1 = 0;
if (Snip(j, i1, j1, i)) {
int l1 = sV[j];
int i2 = sV[i1];
int j2 = sV[j1];
if (numTriangles == triangles.Length) {
Triangle[] atriangle = new Triangle[triangles.Length * 2];
System.Array.Copy((triangles),0,(atriangle),0,numTriangles);
triangles = atriangle;
}
triangles[numTriangles] = new Triangle(l1, i2, j2);
AddEdge(l1, i2, numTriangles);
AddEdge(i2, j2, numTriangles);
AddEdge(j2, l1, numTriangles);
numTriangles++;
int k2 = i1;
for (int l2 = i1 + 1; l2 < i; l2++) {
sV[k2] = sV[l2];
k2++;
}
i--;
k1 = 2 * i;
}
}
sV = null;
}
public virtual bool Triangulate() {
try {
BasicTriangulation();
return true;
} catch (Exception) {
numEdges = 0;
}
return false;
}
public virtual void AddPolyPoint(float x, float y) {
for (int i = 0; i < numPoints; i++) {
if ((pointsX[i] == x) && (pointsY[i] == y)) {
y += offset;
offset += EPSILON;
}
}
if (numPoints == pointsX.Length) {
float[] af = new float[numPoints * 2];
System.Array.Copy((Array)(pointsX),0,(Array)(af),0,numPoints);
pointsX = af;
af = new float[numPoints * 2];
System.Array.Copy((Array)(pointsY),0,(Array)(af),0,numPoints);
pointsY = af;
}
pointsX[numPoints] = x;
pointsY[numPoints] = y;
numPoints++;
}
internal class Triangle {
internal int[] v;
internal Triangle(int i, int j, int k) {
v = new int[3];
v[0] = i;
v[1] = j;
v[2] = k;
}
}
internal class Edge {
internal int v0;
internal int v1;
internal int t0;
internal int t1;
internal bool suspect;
internal Edge() {
v0 = -1;
v1 = -1;
t0 = -1;
t1 = -1;
}
}
public virtual int GetTriangleCount() {
return numTriangles;
}
public virtual float[] GetTrianglePoint(int tri, int i) {
float xp = pointsX[triangles[tri].v[i]];
float yp = pointsY[triangles[tri].v[i]];
return new float[] { xp, yp };
}
public virtual void StartHole() {
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using Nini.Config;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Framework.UserManagement
{
public class UserData
{
public UUID Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string HomeURL { get; set; }
public Dictionary<string, object> ServerURLs { get; set; }
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")]
public class UserManagementModule : ISharedRegionModule, IUserManagement
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled;
protected List<Scene> m_Scenes = new List<Scene>();
// The cache
protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>();
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name);
if (umanmod == Name)
{
m_Enabled = true;
RegisterConsoleCmds();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name);
}
}
public bool IsSharedModule
{
get { return true; }
}
public virtual string Name
{
get { return "BasicUserManagementModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IUserManagement>(this);
scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient);
scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IUserManagement>(this);
m_Scenes.Remove(scene);
}
}
public void RegionLoaded(Scene s)
{
}
public void PostInitialise()
{
}
public void Close()
{
m_Scenes.Clear();
lock (m_UserCache)
m_UserCache.Clear();
}
#endregion ISharedRegionModule
#region Event Handlers
void EventManager_OnPrimsLoaded(Scene s)
{
// let's sniff all the user names referenced by objects in the scene
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length);
s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); });
}
void EventManager_OnNewClient(IClientAPI client)
{
client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed);
client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest);
}
void HandleConnectionClosed(IClientAPI client)
{
client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest);
}
void HandleUUIDNameRequest(UUID uuid, IClientAPI remote_client)
{
if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid))
{
remote_client.SendNameReply(uuid, "Mr", "OpenSim");
}
else
{
string[] names = GetUserNames(uuid);
if (names.Length == 2)
{
//m_log.DebugFormat("[XXX] HandleUUIDNameRequest {0} is {1} {2}", uuid, names[0], names[1]);
remote_client.SendNameReply(uuid, names[0], names[1]);
}
}
}
public void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query);
// searhc the user accounts service
List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query);
List<UserData> users = new List<UserData>();
if (accs != null)
{
foreach (UserAccount acc in accs)
{
UserData ud = new UserData();
ud.FirstName = acc.FirstName;
ud.LastName = acc.LastName;
ud.Id = acc.PrincipalID;
users.Add(ud);
}
}
// search the local cache
foreach (UserData data in m_UserCache.Values)
if (users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null &&
(data.FirstName.StartsWith(query) || data.LastName.StartsWith(query)))
users.Add(data);
AddAdditionalUsers(avatarID, query, users);
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[users.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (UserData item in users)
{
UUID translatedIDtem = item.Id;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName);
searchData[i].LastName = Utils.StringToBytes((string)item.LastName);
i++;
}
if (users.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
protected virtual void AddAdditionalUsers(UUID avatarID, string query, List<UserData> users)
{
}
#endregion Event Handlers
private void CacheCreators(SceneObjectGroup sog)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification);
AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
{
AddUser(sop.CreatorID, sop.CreatorData);
foreach (TaskInventoryItem item in sop.TaskInventory.Values)
AddUser(item.CreatorID, item.CreatorData);
}
}
private string[] GetUserNames(UUID uuid)
{
string[] returnstring = new string[2];
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(uuid))
{
returnstring[0] = m_UserCache[uuid].FirstName;
returnstring[1] = m_UserCache[uuid].LastName;
return returnstring;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid);
if (account != null)
{
returnstring[0] = account.FirstName;
returnstring[1] = account.LastName;
UserData user = new UserData();
user.FirstName = account.FirstName;
user.LastName = account.LastName;
lock (m_UserCache)
m_UserCache[uuid] = user;
}
else
{
returnstring[0] = "Unknown";
returnstring[1] = "User";
}
return returnstring;
}
#region IUserManagement
public UUID GetUserIdByName(string name)
{
string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
throw new Exception("Name must have 2 components");
return GetUserIdByName(parts[0], parts[1]);
}
public UUID GetUserIdByName(string firstName, string lastName)
{
// TODO: Optimize for reverse lookup if this gets used by non-console commands.
lock (m_UserCache)
{
foreach (UserData user in m_UserCache.Values)
{
if (user.FirstName == firstName && user.LastName == lastName)
return user.Id;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
if (account != null)
return account.PrincipalID;
return UUID.Zero;
}
public string GetUserName(UUID uuid)
{
string[] names = GetUserNames(uuid);
if (names.Length == 2)
{
string firstname = names[0];
string lastname = names[1];
return firstname + " " + lastname;
}
return "(hippos)";
}
public string GetUserHomeURL(UUID userID)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(userID))
return m_UserCache[userID].HomeURL;
}
return string.Empty;
}
public string GetUserServerURL(UUID userID, string serverType)
{
UserData userdata;
lock (m_UserCache)
m_UserCache.TryGetValue(userID, out userdata);
if (userdata != null)
{
// m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID);
if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null)
{
return userdata.ServerURLs[serverType].ToString();
}
if (userdata.HomeURL != null && userdata.HomeURL != string.Empty)
{
//m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Did not find url type {0} so requesting urls from '{1}' for {2}",
// serverType, userdata.HomeURL, userID);
UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL);
userdata.ServerURLs = uConn.GetServerURLs(userID);
if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null)
return userdata.ServerURLs[serverType].ToString();
}
}
return string.Empty;
}
public string GetUserUUI(UUID userID)
{
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, userID);
if (account != null)
return userID.ToString();
UserData ud;
lock (m_UserCache)
m_UserCache.TryGetValue(userID, out ud);
if (ud != null)
{
string homeURL = ud.HomeURL;
string first = ud.FirstName, last = ud.LastName;
if (ud.LastName.StartsWith("@"))
{
string[] parts = ud.FirstName.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
return userID + ";" + homeURL + ";" + first + " " + last;
}
}
return userID.ToString();
}
public void AddUser(UUID uuid, string first, string last)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(uuid))
return;
}
UserData user = new UserData();
user.Id = uuid;
user.FirstName = first;
user.LastName = last;
AddUserInternal(user);
}
public void AddUser(UUID uuid, string first, string last, string homeURL)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL);
if (homeURL == string.Empty)
return;
AddUser(uuid, homeURL + ";" + first + " " + last);
}
public void AddUser (UUID id, string creatorData)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData);
UserData oldUser;
//lock the whole block - prevent concurrent update
lock (m_UserCache)
{
m_UserCache.TryGetValue (id, out oldUser);
if (oldUser != null)
{
if (creatorData == null || creatorData == String.Empty)
{
//ignore updates without creator data
return;
}
//try update unknown users
//and creator's home URL's
if ((oldUser.FirstName == "Unknown" && !creatorData.Contains ("Unknown")) || (oldUser.HomeURL != null && !creatorData.StartsWith (oldUser.HomeURL)))
{
m_UserCache.Remove (id);
// m_log.DebugFormat("[USER MANAGEMENT MODULE]: Re-adding user with id {0}, creatorData [{1}] and old HomeURL {2}", id, creatorData,oldUser.HomeURL);
}
else
{
//we have already a valid user within the cache
return;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount (m_Scenes [0].RegionInfo.ScopeID, id);
if (account != null)
{
AddUser (id, account.FirstName, account.LastName);
}
else
{
UserData user = new UserData ();
user.Id = id;
if (creatorData != null && creatorData != string.Empty)
{
//creatorData = <endpoint>;<name>
string[] parts = creatorData.Split (';');
if (parts.Length >= 1)
{
user.HomeURL = parts [0];
try
{
Uri uri = new Uri (parts [0]);
user.LastName = "@" + uri.Authority;
}
catch (UriFormatException)
{
m_log.DebugFormat ("[SCENE]: Unable to parse Uri {0}", parts [0]);
user.LastName = "@unknown";
}
}
if (parts.Length >= 2)
user.FirstName = parts [1].Replace (' ', '.');
}
else
{
user.FirstName = "Unknown";
user.LastName = "User";
}
AddUserInternal (user);
}
}
}
void AddUserInternal(UserData user)
{
lock (m_UserCache)
m_UserCache[user.Id] = user;
//m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Added user {0} {1} {2} {3}",
// user.Id, user.FirstName, user.LastName, user.HomeURL);
}
public bool IsLocalGridUser(UUID uuid)
{
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
if (account == null || (account != null && !account.LocalToGrid))
return false;
return true;
}
#endregion IUserManagement
protected void RegisterConsoleCmds()
{
MainConsole.Instance.Commands.AddCommand("Users", true,
"show names",
"show names",
"Show the bindings between user UUIDs and user names",
String.Empty,
HandleShowUsers);
}
private void HandleShowUsers(string module, string[] cmd)
{
lock (m_UserCache)
{
if (m_UserCache.Count == 0)
{
MainConsole.Instance.Output("No users found");
return;
}
MainConsole.Instance.Output("UUID User Name");
MainConsole.Instance.Output("-----------------------------------------------------------------------------");
foreach (KeyValuePair<UUID, UserData> kvp in m_UserCache)
{
MainConsole.Instance.Output(String.Format("{0} {1} {2} ({3})",
kvp.Key, kvp.Value.FirstName, kvp.Value.LastName, kvp.Value.HomeURL));
}
return;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// CurveEditor.designer.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Xna.Tools
{
partial class CurveEditor
{
/// <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(CurveEditor));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.curveListView = new System.Windows.Forms.ListView();
this.curveControl = new Xna.Tools.CurveControl();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 24);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.curveListView);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.curveControl);
this.splitContainer1.Size = new System.Drawing.Size(808, 309);
this.splitContainer1.SplitterDistance = 128;
this.splitContainer1.TabIndex = 0;
//
// curveListView
//
this.curveListView.CheckBoxes = true;
this.curveListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.curveListView.HideSelection = false;
this.curveListView.LabelEdit = true;
this.curveListView.Location = new System.Drawing.Point(0, 0);
this.curveListView.Name = "curveListView";
this.curveListView.Size = new System.Drawing.Size(128, 309);
this.curveListView.TabIndex = 0;
this.curveListView.TileSize = new System.Drawing.Size(168, 16);
this.curveListView.UseCompatibleStateImageBehavior = false;
this.curveListView.View = System.Windows.Forms.View.List;
this.curveListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.curveListView_ItemChecked);
this.curveListView.SelectedIndexChanged += new System.EventHandler(this.curveListView_SelectedIndexChanged);
this.curveListView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.curveListView_KeyDown);
this.curveListView.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.curveListView_AfterLabelEdit);
//
// curveControl
//
this.curveControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.curveControl.Editable = true;
this.curveControl.GridBoldLineColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(102)))), ((int)(((byte)(106)))));
this.curveControl.GridLineColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(205)))), ((int)(((byte)(211)))));
this.curveControl.GridTextColor = System.Drawing.Color.Black;
this.curveControl.Location = new System.Drawing.Point(0, 0);
this.curveControl.MenuVisible = true;
this.curveControl.Name = "curveControl";
this.curveControl.SelectingBoxBorderColor = System.Drawing.Color.Black;
this.curveControl.SelectingBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(80)))), ((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(128)))));
this.curveControl.Size = new System.Drawing.Size(676, 309);
this.curveControl.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(808, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.newToolStripMenuItem.Text = "&New";
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(133, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.saveToolStripMenuItem.Text = "&Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(133, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(111, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.DefaultExt = "xml";
this.saveFileDialog1.Filter = "Xml Files|*.xml|All Files|*.*";
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "xml";
this.openFileDialog1.FileName = "Curve";
this.openFileDialog1.Filter = "Xml Files|*.xml|All Files|*.*";
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "Open Curve File";
//
// CurveEditor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(808, 333);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "CurveEditor";
this.Text = "XNA Curve Editor";
this.Load += new System.EventHandler(this.CurveEditor_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private CurveControl curveControl;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ListView curveListView;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Util.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Util
{
/// <summary>
/// <para>Provides access to version information for HTTP components. Instances of this class provide version information for a single module or informal unit, as explained . Static methods are used to extract version information from property files that are automatically packaged with HTTP component release JARs. <br></br> All available version information is provided in strings, where the string format is informal and subject to change without notice. Version information is provided for debugging output and interpretation by humans, not for automated processing in applications.</para><para><para> </para><simplesectsep></simplesectsep><para>and others </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/VersionInfo
/// </java-name>
[Dot42.DexImport("org/apache/http/util/VersionInfo", AccessFlags = 33)]
public partial class VersionInfo
/* scope: __dot42__ */
{
/// <summary>
/// <para>A string constant for unavailable information. </para>
/// </summary>
/// <java-name>
/// UNAVAILABLE
/// </java-name>
[Dot42.DexImport("UNAVAILABLE", "Ljava/lang/String;", AccessFlags = 25)]
public const string UNAVAILABLE = "UNAVAILABLE";
/// <summary>
/// <para>The filename of the version information files. </para>
/// </summary>
/// <java-name>
/// VERSION_PROPERTY_FILE
/// </java-name>
[Dot42.DexImport("VERSION_PROPERTY_FILE", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_PROPERTY_FILE = "version.properties";
/// <java-name>
/// PROPERTY_MODULE
/// </java-name>
[Dot42.DexImport("PROPERTY_MODULE", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_MODULE = "info.module";
/// <java-name>
/// PROPERTY_RELEASE
/// </java-name>
[Dot42.DexImport("PROPERTY_RELEASE", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_RELEASE = "info.release";
/// <java-name>
/// PROPERTY_TIMESTAMP
/// </java-name>
[Dot42.DexImport("PROPERTY_TIMESTAMP", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROPERTY_TIMESTAMP = "info.timestamp";
/// <summary>
/// <para>Instantiates version information.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)V", AccessFlags = 4)]
protected internal VersionInfo(string pckg, string module, string release, string time, string clsldr) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para>
/// </summary>
/// <returns>
/// <para>the package name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getPackage
/// </java-name>
[Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetPackage() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the module name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getModule
/// </java-name>
[Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetModule() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the release version, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getRelease
/// </java-name>
[Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetRelease() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the timestamp, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getTimestamp
/// </java-name>
[Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetTimestamp() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para>
/// </summary>
/// <returns>
/// <para>the classloader description, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getClassloader
/// </java-name>
[Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetClassloader() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Provides the version information in human-readable format.</para><para></para>
/// </summary>
/// <returns>
/// <para>a string holding this version information </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// loadVersionInfo
/// </java-name>
[Dot42.DexImport("loadVersionInfo", "([Ljava/lang/String;Ljava/lang/ClassLoader;)[Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)]
public static global::Org.Apache.Http.Util.VersionInfo[] LoadVersionInfo(string[] @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo[]);
}
/// <java-name>
/// loadVersionInfo
/// </java-name>
[Dot42.DexImport("loadVersionInfo", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Lorg/apache/http/util/VersionInfo;", AccessFlags = 25)]
public static global::Org.Apache.Http.Util.VersionInfo LoadVersionInfo(string @string, global::Java.Lang.ClassLoader classLoader) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo);
}
/// <summary>
/// <para>Instantiates version information from properties.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version information </para>
/// </returns>
/// <java-name>
/// fromMap
/// </java-name>
[Dot42.DexImport("fromMap", "(Ljava/lang/String;Ljava/util/Map;Ljava/lang/ClassLoader;)Lorg/apache/http/util/V" +
"ersionInfo;", AccessFlags = 28)]
protected internal static global::Org.Apache.Http.Util.VersionInfo FromMap(string pckg, global::Java.Util.IMap<object, object> info, global::Java.Lang.ClassLoader clsldr) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Util.VersionInfo);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal VersionInfo() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the package name. The package name identifies the module or informal unit.</para><para></para>
/// </summary>
/// <returns>
/// <para>the package name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getPackage
/// </java-name>
public string Package
{
[Dot42.DexImport("getPackage", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetPackage(); }
}
/// <summary>
/// <para>Obtains the name of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the module name, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getModule
/// </java-name>
public string Module
{
[Dot42.DexImport("getModule", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetModule(); }
}
/// <summary>
/// <para>Obtains the release of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the release version, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getRelease
/// </java-name>
public string Release
{
[Dot42.DexImport("getRelease", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetRelease(); }
}
/// <summary>
/// <para>Obtains the timestamp of the versioned module or informal unit. This data is read from the version information for the package.</para><para></para>
/// </summary>
/// <returns>
/// <para>the timestamp, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getTimestamp
/// </java-name>
public string Timestamp
{
[Dot42.DexImport("getTimestamp", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetTimestamp(); }
}
/// <summary>
/// <para>Obtains the classloader used to read the version information. This is just the <code>toString</code> output of the classloader, since the version information should not keep a reference to the classloader itself. That could prevent garbage collection.</para><para></para>
/// </summary>
/// <returns>
/// <para>the classloader description, never <code>null</code> </para>
/// </returns>
/// <java-name>
/// getClassloader
/// </java-name>
public string Classloader
{
[Dot42.DexImport("getClassloader", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetClassloader(); }
}
}
/// <summary>
/// <para>A set of utility methods to help produce consistent equals and hashCode methods.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/LangUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/LangUtils", AccessFlags = 49)]
public sealed partial class LangUtils
/* scope: __dot42__ */
{
/// <java-name>
/// HASH_SEED
/// </java-name>
[Dot42.DexImport("HASH_SEED", "I", AccessFlags = 25)]
public const int HASH_SEED = 17;
/// <java-name>
/// HASH_OFFSET
/// </java-name>
[Dot42.DexImport("HASH_OFFSET", "I", AccessFlags = 25)]
public const int HASH_OFFSET = 37;
/// <summary>
/// <para>Disabled default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal LangUtils() /* MethodBuilder.Create */
{
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(II)I", AccessFlags = 9)]
public static int GetHashCode(int int32, int int321) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(IZ)I", AccessFlags = 9)]
public static int GetHashCode(int int32, bool boolean) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "(ILjava/lang/Object;)I", AccessFlags = 9)]
public static int GetHashCode(int int32, object @object) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;Ljava/lang/Object;)Z", AccessFlags = 9)]
public static bool Equals(object @object, object object1) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "([Ljava/lang/Object;[Ljava/lang/Object;)Z", AccessFlags = 9)]
public static bool Equals(object[] @object, object[] object1) /* MethodBuilder.Create */
{
return default(bool);
}
}
/// <summary>
/// <para>A resizable char array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/CharArrayBuffer
/// </java-name>
[Dot42.DexImport("org/apache/http/util/CharArrayBuffer", AccessFlags = 49)]
public sealed partial class CharArrayBuffer
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public CharArrayBuffer(int capacity) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([CII)V", AccessFlags = 1)]
public void Append(char[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/String;)V", AccessFlags = 1)]
public void Append(string b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(C)V", AccessFlags = 1)]
public void Append(char b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1)]
public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)]
public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/ByteArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.ByteArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public void Append(object b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toCharArray
/// </java-name>
[Dot42.DexImport("toCharArray", "()[C", AccessFlags = 1)]
public char[] ToCharArray() /* MethodBuilder.Create */
{
return default(char[]);
}
/// <java-name>
/// charAt
/// </java-name>
[Dot42.DexImport("charAt", "(I)C", AccessFlags = 1)]
public char CharAt(int i) /* MethodBuilder.Create */
{
return default(char);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[C", AccessFlags = 1)]
public char[] Buffer() /* MethodBuilder.Create */
{
return default(char[]);
}
/// <java-name>
/// capacity
/// </java-name>
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
public int Capacity() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// length
/// </java-name>
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
public int Length() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// ensureCapacity
/// </java-name>
[Dot42.DexImport("ensureCapacity", "(I)V", AccessFlags = 1)]
public void EnsureCapacity(int required) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setLength
/// </java-name>
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
public void SetLength(int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isEmpty
/// </java-name>
[Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)]
public bool IsEmpty() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isFull
/// </java-name>
[Dot42.DexImport("isFull", "()Z", AccessFlags = 1)]
public bool IsFull() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(III)I", AccessFlags = 1)]
public int IndexOf(int ch, int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// indexOf
/// </java-name>
[Dot42.DexImport("indexOf", "(I)I", AccessFlags = 1)]
public int IndexOf(int ch) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// substring
/// </java-name>
[Dot42.DexImport("substring", "(II)Ljava/lang/String;", AccessFlags = 1)]
public string Substring(int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// substringTrimmed
/// </java-name>
[Dot42.DexImport("substringTrimmed", "(II)Ljava/lang/String;", AccessFlags = 1)]
public string SubstringTrimmed(int beginIndex, int endIndex) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CharArrayBuffer() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>The home for utility methods that handle various encoding tasks.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/EncodingUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/EncodingUtils", AccessFlags = 49)]
public sealed partial class EncodingUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>This class should not be instantiated. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EncodingUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetString(sbyte[] data, int offset, int length, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BIILjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetString(byte[] data, int offset, int length, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetString(sbyte[] data, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result of the conversion. </para>
/// </returns>
/// <java-name>
/// getString
/// </java-name>
[Dot42.DexImport("getString", "([BLjava/lang/String;)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetString(byte[] data, string charset) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The resulting byte array. </para>
/// </returns>
/// <java-name>
/// getBytes
/// </java-name>
[Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9)]
public static sbyte[] JavaGetBytes(string data, string charset) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <summary>
/// <para>Converts the specified string to a byte array. If the charset is not supported the default system charset is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>The resulting byte array. </para>
/// </returns>
/// <java-name>
/// getBytes
/// </java-name>
[Dot42.DexImport("getBytes", "(Ljava/lang/String;Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] GetBytes(string data, string charset) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <summary>
/// <para>Converts the specified string to byte array of ASCII characters.</para><para></para>
/// </summary>
/// <returns>
/// <para>The string as a byte array. </para>
/// </returns>
/// <java-name>
/// getAsciiBytes
/// </java-name>
[Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9)]
public static sbyte[] JavaGetAsciiBytes(string data) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <summary>
/// <para>Converts the specified string to byte array of ASCII characters.</para><para></para>
/// </summary>
/// <returns>
/// <para>The string as a byte array. </para>
/// </returns>
/// <java-name>
/// getAsciiBytes
/// </java-name>
[Dot42.DexImport("getAsciiBytes", "(Ljava/lang/String;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] GetAsciiBytes(string data) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9)]
public static string GetAsciiString(sbyte[] data, int offset, int length) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([BII)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetAsciiString(byte[] data, int offset, int length) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9)]
public static string GetAsciiString(sbyte[] data) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Converts the byte array of ASCII characters to a string. This method is to be used when decoding content of HTTP elements (such as response headers)</para><para></para>
/// </summary>
/// <returns>
/// <para>The string representation of the byte array </para>
/// </returns>
/// <java-name>
/// getAsciiString
/// </java-name>
[Dot42.DexImport("getAsciiString", "([B)Ljava/lang/String;", AccessFlags = 9, IgnoreFromJava = true)]
public static string GetAsciiString(byte[] data) /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>A resizable byte array.</para><para><para></para><para></para><title>Revision:</title><para>496070 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/ByteArrayBuffer
/// </java-name>
[Dot42.DexImport("org/apache/http/util/ByteArrayBuffer", AccessFlags = 49)]
public sealed partial class ByteArrayBuffer
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)]
public ByteArrayBuffer(int capacity) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1)]
public void Append(sbyte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)]
public void Append(byte[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(I)V", AccessFlags = 1)]
public void Append(int b) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "([CII)V", AccessFlags = 1)]
public void Append(char[] b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// append
/// </java-name>
[Dot42.DexImport("append", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1)]
public void Append(global::Org.Apache.Http.Util.CharArrayBuffer b, int off, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1)]
public sbyte[] JavaToByteArray() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public byte[] ToByteArray() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// byteAt
/// </java-name>
[Dot42.DexImport("byteAt", "(I)I", AccessFlags = 1)]
public int ByteAt(int i) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// capacity
/// </java-name>
[Dot42.DexImport("capacity", "()I", AccessFlags = 1)]
public int Capacity() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// length
/// </java-name>
[Dot42.DexImport("length", "()I", AccessFlags = 1)]
public int Length() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[B", AccessFlags = 1)]
public sbyte[] JavaBuffer() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// buffer
/// </java-name>
[Dot42.DexImport("buffer", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public byte[] Buffer() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// setLength
/// </java-name>
[Dot42.DexImport("setLength", "(I)V", AccessFlags = 1)]
public void SetLength(int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isEmpty
/// </java-name>
[Dot42.DexImport("isEmpty", "()Z", AccessFlags = 1)]
public bool IsEmpty() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isFull
/// </java-name>
[Dot42.DexImport("isFull", "()Z", AccessFlags = 1)]
public bool IsFull() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ByteArrayBuffer() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Static helpers for dealing with entities.</para><para><para></para><para></para><title>Revision:</title><para>569637 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/EntityUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/EntityUtils", AccessFlags = 49)]
public sealed partial class EntityUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>Disabled default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal EntityUtils() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9)]
public static sbyte[] JavaToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// toByteArray
/// </java-name>
[Dot42.DexImport("toByteArray", "(Lorg/apache/http/HttpEntity;)[B", AccessFlags = 9, IgnoreFromJava = true)]
public static byte[] ToByteArray(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getContentCharSet
/// </java-name>
[Dot42.DexImport("getContentCharSet", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetContentCharSet(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string ToString(global::Org.Apache.Http.IHttpEntity entity, string defaultCharset) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "(Lorg/apache/http/HttpEntity;)Ljava/lang/String;", AccessFlags = 9)]
public static string ToString(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>The home for utility methods that handle various exception-related tasks.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/util/ExceptionUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/util/ExceptionUtils", AccessFlags = 49)]
public sealed partial class ExceptionUtils
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal ExceptionUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>If we're running on JDK 1.4 or later, initialize the cause for the given throwable.</para><para></para>
/// </summary>
/// <java-name>
/// initCause
/// </java-name>
[Dot42.DexImport("initCause", "(Ljava/lang/Throwable;Ljava/lang/Throwable;)V", AccessFlags = 9)]
public static void InitCause(global::System.Exception throwable, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Services.Common;
using Nop.Services.Configuration;
namespace Nop.Services.Helpers
{
/// <summary>
/// Represents a datetime helper
/// </summary>
public partial class DateTimeHelper : IDateTimeHelper
{
private readonly IWorkContext _workContext;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ISettingService _settingService;
private readonly DateTimeSettings _dateTimeSettings;
/// <summary>
/// Ctor
/// </summary>
/// <param name="workContext">Work context</param>
/// <param name="genericAttributeService">Generic attribute service</param>
/// <param name="settingService">Setting service</param>
/// <param name="dateTimeSettings">Datetime settings</param>
public DateTimeHelper(IWorkContext workContext,
IGenericAttributeService genericAttributeService,
ISettingService settingService,
DateTimeSettings dateTimeSettings)
{
this._workContext = workContext;
this._genericAttributeService = genericAttributeService;
this._settingService = settingService;
this._dateTimeSettings = dateTimeSettings;
}
/// <summary>
/// Retrieves a System.TimeZoneInfo object from the registry based on its identifier.
/// </summary>
/// <param name="id">The time zone identifier, which corresponds to the System.TimeZoneInfo.Id property.</param>
/// <returns>A System.TimeZoneInfo object whose identifier is the value of the id parameter.</returns>
public virtual TimeZoneInfo FindTimeZoneById(string id)
{
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
/// <summary>
/// Returns a sorted collection of all the time zones
/// </summary>
/// <returns>A read-only collection of System.TimeZoneInfo objects.</returns>
public virtual ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
{
return TimeZoneInfo.GetSystemTimeZones();
}
/// <summary>
/// Converts the date and time to current user date and time
/// </summary>
/// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>
/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
public virtual DateTime ConvertToUserTime(DateTime dt)
{
return ConvertToUserTime(dt, dt.Kind);
}
/// <summary>
/// Converts the date and time to current user date and time
/// </summary>
/// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>
/// <param name="sourceDateTimeKind">The source datetimekind</param>
/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
public virtual DateTime ConvertToUserTime(DateTime dt, DateTimeKind sourceDateTimeKind)
{
dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
var currentUserTimeZoneInfo = this.CurrentTimeZone;
return TimeZoneInfo.ConvertTime(dt, currentUserTimeZoneInfo);
}
/// <summary>
/// Converts the date and time to current user date and time
/// </summary>
/// <param name="dt">The date and time to convert.</param>
/// <param name="sourceTimeZone">The time zone of dateTime.</param>
/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
public virtual DateTime ConvertToUserTime(DateTime dt, TimeZoneInfo sourceTimeZone)
{
var currentUserTimeZoneInfo = this.CurrentTimeZone;
return ConvertToUserTime(dt, sourceTimeZone, currentUserTimeZoneInfo);
}
/// <summary>
/// Converts the date and time to current user date and time
/// </summary>
/// <param name="dt">The date and time to convert.</param>
/// <param name="sourceTimeZone">The time zone of dateTime.</param>
/// <param name="destinationTimeZone">The time zone to convert dateTime to.</param>
/// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
public virtual DateTime ConvertToUserTime(DateTime dt, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
{
return TimeZoneInfo.ConvertTime(dt, sourceTimeZone, destinationTimeZone);
}
/// <summary>
/// Converts the date and time to Coordinated Universal Time (UTC)
/// </summary>
/// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>
/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
public virtual DateTime ConvertToUtcTime(DateTime dt)
{
return ConvertToUtcTime(dt, dt.Kind);
}
/// <summary>
/// Converts the date and time to Coordinated Universal Time (UTC)
/// </summary>
/// <param name="dt">The date and time (respesents local system time or UTC time) to convert.</param>
/// <param name="sourceDateTimeKind">The source datetimekind</param>
/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
public virtual DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind)
{
dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
return TimeZoneInfo.ConvertTimeToUtc(dt);
}
/// <summary>
/// Converts the date and time to Coordinated Universal Time (UTC)
/// </summary>
/// <param name="dt">The date and time to convert.</param>
/// <param name="sourceTimeZone">The time zone of dateTime.</param>
/// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
public virtual DateTime ConvertToUtcTime(DateTime dt, TimeZoneInfo sourceTimeZone)
{
if (sourceTimeZone.IsInvalidTime(dt))
{
//could not convert
return dt;
}
return TimeZoneInfo.ConvertTimeToUtc(dt, sourceTimeZone);
}
/// <summary>
/// Gets a customer time zone
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Customer time zone; if customer is null, then default store time zone</returns>
public virtual TimeZoneInfo GetCustomerTimeZone(Customer customer)
{
//registered user
TimeZoneInfo timeZoneInfo = null;
if (_dateTimeSettings.AllowCustomersToSetTimeZone)
{
string timeZoneId = string.Empty;
if (customer != null)
timeZoneId = customer.GetAttribute<string>(SystemCustomerAttributeNames.TimeZoneId, _genericAttributeService);
try
{
if (!String.IsNullOrEmpty(timeZoneId))
timeZoneInfo = FindTimeZoneById(timeZoneId);
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
}
//default timezone
if (timeZoneInfo == null)
timeZoneInfo = this.DefaultStoreTimeZone;
return timeZoneInfo;
}
/// <summary>
/// Gets or sets a default store time zone
/// </summary>
public virtual TimeZoneInfo DefaultStoreTimeZone
{
get
{
TimeZoneInfo timeZoneInfo = null;
try
{
if (!String.IsNullOrEmpty(_dateTimeSettings.DefaultStoreTimeZoneId))
timeZoneInfo = FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
if (timeZoneInfo == null)
timeZoneInfo = TimeZoneInfo.Local;
return timeZoneInfo;
}
set
{
string defaultTimeZoneId = string.Empty;
if (value != null)
{
defaultTimeZoneId = value.Id;
}
_dateTimeSettings.DefaultStoreTimeZoneId = defaultTimeZoneId;
_settingService.SaveSetting(_dateTimeSettings);
}
}
/// <summary>
/// Gets or sets the current user time zone
/// </summary>
public virtual TimeZoneInfo CurrentTimeZone
{
get
{
return GetCustomerTimeZone(_workContext.CurrentCustomer);
}
set
{
if (!_dateTimeSettings.AllowCustomersToSetTimeZone)
return;
string timeZoneId = string.Empty;
if (value != null)
{
timeZoneId = value.Id;
}
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.TimeZoneId, timeZoneId);
}
}
}
}
| |
/*
Copyright (c) 2006 - 2008 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.
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace OpenTK
{
/// <summary>
/// 3-component Vector of the Half type. Occupies 6 Byte total.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Vector3h : IEquatable<Vector3h>
{
/// <summary>The X component of the Half3.</summary>
public Half X;
/// <summary>The Y component of the Half3.</summary>
public Half Y;
/// <summary>The Z component of the Half3.</summary>
public Half Z;
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Half value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector3h(Single value)
{
X = new Half(value);
Y = new Half(value);
Z = new Half(value);
}
/// <summary>
/// The new Half3 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector3h(Half x, Half y, Half z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
public Vector3h(Single x, Single y, Single z)
{
X = new Half(x);
Y = new Half(y);
Z = new Half(z);
}
/// <summary>
/// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector3h(Single x, Single y, Single z, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
Z = new Half(z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
public Vector3h(ref Vector3 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
}
/// <summary>
/// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector3d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector3h(ref Vector3d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
}
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xz { get { return new Vector2h(X, Z); } set { X = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yx { get { return new Vector2h(Y, X); } set { Y = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yz { get { return new Vector2h(Y, Z); } set { Y = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zx { get { return new Vector2h(Z, X); } set { Z = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zy { get { return new Vector2h(Z, Y); } set { Z = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xzy { get { return new Vector3h(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yxz { get { return new Vector3h(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yzx { get { return new Vector3h(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zxy { get { return new Vector3h(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zyx { get { return new Vector3h(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } }
/// <summary>
/// Returns this Half3 instance's contents as Vector3.
/// </summary>
/// <returns>OpenTK.Vector3</returns>
public Vector3 ToVector3()
{
return new Vector3(X, Y, Z);
}
/// <summary>
/// Returns this Half3 instance's contents as Vector3d.
/// </summary>
public Vector3d ToVector3d()
{
return new Vector3d(X, Y, Z);
}
/// <summary>Converts OpenTK.Vector3 to OpenTK.Half3.</summary>
/// <param name="v3f">The Vector3 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3 v3f)
{
return new Vector3h(v3f);
}
/// <summary>Converts OpenTK.Vector3d to OpenTK.Half3.</summary>
/// <param name="v3d">The Vector3d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector3h(Vector3d v3d)
{
return new Vector3h(v3d);
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3.</returns>
public static explicit operator Vector3(Vector3h h3)
{
return new Vector3(
h3.X.ToSingle(),
h3.Y.ToSingle(),
h3.Z.ToSingle());
}
/// <summary>Converts OpenTK.Half3 to OpenTK.Vector3d.</summary>
/// <param name="h3">The Half3 to convert.</param>
/// <returns>The resulting Vector3d.</returns>
public static explicit operator Vector3d(Vector3h h3)
{
return new Vector3d(
h3.X.ToSingle(),
h3.Y.ToSingle(),
h3.Z.ToSingle());
}
/// <summary>The size in bytes for an instance of the Half3 struct is 6.</summary>
public static readonly int SizeInBytes = 6;
///// <summary>Constructor used by ISerializable to deserialize the object.</summary>
///// <param name="info"></param>
///// <param name="context"></param>
//public Vector3h(SerializationInfo info, StreamingContext context)
//{
// this.X = (Half)info.GetValue("X", typeof(Half));
// this.Y = (Half)info.GetValue("Y", typeof(Half));
// this.Z = (Half)info.GetValue("Z", typeof(Half));
//}
///// <summary>Used by ISerialize to serialize the object.</summary>
///// <param name="info"></param>
///// <param name="context"></param>
//public void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// info.AddValue("X", this.X);
// info.AddValue("Y", this.Y);
// info.AddValue("Z", this.Z);
//}
/// <summary>Updates the X,Y and Z components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
Z.FromBinaryStream(bin);
}
/// <summary>Writes the X,Y and Z components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
Z.ToBinaryStream(bin);
}
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half3 vector.</summary>
/// <param name="other">OpenTK.Half3 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector3h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z));
}
private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
/// <summary>Returns a string that contains this Half3's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}{3} {1}{3} {2})", X.ToString(), Y.ToString(), Z.ToString(), listSeparator);
}
/// <summary>Returns the Half3 as an array of bytes.</summary>
/// <param name="h">The Half3 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector3h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
temp = Half.GetBytes(h.Z);
result[4] = temp[0];
result[5] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half3.</summary>
/// <param name="value">A Half3 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half3 instance.</returns>
public static Vector3h FromBytes(byte[] value, int startIndex)
{
return new Vector3h(
Half.FromBytes(value, startIndex),
Half.FromBytes(value, startIndex + 2),
Half.FromBytes(value, startIndex + 4));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase
{
[Fact]
public void CreateBuilderDefaultCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>();
Assert.NotNull(builder);
Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>());
}
[Fact]
public void CreateBuilderInvalidCapacity()
{
Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateBuilder<int>(-1));
}
[Fact]
public void NormalConstructionValueType()
{
var builder = ImmutableArray.CreateBuilder<int>(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<int>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Equal(0, builder[i]);
}
builder.Add(5);
builder.Add(6);
builder.Add(7);
Assert.Equal(5, builder[0]);
Assert.Equal(6, builder[1]);
Assert.Equal(7, builder[2]);
}
[Fact]
public void NormalConstructionRefType()
{
var builder = new ImmutableArray<GenericParameterHelper>.Builder(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Null(builder[i]);
}
builder.Add(new GenericParameterHelper(5));
builder.Add(new GenericParameterHelper(6));
builder.Add(new GenericParameterHelper(7));
Assert.Equal(5, builder[0].Data);
Assert.Equal(6, builder[1].Data);
Assert.Equal(7, builder[2].Data);
}
[Fact]
public void AddRangeIEnumerable()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.AddRange((IEnumerable<int>)new[] { 1 });
Assert.Equal(1, builder.Count);
builder.AddRange((IEnumerable<int>)new[] { 2 });
Assert.Equal(2, builder.Count);
// Exceed capacity
builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count
Assert.Equal(4, builder.Count);
Assert.Equal(Enumerable.Range(1, 4), builder);
}
[Fact]
public void Add()
{
var builder = ImmutableArray.CreateBuilder<int>(0);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(1);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(2);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
}
[Fact]
public void AddRangeBuilder()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var builder2 = new ImmutableArray<int>.Builder(2);
builder1.AddRange(builder2);
Assert.Equal(0, builder1.Count);
Assert.Equal(0, builder2.Count);
builder2.Add(1);
builder2.Add(2);
builder1.AddRange(builder2);
Assert.Equal(2, builder1.Count);
Assert.Equal(2, builder2.Count);
Assert.Equal(new[] { 1, 2 }, builder1);
}
[Fact]
public void AddRangeImmutableArray()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var array = ImmutableArray.Create(1, 2, 3);
builder1.AddRange(array);
Assert.Equal(new[] { 1, 2, 3 }, builder1);
Assert.Throws<ArgumentNullException>(() => builder1.AddRange((int[])null));
Assert.Throws<ArgumentNullException>(() => builder1.AddRange(null, 42));
Assert.Throws<ArgumentOutOfRangeException>(() => builder1.AddRange(new int[0], -1));
Assert.Throws<IndexOutOfRangeException>(() => builder1.AddRange(new int[0], 42));
Assert.Throws<ArgumentNullException>(() => builder1.AddRange((ImmutableArray<int>.Builder)null));
Assert.Throws<ArgumentNullException>(() => builder1.AddRange((IEnumerable<int>)null));
Assert.Throws<NullReferenceException>(() => builder1.AddRange(default(ImmutableArray<int>)));
builder1.AddRange(default(ImmutableArray<int>), 42);
var builder2 = new ImmutableArray<object>.Builder();
builder2.AddRange(default(ImmutableArray<string>));
Assert.Throws<ArgumentNullException>(() => builder2.AddRange((ImmutableArray<string>.Builder)null));
}
[Fact]
public void AddRangeDerivedArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" });
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedImmutableArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" }.ToImmutableArray());
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedBuilder()
{
var builder = new ImmutableArray<string>.Builder();
builder.AddRange(new[] { "a", "b" });
var builderBase = new ImmutableArray<object>.Builder();
builderBase.AddRange(builder);
Assert.Equal(new[] { "a", "b" }, builderBase);
}
[Fact]
public void Contains()
{
var builder = new ImmutableArray<int>.Builder();
Assert.False(builder.Contains(1));
builder.Add(1);
Assert.True(builder.Contains(1));
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void Insert()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
builder.Insert(1, 4);
builder.Insert(4, 5);
Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(builder.Count + 1, 0));
}
[Fact]
public void Remove()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
Assert.True(builder.Remove(1));
Assert.False(builder.Remove(6));
Assert.Equal(new[] { 2, 3, 4 }, builder);
Assert.True(builder.Remove(3));
Assert.Equal(new[] { 2, 4 }, builder);
Assert.True(builder.Remove(4));
Assert.Equal(new[] { 2 }, builder);
Assert.True(builder.Remove(2));
Assert.Equal(0, builder.Count);
}
[Fact]
public void RemoveAt()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.RemoveAt(0);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(3));
Assert.Equal(new[] { 2, 3, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
Assert.Equal(0, builder.Count);
}
[Fact]
public void ReverseContents()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.Reverse();
Assert.Equal(new[] { 4, 3, 2, 1 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 1, 2, 3 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 3, 2 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new int[0], builder);
}
[Fact]
public void Sort()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
builder.Sort();
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void SortNullComparer()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
builder.Sort(null);
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void SortOneElementArray()
{
int[] resultantArray = new[] { 4 };
var builder1 = new ImmutableArray<int>.Builder();
builder1.Add(4);
builder1.Sort();
Assert.Equal(resultantArray, builder1);
var builder2 = new ImmutableArray<int>.Builder();
builder2.Add(4);
builder2.Sort(Comparer<int>.Default);
Assert.Equal(resultantArray, builder2);
var builder3 = new ImmutableArray<int>.Builder();
builder3.Add(4);
builder3.Sort(0, 1, Comparer<int>.Default);
Assert.Equal(resultantArray, builder3);
}
[Fact]
public void SortRange()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(-1, 2, Comparer<int>.Default));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(1, 4, Comparer<int>.Default));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(0, -1, Comparer<int>.Default));
builder.Sort(builder.Count, 0, Comparer<int>.Default);
Assert.Equal(new int[] { 2, 4, 1, 3 }, builder);
builder.Sort(1, 2, Comparer<int>.Default);
Assert.Equal(new[] { 2, 1, 4, 3 }, builder);
}
[Fact]
public void SortComparer()
{
var builder1 = new ImmutableArray<string>.Builder();
var builder2 = new ImmutableArray<string>.Builder();
builder1.AddRange("c", "B", "a");
builder2.AddRange("c", "B", "a");
builder1.Sort(StringComparer.OrdinalIgnoreCase);
builder2.Sort(StringComparer.Ordinal);
Assert.Equal(new[] { "a", "B", "c" }, builder1);
Assert.Equal(new[] { "B", "a", "c" }, builder2);
}
[Fact]
public void Count()
{
var builder = new ImmutableArray<int>.Builder(3);
// Initial count is at zero, which is less than capacity.
Assert.Equal(0, builder.Count);
// Expand the accessible region of the array by increasing the count, but still below capacity.
builder.Count = 2;
Assert.Equal(2, builder.Count);
Assert.Equal(2, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
// Expand the accessible region of the array beyond the current capacity.
builder.Count = 4;
Assert.Equal(4, builder.Count);
Assert.Equal(4, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Equal(0, builder[2]);
Assert.Equal(0, builder[3]);
Assert.Throws<IndexOutOfRangeException>(() => builder[4]);
}
[Fact]
public void CountContract()
{
var builder = new ImmutableArray<int>.Builder(100);
builder.AddRange(Enumerable.Range(1, 100));
builder.Count = 10;
Assert.Equal(Enumerable.Range(1, 10), builder);
builder.Count = 100;
Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder);
}
[Fact]
public void IndexSetter()
{
var builder = new ImmutableArray<int>.Builder();
Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1);
Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1);
builder.Count = 1;
builder[0] = 2;
Assert.Equal(2, builder[0]);
builder.Count = 10;
builder[9] = 3;
Assert.Equal(3, builder[9]);
builder.Count = 2;
Assert.Equal(2, builder[0]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
}
[Fact]
public void ToImmutable()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
ImmutableArray<int> array = builder.ToImmutable();
Assert.Equal(1, array[0]);
Assert.Equal(2, array[1]);
Assert.Equal(3, array[2]);
// Make sure that subsequent mutation doesn't impact the immutable array.
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(2, array[1]);
builder.Clear();
Assert.True(builder.ToImmutable().IsEmpty);
}
[Fact]
public void CopyTo()
{
var builder = ImmutableArray.Create(1, 2, 3).ToBuilder();
var target = new int[4];
builder.CopyTo(target, 1);
Assert.Equal(new[] { 0, 1, 2, 3 }, target);
Assert.Throws<ArgumentNullException>(() => builder.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.CopyTo(target, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.CopyTo(target, 2));
}
[Fact]
public void Clear()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.Add(1);
builder.Add(1);
builder.Clear();
Assert.Equal(0, builder.Count);
Assert.Throws<IndexOutOfRangeException>(() => builder[0]);
}
[Fact]
public void MutationsSucceedAfterToImmutable()
{
var builder = new ImmutableArray<int>.Builder(1);
builder.Add(1);
var immutable = builder.ToImmutable();
builder[0] = 0;
Assert.Equal(0, builder[0]);
Assert.Equal(1, immutable[0]);
}
[Fact]
public void Enumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = empty.GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = manyElements.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void IEnumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = ((IEnumerable<int>)empty).GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = ((IEnumerable<int>)manyElements).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void MoveToImmutableNormal()
{
var builder = CreateBuilderWithCount<string>(2);
Assert.Equal(2, builder.Count);
Assert.Equal(2, builder.Capacity);
builder[1] = "b";
builder[0] = "a";
var array = builder.MoveToImmutable();
Assert.Equal(new[] { "a", "b" }, array);
Assert.Equal(0, builder.Count);
Assert.Equal(0, builder.Capacity);
}
[Fact]
public void MoveToImmutableRepeat()
{
var builder = CreateBuilderWithCount<string>(2);
builder[0] = "a";
builder[1] = "b";
var array1 = builder.MoveToImmutable();
var array2 = builder.MoveToImmutable();
Assert.Equal(new[] { "a", "b" }, array1);
Assert.Equal(0, array2.Length);
}
[Fact]
public void MoveToImmutablePartialFill()
{
var builder = ImmutableArray.CreateBuilder<int>(4);
builder.Add(42);
builder.Add(13);
Assert.Equal(4, builder.Capacity);
Assert.Equal(2, builder.Count);
Assert.Throws(typeof(InvalidOperationException), () => builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutablePartialFillWithCountUpdate()
{
var builder = ImmutableArray.CreateBuilder<int>(4);
builder.Add(42);
builder.Add(13);
Assert.Equal(4, builder.Capacity);
Assert.Equal(2, builder.Count);
builder.Count = builder.Capacity;
var array = builder.MoveToImmutable();
Assert.Equal(new[] { 42, 13, 0, 0 }, array);
}
[Fact]
public void MoveToImmutableThenUse()
{
var builder = CreateBuilderWithCount<string>(2);
Assert.Equal(2, builder.MoveToImmutable().Length);
Assert.Equal(0, builder.Capacity);
builder.Add("a");
builder.Add("b");
Assert.Equal(2, builder.Count);
Assert.True(builder.Capacity >= 2);
Assert.Equal(new[] { "a", "b" }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAfterClear()
{
var builder = CreateBuilderWithCount<string>(2);
builder[0] = "a";
builder[1] = "b";
builder.Clear();
Assert.Throws(typeof(InvalidOperationException), () => builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Add(i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableInsertToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Insert(i, i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddRangeToCapcity()
{
var array = new[] { 1, 2, 3, 4, 5 };
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: array.Length);
builder.AddRange(array);
Assert.Equal(array, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddRemoveAddToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Add(i);
builder.RemoveAt(i);
builder.Add(i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void CapacitySetToZero()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Capacity = 0;
Assert.Equal(0, builder.Capacity);
Assert.Equal(new int[] { }, builder.ToArray());
}
[Fact]
public void CapacitySetToLessThanCount()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(1);
Assert.Throws(typeof(ArgumentException), () => builder.Capacity = 1);
}
[Fact]
public void CapacitySetToCount()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = builder.Count;
Assert.Equal(2, builder.Capacity);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void CapacitySetToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = builder.Capacity;
Assert.Equal(10, builder.Capacity);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void CapacitySetToBiggerCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = 20;
Assert.Equal(20, builder.Capacity);
Assert.Equal(2, builder.Count);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.CreateBuilder<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableArray.CreateBuilder<string>(4));
}
private static ImmutableArray<T>.Builder CreateBuilderWithCount<T>(int count)
{
var builder = ImmutableArray.CreateBuilder<T>(count);
builder.Count = count;
return builder;
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var builder = new ImmutableArray<T>.Builder(contents.Length);
builder.AddRange(contents);
return builder;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Gallio.Common.Collections;
using Gallio.Model;
using Gallio.Runner.Extensions;
using Gallio.Runner.Projects.Schema;
using Gallio.Runner.Reports;
namespace Gallio.Runner.Projects
{
/// <summary>
/// A test project consists of a test package with a list of test files, a list
/// of test extensions, and report options.
/// </summary>
public class TestProject
{
private TestPackage testPackage;
private string reportNameFormat;
private bool isReportNameFormatSpecified;
private string reportDirectory;
private readonly List<FilterInfo> testFilters;
private readonly List<ITestRunnerExtension> testRunnerExtensions;
private readonly List<string> testRunnerExtensionSpecifications;
private string testRunnerFactoryName;
private bool isTestRunnerFactoryNameSpecified;
/// <summary>
/// The default report name format.
/// </summary>
/// <value>"test-report-{0}-{1}"</value>
public static readonly string DefaultReportNameFormat = @"test-report-{0}-{1}";
/// <summary>
/// The default report directory relative path.
/// </summary>
/// <value>"Reports"</value>
public static readonly string DefaultReportDirectoryRelativePath = @"Reports";
/// <summary>
/// The default test runner factory name.
/// </summary>
/// <value><see cref="StandardTestRunnerFactoryNames.IsolatedProcess" /></value>
public static readonly string DefaultTestRunnerFactoryName = StandardTestRunnerFactoryNames.IsolatedProcess;
/// <summary>
/// The file extension for Gallio project files.
/// </summary>
/// <value>".gallio"</value>
public static readonly string Extension = ".gallio";
/// <summary>
/// Creates an empty test project.
/// </summary>
public TestProject()
{
testPackage = new TestPackage();
testFilters = new List<FilterInfo>();
testRunnerExtensions = new List<ITestRunnerExtension>();
testRunnerExtensionSpecifications = new List<string>();
reportNameFormat = DefaultReportNameFormat;
reportDirectory = DefaultReportDirectoryRelativePath;
testRunnerFactoryName = DefaultTestRunnerFactoryName;
ReportArchive = ReportArchive.Normal;
}
/// <summary>
/// Gets or sets the test package.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public TestPackage TestPackage
{
get
{
return testPackage;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
testPackage = value;
}
}
/// <summary>
/// Gets a read-only list of test filters.
/// </summary>
public IList<FilterInfo> TestFilters
{
get
{
return new ReadOnlyCollection<FilterInfo>(testFilters);
}
}
/// <summary>
/// Gets a read-only list of test runner extensions.
/// </summary>
public IList<ITestRunnerExtension> TestRunnerExtensions
{
get
{
return new ReadOnlyCollection<ITestRunnerExtension>(testRunnerExtensions);
}
}
/// <summary>
/// Gets a read-only list of test runner extension specifications.
/// </summary>
/// <seealso cref="TestRunnerExtensionUtils.CreateExtensionFromSpecification"/>
/// for an explanation of the specification syntax.
public IList<string> TestRunnerExtensionSpecifications
{
get
{
return new ReadOnlyCollection<string>(testRunnerExtensionSpecifications);
}
}
/// <summary>
/// Gets or sets the name of a <see cref="ITestRunnerFactory" /> to use for constructing
/// the <see cref="ITestRunner" /> at test execution time.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <see cref="StandardTestRunnerFactoryNames.IsolatedProcess"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public string TestRunnerFactoryName
{
get
{
return testRunnerFactoryName;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
testRunnerFactoryName = value;
isTestRunnerFactoryNameSpecified = true;
}
}
/// <summary>
/// Returns true if <see cref="TestRunnerFactoryName" /> has been set explicitly.
/// </summary>
public bool IsTestRunnerFactoryNameSpecified
{
get
{
return isTestRunnerFactoryNameSpecified;
}
}
/// <summary>
/// Gets or sets the folder to save generated reports to.
/// </summary>
/// <remarks>
/// <para>
/// Relative to project location, if not absolute.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public string ReportDirectory
{
get
{
return reportDirectory;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
reportDirectory = value;
IsReportDirectorySpecified = true;
}
}
/// <summary>
/// Returns true if <see cref="ReportDirectory" /> has been set explicitly.
/// </summary>
public bool IsReportDirectorySpecified
{
get;
private set;
}
/// <summary>
/// The format for the filename of generated reports.
/// </summary>
/// <remarks>
/// <para>
/// Within the format string, <c>{0}</c> is replaced by the date and <c>{1}</c> by the time.
/// </para>
/// <para>
/// The default value is <c>"test-report-{0}-{1}"</c>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public string ReportNameFormat
{
get
{
return reportNameFormat;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
reportNameFormat = value;
isReportNameFormatSpecified = true;
}
}
/// <summary>
/// Gets or sets a value indicating whether the resulting reports must be enclosed
/// in a compressed archive file (zip).
/// </summary>
public ReportArchive ReportArchive
{
get;
set;
}
/// <summary>
/// Returns true if <see cref="ReportNameFormat" /> has been set explicitly.
/// </summary>
public bool IsReportNameFormatSpecified
{
get
{
return isReportNameFormatSpecified;
}
}
/// <summary>
/// Resets <see cref="TestRunnerFactoryName"/> to its default value and sets <see cref="IsTestRunnerFactoryNameSpecified" /> to false.
/// </summary>
public void ResetTestRunnerFactoryName()
{
testRunnerFactoryName = DefaultTestRunnerFactoryName;
isTestRunnerFactoryNameSpecified = false;
}
/// <summary>
/// Resets <see cref="ReportDirectory"/> to its default value and sets <see cref="IsReportDirectorySpecified" /> to false.
/// </summary>
public void ResetReportDirectory()
{
reportDirectory = DefaultReportDirectoryRelativePath;
IsReportDirectorySpecified = false;
}
/// <summary>
/// Resets <see cref="ReportNameFormat"/> to its default value and sets <see cref="IsReportNameFormatSpecified" /> to false.
/// </summary>
public void ResetReportNameFormat()
{
reportNameFormat = DefaultReportNameFormat;
isReportNameFormatSpecified = false;
}
/// <summary>
/// Clears the list of test filters.
/// </summary>
public void ClearTestFilters()
{
testFilters.Clear();
}
/// <summary>
/// Adds a test filter if not already added.
/// </summary>
/// <param name="filter">The filter to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="filter"/> is null.</exception>
public void AddTestFilter(FilterInfo filter)
{
if (filter == null)
throw new ArgumentNullException("filter");
filter.Validate();
if (!testFilters.Contains(filter))
testFilters.Add(filter);
}
/// <summary>
/// Removes a test filter.
/// </summary>
/// <param name="filter">The filter to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="filter"/> is null.</exception>
public void RemoveTestFilter(FilterInfo filter)
{
if (filter == null)
throw new ArgumentNullException("filter");
testFilters.Remove(filter);
}
/// <summary>
/// Clears the list of test runner extensions.
/// </summary>
public void ClearTestRunnerExtensions()
{
testRunnerExtensions.Clear();
}
/// <summary>
/// Adds a test runner extension if not already added.
/// </summary>
/// <param name="extension">The test runner extension to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="extension"/> is null.</exception>
public void AddTestRunnerExtension(ITestRunnerExtension extension)
{
if (extension == null)
throw new ArgumentNullException("extension");
if (!testRunnerExtensions.Contains(extension))
testRunnerExtensions.Add(extension);
}
/// <summary>
/// Removes a test runner extension.
/// </summary>
/// <param name="extension">The test runner extension to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="extension"/> is null.</exception>
public void RemoveTestRunnerExtension(ITestRunnerExtension extension)
{
if (extension == null)
throw new ArgumentNullException("extension");
testRunnerExtensions.Remove(extension);
}
/// <summary>
/// Clears the list of test runner extension specifications.
/// </summary>
public void ClearTestRunnerExtensionSpecifications()
{
testRunnerExtensionSpecifications.Clear();
}
/// <summary>
/// Adds a test runner extension specification if not already added.
/// </summary>
/// <param name="extensionSpecification">The test runner extension specification to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="extensionSpecification"/> is null.</exception>
/// <seealso cref="TestRunnerExtensionUtils.CreateExtensionFromSpecification"/>
/// for an explanation of the specification syntax.
public void AddTestRunnerExtensionSpecification(string extensionSpecification)
{
if (extensionSpecification == null)
throw new ArgumentNullException("extensionSpecification");
if (!testRunnerExtensionSpecifications.Contains(extensionSpecification))
testRunnerExtensionSpecifications.Add(extensionSpecification);
}
/// <summary>
/// Removes a test runner extension specification.
/// </summary>
/// <param name="extensionSpecification">The test runner extension specification to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="extensionSpecification"/> is null.</exception>
/// <seealso cref="TestRunnerExtensionUtils.CreateExtensionFromSpecification"/>
/// for an explanation of the specification syntax.
public void RemoveTestRunnerExtensionSpecification(string extensionSpecification)
{
if (extensionSpecification == null)
throw new ArgumentNullException("extensionSpecification");
testRunnerExtensionSpecifications.Remove(extensionSpecification);
}
/// <summary>
/// Creates a copy of the test project.
/// </summary>
/// <returns>The new copy.</returns>
public TestProject Copy()
{
var copy = new TestProject()
{
testRunnerFactoryName = testRunnerFactoryName,
isTestRunnerFactoryNameSpecified = isTestRunnerFactoryNameSpecified,
reportDirectory = reportDirectory,
IsReportDirectorySpecified = IsReportDirectorySpecified,
reportNameFormat = reportNameFormat,
isReportNameFormatSpecified = isReportNameFormatSpecified,
testPackage = testPackage.Copy(),
ReportArchive = ReportArchive
};
GenericCollectionUtils.ConvertAndAddAll(testFilters, copy.testFilters, x => x.Copy());
copy.testRunnerExtensions.AddRange(testRunnerExtensions);
copy.testRunnerExtensionSpecifications.AddRange(testRunnerExtensionSpecifications);
return copy;
}
/// <summary>
/// Applies the settings of another test project as an overlay on top of this one.
/// </summary>
/// <remarks>
/// <para>
/// Overrides scalar settings (such as <see cref="ReportNameFormat"/>) with those of
/// the overlay when they are specified (such as when <see cref="IsReportNameFormatSpecified" /> is true).
/// Merges aggregate settings (such as lists of files).
/// </para>
/// </remarks>
/// <param name="overlay">The test project to overlay on top of this one.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="overlay"/> is null.</exception>
public void ApplyOverlay(TestProject overlay)
{
if (overlay == null)
throw new ArgumentNullException("overlay");
if (overlay.IsReportNameFormatSpecified)
ReportNameFormat = overlay.ReportNameFormat;
if (overlay.IsReportDirectorySpecified)
ReportDirectory = overlay.ReportDirectory;
if (overlay.IsTestRunnerFactoryNameSpecified)
TestRunnerFactoryName = overlay.TestRunnerFactoryName;
GenericCollectionUtils.ForEach(overlay.TestFilters, x => AddTestFilter(x.Copy()));
GenericCollectionUtils.ForEach(overlay.TestRunnerExtensions, AddTestRunnerExtension);
GenericCollectionUtils.ForEach(overlay.TestRunnerExtensionSpecifications, AddTestRunnerExtensionSpecification);
TestPackage.ApplyOverlay(overlay.TestPackage);
}
}
}
| |
#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;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization.Formatters;
using PlayFab.Json.Serialization;
using System.Runtime.Serialization;
namespace PlayFab.Json
{
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer"/> object.
/// </summary>
public class JsonSerializerSettings
{
internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;
internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;
internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;
internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;
internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;
internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;
internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;
internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;
internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple;
internal static readonly StreamingContext DefaultContext;
internal const Formatting DefaultFormatting = Formatting.None;
internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;
internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;
internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;
internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;
internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;
internal const FormatterAssemblyStyle DefaultFormatterAssemblyStyle = FormatterAssemblyStyle.Simple;
internal static readonly CultureInfo DefaultCulture;
internal const bool DefaultCheckAdditionalContent = false;
internal const string DefaultDateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
internal Formatting? _formatting;
internal DateFormatHandling? _dateFormatHandling;
internal DateTimeZoneHandling? _dateTimeZoneHandling;
internal DateParseHandling? _dateParseHandling;
internal FloatFormatHandling? _floatFormatHandling;
internal FloatParseHandling? _floatParseHandling;
internal StringEscapeHandling? _stringEscapeHandling;
internal CultureInfo _culture;
internal bool? _checkAdditionalContent;
internal int? _maxDepth;
internal bool _maxDepthSet;
internal string _dateFormatString;
internal bool _dateFormatStringSet;
internal FormatterAssemblyStyle? _typeNameAssemblyFormat;
internal DefaultValueHandling? _defaultValueHandling;
internal PreserveReferencesHandling? _preserveReferencesHandling;
internal NullValueHandling? _nullValueHandling;
internal ObjectCreationHandling? _objectCreationHandling;
internal MissingMemberHandling? _missingMemberHandling;
internal ReferenceLoopHandling? _referenceLoopHandling;
internal StreamingContext? _context;
internal ConstructorHandling? _constructorHandling;
internal TypeNameHandling? _typeNameHandling;
/// <summary>
/// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
/// <value>Reference loop handling.</value>
public ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling ?? DefaultReferenceLoopHandling; }
set { _referenceLoopHandling = value; }
}
/// <summary>
/// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
/// <value>Missing member handling.</value>
public MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling ?? DefaultMissingMemberHandling; }
set { _missingMemberHandling = value; }
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling ?? DefaultObjectCreationHandling; }
set { _objectCreationHandling = value; }
}
/// <summary>
/// Gets or sets how null values are handled during serialization and deserialization.
/// </summary>
/// <value>Null value handling.</value>
public NullValueHandling NullValueHandling
{
get { return _nullValueHandling ?? DefaultNullValueHandling; }
set { _nullValueHandling = value; }
}
/// <summary>
/// Gets or sets how null default are handled during serialization and deserialization.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling ?? DefaultDefaultValueHandling; }
set { _defaultValueHandling = value; }
}
/// <summary>
/// Gets or sets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>The converters.</value>
public IList<JsonConverter> Converters { get; set; }
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
/// <value>The preserve references handling.</value>
public PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling ?? DefaultPreserveReferencesHandling; }
set { _preserveReferencesHandling = value; }
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling ?? DefaultTypeNameHandling; }
set { _typeNameHandling = value; }
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat ?? DefaultFormatterAssemblyStyle; }
set { _typeNameAssemblyFormat = value; }
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public ConstructorHandling ConstructorHandling
{
get { return _constructorHandling ?? DefaultConstructorHandling; }
set { _constructorHandling = value; }
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver { get; set; }
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
/// <value>The reference resolver.</value>
public IReferenceResolver ReferenceResolver { get; set; }
/// <summary>
/// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages.
/// </summary>
/// <value>The trace writer.</value>
public ITraceWriter TraceWriter { get; set; }
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
/// <value>The binder.</value>
public SerializationBinder Binder { get; set; }
/// <summary>
/// Gets or sets the error handler called during serialization and deserialization.
/// </summary>
/// <value>The error handler called during serialization and deserialization.</value>
public EventHandler<ErrorEventArgs> Error { get; set; }
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public StreamingContext Context
{
get { return _context ?? DefaultContext; }
set { _context = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString ?? DefaultDateFormatString; }
set
{
_dateFormatString = value;
_dateFormatStringSet = true;
}
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
_maxDepthSet = true;
}
}
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting ?? DefaultFormatting; }
set { _formatting = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling ?? DefaultDateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling ?? DefaultDateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling ?? DefaultDateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written as JSON.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling ?? DefaultFloatFormatHandling; }
set { _floatFormatHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling ?? DefaultFloatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling ?? DefaultStringEscapeHandling; }
set { _stringEscapeHandling = value; }
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? DefaultCulture; }
set { _culture = value; }
}
/// <summary>
/// Gets a value indicating whether there will be a check for additional content after deserializing an object.
/// </summary>
/// <value>
/// <c>true</c> if there will be a check for additional content after deserializing an object; otherwise, <c>false</c>.
/// </value>
public bool CheckAdditionalContent
{
get { return _checkAdditionalContent ?? DefaultCheckAdditionalContent; }
set { _checkAdditionalContent = value; }
}
static JsonSerializerSettings()
{
DefaultContext = new StreamingContext();
DefaultCulture = CultureInfo.InvariantCulture;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializerSettings"/> class.
/// </summary>
public JsonSerializerSettings()
{
Converters = new List<JsonConverter>();
}
}
}
#endif
| |
/*
* 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.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Statistics;
using OpenSim.Services.Interfaces;
namespace OpenSim.Framework.Communications.Services
{
public abstract class LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_welcomeMessage = "Welcome to OpenSim";
protected int m_minLoginLevel = 0;
protected UserManagerBase m_userManager = null;
protected Mutex m_loginMutex = new Mutex(false);
/// <summary>
/// Used during login to send the skeleton of the OpenSim Library to the client.
/// </summary>
protected LibraryRootFolder m_libraryRootFolder;
protected uint m_defaultHomeX;
protected uint m_defaultHomeY;
protected bool m_warn_already_logged = true;
/// <summary>
/// Used by the login service to make requests to the inventory service.
/// </summary>
protected IInterServiceInventoryServices m_interInventoryService;
// Hack
protected IInventoryService m_InventoryService;
public UserManagerBase UserManager { get { return m_userManager; } }
public LibraryRootFolder LibraryRootFolder { get { return m_libraryRootFolder; } }
public string WelcomeMessage { get { return m_welcomeMessage; } }
public IInterServiceInventoryServices InterInventoryService { get { return m_interInventoryService; } }
/// <summary>
/// Constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="libraryRootFolder"></param>
/// <param name="welcomeMess"></param>
public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder,
string welcomeMess)
{
m_userManager = userManager;
m_libraryRootFolder = libraryRootFolder;
if (welcomeMess != String.Empty)
{
m_welcomeMessage = welcomeMess;
}
}
/// <summary>
/// If the user is already logged in, try to notify the region that the user they've got is dead.
/// </summary>
/// <param name="theUser"></param>
public virtual void LogOffUser(UserProfileData theUser, string message)
{
}
/// <summary>
/// Called when we receive the client's initial XMLRPC login_to_simulator request message
/// </summary>
/// <param name="request">The XMLRPC request</param>
/// <returns>The response to send</returns>
public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
//CFK: CustomizeResponse contains sufficient strings to alleviate the need for this.
//CKF: m_log.Info("[LOGIN]: Attempting login now...");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
SniffLoginKey((Uri)request.Params[2], requestData);
bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") &&
(requestData.Contains("passwd") || requestData.Contains("web_login_key")));
string startLocationRequest = "last";
UserProfileData userProfile;
LoginResponse logResponse = new LoginResponse();
string firstname;
string lastname;
if (GoodXML)
{
if (requestData.Contains("start"))
{
startLocationRequest = (string)requestData["start"];
}
firstname = (string)requestData["first"];
lastname = (string)requestData["last"];
m_log.InfoFormat(
"[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'",
firstname, lastname);
string clientVersion = "Unknown";
if (requestData.Contains("version"))
{
clientVersion = (string)requestData["version"];
}
m_log.DebugFormat(
"[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest);
if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile))
{
return logResponse.CreateLoginFailedResponse();
}
}
else
{
m_log.Info(
"[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data");
return logResponse.CreateGridErrorResponse();
}
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponse();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
//TODO: The following statements can cause trouble:
// If agentOnline could not turn from true back to false normally
// because of some problem, for instance, the crashment of server or client,
// the user cannot log in any longer.
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in",
firstname, lastname);
return logResponse.CreateAlreadyLoggedInResponse();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: XMLRPC User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
firstname, lastname);
}
}
// Otherwise...
// Create a new agent session
// XXYY we don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}",
agentID, e);
// Let's not panic
if (!AllowLoginWithoutInventory())
return logResponse.CreateLoginInventoryFailedResponse();
}
if (inventData != null)
{
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
}
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = UUID.Zero.ToString(); //"00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
if (CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient))
{
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.",
firstname, lastname);
return logResponse.ToXmlRpcResponse();
}
else
{
m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname);
return logResponse.CreateDeadRegionResponse();
}
}
catch (Exception e)
{
m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e);
m_log.Error(e.StackTrace);
}
}
m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response");
return response;
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
protected virtual bool TryAuthenticateXmlRpcLogin(
XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile)
{
Hashtable requestData = (Hashtable)request.Params[0];
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Debug("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname);
return false;
}
else
{
if (requestData.Contains("passwd"))
{
string passwd = (string)requestData["passwd"];
bool authenticated = AuthenticateUser(userProfile, passwd);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed password authentication",
firstname, lastname);
return authenticated;
}
if (requestData.Contains("web_login_key"))
{
try
{
UUID webloginkey = new UUID((string)requestData["web_login_key"]);
bool authenticated = AuthenticateUser(userProfile, webloginkey);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed web login key authentication",
firstname, lastname);
return authenticated;
}
catch (Exception e)
{
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}",
requestData["web_login_key"], firstname, lastname, e);
return false;
}
}
m_log.DebugFormat(
"[LOGIN END]: XMLRPC login request for {0} {1} contained neither a password nor a web login key",
firstname, lastname);
}
return false;
}
protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile)
{
bool GoodLogin = false;
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname);
return false;
}
GoodLogin = AuthenticateUser(userProfile, passwd);
return GoodLogin;
}
/// <summary>
/// Called when we receive the client's initial LLSD login_to_simulator request message
/// </summary>
/// <param name="request">The LLSD request</param>
/// <returns>The response to send</returns>
public OSD LLSDLoginMethod(OSD request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
// bool GoodLogin = false;
string startLocationRequest = "last";
UserProfileData userProfile = null;
LoginResponse logResponse = new LoginResponse();
if (request.Type == OSDType.Map)
{
OSDMap map = (OSDMap)request;
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{
string firstname = map["first"].AsString();
string lastname = map["last"].AsString();
string passwd = map["passwd"].AsString();
if (map.ContainsKey("start"))
{
m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString());
startLocationRequest = map["start"].AsString();
}
m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd);
if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile))
{
return logResponse.CreateLoginFailedResponseLLSD();
}
}
else
return logResponse.CreateLoginFailedResponseLLSD();
}
else
return logResponse.CreateLoginFailedResponseLLSD();
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponseLLSD();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in",
userProfile.FirstName, userProfile.SurName);
userProfile.CurrentAgent = null;
return logResponse.CreateAlreadyLoggedInResponseLLSD();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: LLSD User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
userProfile.FirstName, userProfile.SurName);
}
}
// Otherwise...
// Create a new agent session
// XXYY We don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
//InventoryData inventData = GetInventorySkeleton(agentID);
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}",
agentID, e.GetType(), e.Message);
return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD ();
}
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = (Int32)Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
try
{
CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient);
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateDeadRegionResponseLLSD();
}
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.",
userProfile.FirstName, userProfile.SurName);
return logResponse.ToLLSDResponse();
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateFailedResponseLLSD();
}
}
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
public Hashtable ProcessHTMLLogin(Hashtable keysvals)
{
// Matches all unspecified characters
// Currently specified,; lowercase letters, upper case letters, numbers, underline
// period, space, parens, and dash.
Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]");
Hashtable returnactions = new Hashtable();
int statuscode = 200;
string firstname = String.Empty;
string lastname = String.Empty;
string location = String.Empty;
string region = String.Empty;
string grid = String.Empty;
string channel = String.Empty;
string version = String.Empty;
string lang = String.Empty;
string password = String.Empty;
string errormessages = String.Empty;
// the client requires the HTML form field be named 'username'
// however, the data it sends when it loads the first time is 'firstname'
// another one of those little nuances.
if (keysvals.Contains("firstname"))
firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999);
if (keysvals.Contains("username"))
firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999);
if (keysvals.Contains("lastname"))
lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999);
if (keysvals.Contains("location"))
location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999);
if (keysvals.Contains("region"))
region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999);
if (keysvals.Contains("grid"))
grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999);
if (keysvals.Contains("channel"))
channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999);
if (keysvals.Contains("version"))
version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999);
if (keysvals.Contains("lang"))
lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999);
if (keysvals.Contains("password"))
password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999);
// load our login form.
string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
if (keysvals.ContainsKey("show_login_form"))
{
UserProfileData user = GetTheUser(firstname, lastname);
bool goodweblogin = false;
if (user != null)
goodweblogin = AuthenticateUser(user, password);
if (goodweblogin)
{
UUID webloginkey = UUID.Random();
m_userManager.StoreWebLoginKey(user.ID, webloginkey);
//statuscode = 301;
// string redirectURL = "about:blank?redirect-http-hack=" +
// HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" +
// lastname +
// "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString());
//m_log.Info("[WEB]: R:" + redirectURL);
returnactions["int_response_code"] = statuscode;
//returnactions["str_redirect_location"] = redirectURL;
//returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>";
returnactions["str_response_string"] = webloginkey.ToString();
}
else
{
errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again";
loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
}
else
{
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
return returnactions;
}
public string GetLoginForm(string firstname, string lastname, string location, string region,
string grid, string channel, string version, string lang,
string password, string errormessages)
{
// inject our values in the form at the markers
string loginform = String.Empty;
string file = Path.Combine(Util.configDir(), "http_loginform.html");
if (!File.Exists(file))
{
loginform = GetDefaultLoginForm();
}
else
{
StreamReader sr = File.OpenText(file);
loginform = sr.ReadToEnd();
sr.Close();
}
loginform = loginform.Replace("[$firstname]", firstname);
loginform = loginform.Replace("[$lastname]", lastname);
loginform = loginform.Replace("[$location]", location);
loginform = loginform.Replace("[$region]", region);
loginform = loginform.Replace("[$grid]", grid);
loginform = loginform.Replace("[$channel]", channel);
loginform = loginform.Replace("[$version]", version);
loginform = loginform.Replace("[$lang]", lang);
loginform = loginform.Replace("[$password]", password);
loginform = loginform.Replace("[$errors]", errormessages);
return loginform;
}
public string GetDefaultLoginForm()
{
string responseString =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
responseString += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
responseString += "<head>";
responseString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
responseString += "<meta http-equiv=\"cache-control\" content=\"no-cache\">";
responseString += "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
responseString += "<title>OpenSim Login</title>";
responseString += "<body><br />";
responseString += "<div id=\"login_box\">";
responseString += "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">";
responseString += "<div id=\"message\">[$errors]</div>";
responseString += "<fieldset id=\"firstname\">";
responseString += "<legend>First Name:</legend>";
responseString += "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"lastname\">";
responseString += "<legend>Last Name:</legend>";
responseString += "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"password\">";
responseString += "<legend>Password:</legend>";
responseString += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
responseString += "<tr>";
responseString += "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>";
responseString += "</tr>";
responseString += "<tr>";
responseString += "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>";
responseString += "<td><label for=\"remember_password\">Remember password</label></td>";
responseString += "</tr>";
responseString += "</table>";
responseString += "</fieldset>";
responseString += "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />";
responseString += "<input type=\"hidden\" name=\"method\" value=\"login\" />";
responseString += "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />";
responseString += "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />";
responseString += "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />";
responseString += "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />";
responseString += "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />";
responseString += "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />";
responseString += "<div id=\"submitbtn\">";
responseString += "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />";
responseString += "</div>";
responseString += "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>";
responseString += "<div id=\"helplinks\"><!---";
responseString += "<a href=\"#join now link\" target=\"_blank\"></a> | ";
responseString += "<a href=\"#forgot password link\" target=\"_blank\"></a>";
responseString += "---></div>";
responseString += "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>";
responseString += "</form>";
responseString += "<script language=\"JavaScript\">";
responseString += "document.getElementById('firstname_input').focus();";
responseString += "</script>";
responseString += "</div>";
responseString += "</div>";
responseString += "</body>";
responseString += "</html>";
return responseString;
}
/// <summary>
/// Saves a target agent to the database
/// </summary>
/// <param name="profile">The users profile</param>
/// <returns>Successful?</returns>
public bool CommitAgent(ref UserProfileData profile)
{
return m_userManager.CommitAgent(ref profile);
}
/// <summary>
/// Checks a user against it's password hash
/// </summary>
/// <param name="profile">The users profile</param>
/// <param name="password">The supplied password</param>
/// <returns>Authenticated?</returns>
public virtual bool AuthenticateUser(UserProfileData profile, string password)
{
bool passwordSuccess = false;
//m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Web Login method seems to also occasionally send the hashed password itself
// we do this to get our hash in a form that the server password code can consume
// when the web-login-form submits the password in the clear (supposed to be over SSL!)
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
// Testing...
//m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
//m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return passwordSuccess;
}
public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey)
{
bool passwordSuccess = false;
m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Match web login key unless it's the default weblogin key UUID.Zero
passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero);
return passwordSuccess;
}
/// <summary>
///
/// </summary>
/// <param name="profile"></param>
/// <param name="request"></param>
public void CreateAgent(UserProfileData profile, XmlRpcRequest request)
{
m_userManager.CreateAgent(profile, request);
}
public void CreateAgent(UserProfileData profile, OSD request)
{
m_userManager.CreateAgent(profile, request);
}
/// <summary>
///
/// </summary>
/// <param name="firstname"></param>
/// <param name="lastname"></param>
/// <returns></returns>
public virtual UserProfileData GetTheUser(string firstname, string lastname)
{
return m_userManager.GetUserProfile(firstname, lastname);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual string GetMessage()
{
return m_welcomeMessage;
}
private static LoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL)
{
LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList();
foreach (FriendListItem fl in LFL)
{
LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend);
buddyitem.BuddyID = fl.Friend;
buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms;
buddyitem.BuddyRightsGiven = (int)fl.FriendPerms;
buddylistreturn.AddNewBuddy(buddyitem);
}
return buddylistreturn;
}
/// <summary>
/// Converts the inventory library skeleton into the form required by the rpc request.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetInventoryLibrary()
{
return null;
Dictionary<UUID, InventoryFolderImpl> rootFolders
= m_libraryRootFolder.RequestSelfAndDescendentFolders();
ArrayList folderHashes = new ArrayList();
foreach (InventoryFolderBase folder in rootFolders.Values)
{
Hashtable TempHash = new Hashtable();
TempHash["name"] = folder.Name;
TempHash["parent_id"] = folder.ParentID.ToString();
TempHash["version"] = (Int32)folder.Version;
TempHash["type_default"] = (Int32)folder.Type;
TempHash["folder_id"] = folder.ID.ToString();
folderHashes.Add(TempHash);
}
return folderHashes;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetLibraryOwner()
{
//for now create random inventory library owner
Hashtable TempHash = new Hashtable();
TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000";
ArrayList inventoryLibOwner = new ArrayList();
inventoryLibOwner.Add(TempHash);
return inventoryLibOwner;
}
public class InventoryData
{
public ArrayList InventoryArray = null;
public UUID RootFolderID = UUID.Zero;
public InventoryData(ArrayList invList, UUID rootID)
{
InventoryArray = invList;
RootFolderID = rootID;
}
}
protected void SniffLoginKey(Uri uri, Hashtable requestData)
{
string uri_str = uri.ToString();
string[] parts = uri_str.Split(new char[] { '=' });
if (parts.Length > 1)
{
string web_login_key = parts[1];
requestData.Add("web_login_key", web_login_key);
m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key);
}
}
/// <summary>
/// Customises the login response and fills in missing values. This method also tells the login region to
/// expect a client connection.
/// </summary>
/// <param name="response">The existing response</param>
/// <param name="theUser">The user profile</param>
/// <param name="startLocationRequest">The requested start location</param>
/// <returns>true on success, false if the region was not successfully told to expect a user connection</returns>
public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, IPEndPoint client)
{
// add active gestures to login-response
AddActiveGestures(response, theUser);
// HomeLocation
RegionInfo homeInfo = null;
// use the homeRegionID if it is stored already. If not, use the regionHandle as before
UUID homeRegionId = theUser.HomeRegionID;
ulong homeRegionHandle = theUser.HomeRegion;
if (homeRegionId != UUID.Zero)
{
homeInfo = GetRegionInfo(homeRegionId);
}
else
{
homeInfo = GetRegionInfo(homeRegionHandle);
}
if (homeInfo != null)
{
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
(homeInfo.RegionLocX * Constants.RegionSize),
(homeInfo.RegionLocY * Constants.RegionSize),
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
}
else
{
m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY);
// Emergency mode: Home-region isn't available, so we can't request the region info.
// Use the stored home regionHandle instead.
// NOTE: If the home-region moves, this will be wrong until the users update their user-profile again
ulong regionX = homeRegionHandle >> 32;
ulong regionY = homeRegionHandle & 0xffffffff;
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
regionX, regionY,
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}",
theUser.FirstName, theUser.SurName,
regionX, regionY);
}
// StartLocation
RegionInfo regionInfo = null;
if (startLocationRequest == "home")
{
regionInfo = homeInfo;
theUser.CurrentAgent.Position = theUser.HomeLocation;
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(),
theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString());
}
else if (startLocationRequest == "last")
{
UUID lastRegion = theUser.CurrentAgent.Region;
regionInfo = GetRegionInfo(lastRegion);
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(),
theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString());
}
else
{
Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
Match uriMatch = reURI.Match(startLocationRequest);
if (uriMatch == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest);
}
else
{
string region = uriMatch.Groups["region"].ToString();
regionInfo = RequestClosestRegion(region);
if (regionInfo == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region);
}
else
{
theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));
}
}
response.LookAt = "[r0,r1,r0]";
// can be: last, home, safe, url
response.StartLocation = "url";
}
if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, client)))
{
return true;
}
// Get the default region handle
ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize);
// If we haven't already tried the default region, reset regionInfo
if (regionInfo != null && defaultHandle != regionInfo.RegionHandle)
regionInfo = null;
if (regionInfo == null)
{
m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
regionInfo = GetRegionInfo(defaultHandle);
}
if (regionInfo == null)
{
m_log.ErrorFormat("[LOGIN]: Sending user to any region");
regionInfo = RequestClosestRegion(String.Empty);
}
theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f);
response.StartLocation = "safe";
return PrepareLoginToRegion(regionInfo, theUser, response, client);
}
protected abstract RegionInfo RequestClosestRegion(string region);
protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle);
protected abstract RegionInfo GetRegionInfo(UUID homeRegionId);
/// <summary>
/// Prepare a login to the given region. This involves both telling the region to expect a connection
/// and appropriately customising the response to the user.
/// </summary>
/// <param name="sim"></param>
/// <param name="user"></param>
/// <param name="response"></param>
/// <param name="remoteClient"></param>
/// <returns>true if the region was successfully contacted, false otherwise</returns>
protected abstract bool PrepareLoginToRegion(
RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint client);
/// <summary>
/// Add active gestures of the user to the login response.
/// </summary>
/// <param name="response">
/// A <see cref="LoginResponse"/>
/// </param>
/// <param name="theUser">
/// A <see cref="UserProfileData"/>
/// </param>
protected void AddActiveGestures(LoginResponse response, UserProfileData theUser)
{
List<InventoryItemBase> gestures = null;
try
{
if (m_InventoryService != null)
gestures = m_InventoryService.GetActiveGestures(theUser.ID);
else
gestures = m_interInventoryService.GetActiveGestures(theUser.ID);
}
catch (Exception e)
{
m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message);
}
//m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count);
ArrayList list = new ArrayList();
if (gestures != null)
{
foreach (InventoryItemBase gesture in gestures)
{
Hashtable item = new Hashtable();
item["item_id"] = gesture.ID.ToString();
item["asset_id"] = gesture.AssetID.ToString();
list.Add(item);
}
}
response.ActiveGestures = list;
}
/// <summary>
/// Get the initial login inventory skeleton (in other words, the folder structure) for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
/// <exception cref='System.Exception'>This will be thrown if there is a problem with the inventory service</exception>
protected InventoryData GetInventorySkeleton(UUID userID)
{
List<InventoryFolderBase> folders = null;
if (m_InventoryService != null)
{
folders = m_InventoryService.GetInventorySkeleton(userID);
}
else
{
folders = m_interInventoryService.GetInventorySkeleton(userID);
}
// If we have user auth but no inventory folders for some reason, create a new set of folders.
if (folders == null || folders.Count == 0)
{
m_log.InfoFormat(
"[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID);
// Although the create user function creates a new agent inventory along with a new user profile, some
// tools are creating the user profile directly in the database without creating the inventory. At
// this time we'll accomodate them by lazily creating the user inventory now if it doesn't already
// exist.
if (m_interInventoryService != null)
{
if (!m_interInventoryService.CreateNewUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
}
else if ((m_InventoryService != null) && !m_InventoryService.CreateUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID);
if (m_InventoryService != null)
folders = m_InventoryService.GetInventorySkeleton(userID);
else
folders = m_interInventoryService.GetInventorySkeleton(userID);
if (folders == null || folders.Count == 0)
{
throw new Exception(
String.Format(
"A root inventory folder for user {0} could not be retrieved from the inventory service",
userID));
}
}
UUID rootID = UUID.Zero;
ArrayList AgentInventoryArray = new ArrayList();
Hashtable TempHash;
foreach (InventoryFolderBase InvFolder in folders)
{
if (InvFolder.ParentID == UUID.Zero)
{
rootID = InvFolder.ID;
}
TempHash = new Hashtable();
TempHash["name"] = InvFolder.Name;
TempHash["parent_id"] = InvFolder.ParentID.ToString();
TempHash["version"] = (Int32)InvFolder.Version;
TempHash["type_default"] = (Int32)InvFolder.Type;
TempHash["folder_id"] = InvFolder.ID.ToString();
AgentInventoryArray.Add(TempHash);
}
return new InventoryData(AgentInventoryArray, rootID);
}
protected virtual bool AllowLoginWithoutInventory()
{
return false;
}
public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
string authed = "FALSE";
if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id"))
{
UUID guess_aid;
UUID guess_sid;
UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid);
if (guess_aid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
UUID.TryParse((string)requestData["session_id"], out guess_sid);
if (guess_sid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
if (m_userManager.VerifySession(guess_aid, guess_sid))
{
authed = "TRUE";
m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid);
}
else
{
m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE");
return Util.CreateUnknownUserErrorResponse();
}
}
Hashtable responseData = new Hashtable();
responseData["auth_session"] = authed;
response.Value = responseData;
return response;
}
}
}
| |
/*
* Copyright 2016 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Firebase.Platform;
using Firebase.Database.Internal;
namespace Firebase.Database {
/// <summary>The entry point for accessing a Firebase Database.</summary>
/// <remarks>
/// The entry point for accessing a Firebase Database. You can get an instance by calling
/// <see cref="DefaultInstance" />
/// . To access a location in the database and read or
/// write data, use
/// <see cref="GetReference()" />
/// </remarks>
public sealed class FirebaseDatabase {
private const string SFirebaseSdkVersion = "1.0.0.0";
private const string SDefaultName = "__DEFAULT__";
private InternalFirebaseDatabase internalDatabase;
// Name of this instance in the databases dictionary.
private string name;
internal FirebaseDatabase(FirebaseApp app, InternalFirebaseDatabase internalDB) {
App = app;
internalDatabase = internalDB;
App.AppDisposed += OnAppDisposed;
}
// Dispose of this object.
private static void DisposeObject(object objectToDispose) {
((FirebaseDatabase)objectToDispose).Dispose();
}
~FirebaseDatabase() {
Dispose();
}
void OnAppDisposed(object sender, System.EventArgs eventArgs) {
Dispose();
}
// Destroy the proxy to the C++ Database object.
private void Dispose() {
System.GC.SuppressFinalize(this);
lock(this) {
if (internalDatabase == null) return;
lock(databases) {
databases.Remove(name);
}
App.AppDisposed -= OnAppDisposed;
App = null;
internalDatabase.Dispose();
internalDatabase = null;
}
}
/// <summary>
/// Returns the Firebase.FirebaseApp instance to which this FirebaseDatabase belongs.
/// </summary>
/// <returns>The Firebase.FirebaseApp instance to which this FirebaseDatabase belongs.</returns>
public FirebaseApp App { get; private set; }
/// <summary>Gets the instance of FirebaseDatabase for the default Firebase.App.</summary>
/// <value>A FirebaseDatabase instance.</value>
public static FirebaseDatabase DefaultInstance {
get {
FirebaseApp instance = FirebaseApp.DefaultInstance;
if (instance == null) {
// This *should* never happen.
throw new DatabaseException("FirebaseApp could not be initialized.");
}
return GetInstance(instance);
}
}
/// <summary>A static map FirebaseApp.name to FirebaseDatabase instance.</summary>
/// <remarks>
/// This prevents creating two different C# FirebaseDatabase instances for
/// the same underlying C++ instance. It uses weak references to avoid keeping
/// the FirebaseDatabase alive forever.
/// </remarks>
private static Dictionary<string, FirebaseDatabase> databases =
new Dictionary<string, FirebaseDatabase>();
/// <summary>Gets an instance of FirebaseDatabase for a specific Firebase.FirebaseApp.</summary>
/// <param name="app">The Firebase.FirebaseApp to get a FirebaseDatabase for.</param>
/// <returns>A FirebaseDatabase instance.</returns>
public static FirebaseDatabase GetInstance(FirebaseApp app) {
return GetInstance(app, Services.AppConfig.GetDatabaseUrl(app.AppPlatform));
}
// This returns a database instance that is currently live, or the default instance
// if there is no live instance.
// This is used for the GoOnline / GoOffline methods that are static in almost any
// Firebase SDK (including this one), except the C++ SDK.
// It's not ideal to use an arbitrary instance, but it should work.
internal static FirebaseDatabase AnyInstance {
get {
lock(databases) {
var e = databases.GetEnumerator();
while (e.MoveNext()) {
FirebaseDatabase db = e.Current.Value;
if (db != null) return db;
}
}
// no existing databases, try to create a default instance
return DefaultInstance;
}
}
/// <summary>Gets an instance of FirebaseDatabase for the specified URL.</summary>
/// <param name="url">The URL to the Firebase Database instance you want to access.</param>
/// <returns>A FirebaseDatabase instance.</returns>
public static FirebaseDatabase GetInstance(String url) {
FirebaseApp instance = FirebaseApp.DefaultInstance;
if (instance == null) {
// This *should* never happen.
throw new DatabaseException("FirebaseApp could not be initialized.");
}
return GetInstance(instance, url);
}
/// <summary>Gets a FirebaseDatabase instance for the specified URL, using the specified
/// FirebsaeApp.</summary>
/// <param name="app">The Firebase.FirebaseApp to get a FirebaseDatabase for.</param>
/// <param name="url">The URL to the Firebase Database instance you want to access.</param>
/// <returns>A FirebaseDatabase instance.</returns>
public static FirebaseDatabase GetInstance(FirebaseApp app, String url) {
if (String.IsNullOrEmpty(url)) {
throw new DatabaseException(
"Failed to get FirebaseDatabase instance: Specify DatabaseURL within "
+ "FirebaseApp or from your GetInstance() call.");
}
FirebaseDatabase db = null;
string name = String.Format("({0}, {1})", app.Name, url);
lock (databases) {
if (!databases.TryGetValue(name, out db)) {
InitResult initResult;
var internalDB = InternalFirebaseDatabase.GetInstanceInternal(app, url, out initResult);
if (internalDB == null || initResult != InitResult.Success) {
throw new DatabaseException("Failed to get FirebaseDatabase instance. "
+ "Please check the log for more information.");
}
db = new FirebaseDatabase(app, internalDB);
db.name = name;
databases[name] = db;
}
}
return db;
}
/// <summary>Gets a DatabaseReference for the root location of this FirebaseDatabase.</summary>
/// <value>A DatabaseReference instance.</value>
public DatabaseReference RootReference {
get { return new DatabaseReference(internalDatabase.GetReference(), this); }
}
/// <summary>Gets a DatabaseReference for the provided path.</summary>
/// <param name="path">Path to a location in your FirebaseDatabase.</param>
/// <returns>A DatabaseReference pointing to the specified path.</returns>
public DatabaseReference GetReference(string path) {
return new DatabaseReference(internalDatabase.GetReference(path), this);
}
/// <summary>Gets a DatabaseReference for the provided URL.</summary>
/// <remarks>
/// Gets a DatabaseReference for the provided URL. The URL must be a URL to a path
/// within this FirebaseDatabase. To create a DatabaseReference to a different database,
/// create a
/// <see cref="Firebase.FirebaseApp" />
/// with a
/// <see>
/// <cref>Firebase.FirebaseOptions</cref>
/// </see>
/// object configured with
/// the appropriate database URL.
/// </remarks>
/// <param name="url">A URL to a path within your database.</param>
/// <returns>A DatabaseReference for the provided URL.</returns>
public DatabaseReference GetReferenceFromUrl(Uri url) {
return GetReferenceFromUrl(url.ToString());
}
/// <summary>Gets a DatabaseReference for the provided URL.</summary>
/// <remarks>
/// Gets a DatabaseReference for the provided URL. The URL must be a URL to a path
/// within this FirebaseDatabase. To create a DatabaseReference to a different database,
/// create a
/// <see cref="Firebase.FirebaseApp" />
/// with a
/// <see>
/// <cref>Firebase.FirebaseOptions</cref>
/// </see>
/// object configured with
/// the appropriate database URL.
/// </remarks>
/// <param name="url">A URL to a path within your database.</param>
/// <returns>A DatabaseReference for the provided URL.</returns>
public DatabaseReference GetReferenceFromUrl(string url) {
return new DatabaseReference(internalDatabase.GetReferenceFromUrl(url), this);
}
/// <summary>
/// The Firebase Database client automatically queues writes and sends them to the server at
/// the earliest opportunity, depending on network connectivity.
/// </summary>
/// <remarks>
/// The Firebase Database client automatically queues writes and sends them to the server at
/// the earliest opportunity, depending on network connectivity. In some cases (e.g.
/// offline usage) there may be a large number of writes waiting to be sent. Calling this
/// method will purge all outstanding writes so they are abandoned.
/// All writes will be purged, including transactions and
/// <see cref="DatabaseReference.OnDisconnect()" />
/// writes. The writes will
/// be rolled back locally, perhaps triggering events for affected event listeners, and the
/// client will not (re-)send them to the Firebase backend.
/// </remarks>
public void PurgeOutstandingWrites() {
internalDatabase.PurgeOutstandingWrites();
}
/// <summary>
/// Resumes our connection to the Firebase Database backend after a previous
/// <see cref="GoOffline()" />
/// Call.
/// </summary>
public void GoOnline() {
internalDatabase.GoOnline();
}
/// <summary>
/// Shuts down our connection to the Firebase Database backend until
/// <see cref="GoOnline()" />
/// is called.
/// </summary>
public void GoOffline() {
internalDatabase.GoOffline();
}
/// <summary>
/// Sets whether pending write data will persist between application exits.
/// </summary>
/// <remarks>
/// The Firebase Database client will cache synchronized data and keep track of all writes
/// you've initiated while your application is running. It seamlessly handles intermittent
/// network connections and re-sends write operations when the network connection is restored.
/// However by default your write operations and cached data are only stored in-memory and will
/// be lost when your app restarts. By setting this value to true, the data will be persisted to
/// on-device (disk) storage and will thus be available again when the app is restarted (even
/// when there is no network connectivity at that time).
///
/// Note:SetPersistenceEnabled should be called before creating any instances of
/// DatabaseReference, and only needs to be called once per application.
/// </remarks>
/// <param name="enabled">
/// Set this to true to persist write data to on-device (disk) storage, or false to discard
/// pending writes when the app exists.
/// </param>
public void SetPersistenceEnabled(bool enabled) {
internalDatabase.set_persistence_enabled(enabled);
}
/// <summary>
/// By default, this is set to
/// <see cref="Firebase.LogLevel.Info">Info</see>
/// .
/// This includes any internal errors (
/// <see cref="Firebase.LogLevel.Error">Error</see>
/// )
/// and any security debug messages (
/// <see cref="Firebase.LogLevel.Info">Info</see>
/// )
/// that the client receives. Set to
/// <see cref="Firebase.LogLevel.Debug">Debug</see>
/// to turn on the diagnostic logging.
/// </summary>
/// <remarks>
/// On Android this can only be set before any operations have been performed with the object.
/// </remarks>
/// <value>The desired minimum log level</value>
public LogLevel LogLevel {
get { return internalDatabase.log_level(); }
set {
internalDatabase.set_log_level(value);
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Statements
{
using System.Activities;
using System.Activities.Tracking;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Transactions;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Tracking;
using System.Runtime;
using System.Globalization;
class InteropEnvironment : IDisposable, IServiceProvider
{
static readonly ReadOnlyCollection<IComparable> emptyList = new ReadOnlyCollection<IComparable>(new IComparable[] { });
static MethodInfo getServiceMethod = typeof(NativeActivityContext).GetMethod("GetExtension");
NativeActivityContext nativeActivityContext;
BookmarkCallback bookmarkCallback;
bool disposed;
bool completed;
bool canceled;
InteropExecutor executor;
IEnumerable<IComparable> initialBookmarks;
Exception uncaughtException;
Transaction transaction;
public InteropEnvironment(InteropExecutor interopExecutor, NativeActivityContext nativeActivityContext,
BookmarkCallback bookmarkCallback, Interop activity, Transaction transaction)
{
//setup environment;
this.executor = interopExecutor;
this.nativeActivityContext = nativeActivityContext;
this.Activity = activity;
this.executor.ServiceProvider = this;
this.bookmarkCallback = bookmarkCallback;
this.transaction = transaction;
OnEnter();
}
public Interop Activity { get; set; }
void IDisposable.Dispose()
{
if (!this.disposed)
{
OnExit();
this.disposed = true;
}
}
public void Execute(System.Workflow.ComponentModel.Activity definition, NativeActivityContext context)
{
Debug.Assert(!disposed, "Cannot access disposed object");
try
{
this.executor.Initialize(definition, this.Activity.GetInputArgumentValues(context), this.Activity.HasNameCollision);
ProcessExecutionStatus(this.executor.Execute());
}
catch (Exception e)
{
this.uncaughtException = e;
throw;
}
}
public void Cancel()
{
Debug.Assert(!disposed, "Cannot access disposed object");
try
{
ProcessExecutionStatus(this.executor.Cancel());
this.canceled = true;
}
catch (Exception e)
{
this.uncaughtException = e;
throw;
}
}
public void EnqueueEvent(IComparable queueName, object item)
{
Debug.Assert(!disposed, "Cannot access disposed object");
try
{
ProcessExecutionStatus(this.executor.EnqueueEvent(queueName, item));
}
catch (Exception e)
{
this.uncaughtException = e;
throw;
}
}
public void TrackActivityStatusChange(System.Workflow.ComponentModel.Activity activity, int eventCounter)
{
this.nativeActivityContext.Track(
new InteropTrackingRecord(this.Activity.DisplayName,
new ActivityTrackingRecord(
activity.GetType(),
activity.QualifiedName,
activity.ContextGuid,
activity.Parent == null ? Guid.Empty : activity.Parent.ContextGuid,
activity.ExecutionStatus,
DateTime.UtcNow,
eventCounter,
null
)
)
);
}
public void TrackData(System.Workflow.ComponentModel.Activity activity, int eventCounter, string key, object data)
{
this.nativeActivityContext.Track(
new InteropTrackingRecord(this.Activity.DisplayName,
new UserTrackingRecord(
activity.GetType(),
activity.QualifiedName,
activity.ContextGuid,
activity.Parent == null ? Guid.Empty : activity.Parent.ContextGuid,
DateTime.UtcNow,
eventCounter,
key,
data
)
)
);
}
public void Resume()
{
Debug.Assert(!disposed, "Cannot access disposed object");
try
{
ProcessExecutionStatus(this.executor.Resume());
}
catch (Exception e)
{
this.uncaughtException = e;
throw;
}
}
//
object IServiceProvider.GetService(Type serviceType)
{
Debug.Assert(!disposed, "Cannot access disposed object");
MethodInfo genericMethodInfo = getServiceMethod.MakeGenericMethod(serviceType);
return genericMethodInfo.Invoke(this.nativeActivityContext, null);
}
public void Persist()
{
this.Activity.Persist(this.nativeActivityContext);
}
public void CreateTransaction(TransactionOptions transactionOptions)
{
this.Activity.CreateTransaction(this.nativeActivityContext, transactionOptions);
}
public void CommitTransaction()
{
this.Activity.CommitTransaction(this.nativeActivityContext);
}
public void AddResourceManager(VolatileResourceManager resourceManager)
{
this.Activity.AddResourceManager(this.nativeActivityContext, resourceManager);
}
//Called everytime on enter of interopenvironment.
void OnEnter()
{
//Capture Current state of Queues in InteropEnvironment.
this.initialBookmarks = this.executor.Queues;
// This method sets up the ambient transaction for the current thread.
// Since the runtime can execute us on different threads,
// we have to set up the transaction scope everytime we enter the interop environment and clear it when we leave the environment.
this.executor.SetAmbientTransactionAndServiceEnvironment(this.transaction);
}
//Called everytime we leave InteropEnvironment.
void OnExit()
{
if (this.uncaughtException != null)
{
if (WorkflowExecutor.IsIrrecoverableException(this.uncaughtException))
{
return;
}
}
// This method clears the ambient transaction for the current thread.
// Since the runtime can execute us on different threads,
// we have to set up the transaction scope everytime we enter the interop environment and clear it when we leave the environment.
this.executor.ClearAmbientTransactionAndServiceEnvironment();
//Capture Current state of Queues in InteropEnvironment.
IEnumerable<IComparable> currentBookmarks = this.executor.Queues;
//Set outparameters when completed or faulted.
if (this.completed || this.uncaughtException != null)
{
this.Activity.OnClose(this.nativeActivityContext, this.uncaughtException);
this.Activity.SetOutputArgumentValues(
this.executor.Outputs, this.nativeActivityContext);
this.nativeActivityContext.RemoveAllBookmarks();
this.executor.BookmarkQueueMap.Clear();
if (this.canceled)
{
this.nativeActivityContext.MarkCanceled();
}
}
else
{
//Find Differentials
IList<IComparable> deletedBookmarks = new List<IComparable>();
foreach (IComparable value in this.initialBookmarks)
{
deletedBookmarks.Add(value);
}
IList<IComparable> newBookmarks = null;
foreach (IComparable value in currentBookmarks)
{
if (!deletedBookmarks.Remove(value))
{
if (newBookmarks == null)
{
newBookmarks = new List<IComparable>();
}
newBookmarks.Add(value);
}
}
if (newBookmarks != null)
{
// Create new Queues as Bookmark.
foreach (IComparable bookmark in newBookmarks)
{
//
Bookmark v2Bookmark = this.nativeActivityContext.CreateBookmark(bookmark.ToString(),
this.bookmarkCallback, BookmarkOptions.MultipleResume);
this.executor.BookmarkQueueMap.Add(v2Bookmark, bookmark);
}
}
// Delete removed queues.
foreach (IComparable bookmark in deletedBookmarks)
{
this.nativeActivityContext.RemoveBookmark(bookmark.ToString());
List<Bookmark> bookmarksToRemove = new List<Bookmark>();
foreach (KeyValuePair<Bookmark, IComparable> entry in this.executor.BookmarkQueueMap)
{
if (entry.Value == bookmark)
{
bookmarksToRemove.Add(entry.Key);
}
}
foreach (Bookmark bookmarkToRemove in bookmarksToRemove)
{
this.executor.BookmarkQueueMap.Remove(bookmarkToRemove);
}
}
}
}
void ProcessExecutionStatus(System.Workflow.ComponentModel.ActivityExecutionStatus executionStatus)
{
this.completed = (executionStatus == System.Workflow.ComponentModel.ActivityExecutionStatus.Closed);
}
public static class ParameterHelper
{
static readonly Type activityType = typeof(System.Workflow.ComponentModel.Activity);
static readonly Type compositeActivityType = typeof(System.Workflow.ComponentModel.CompositeActivity);
static readonly Type dependencyObjectType = typeof(System.Workflow.ComponentModel.DependencyObject);
static readonly Type activityConditionType = typeof(System.Workflow.ComponentModel.ActivityCondition);
// Interop Property Names
internal const string interopPropertyActivityType = "ActivityType";
internal const string interopPropertyActivityProperties = "ActivityProperties";
internal const string interopPropertyActivityMetaProperties = "ActivityMetaProperties";
// Allowed Meta-Properties
internal const string activityNameMetaProperty = "Name";
//Check property names for any Property/PropertyOut pairs that would conflict with our naming scheme
public static bool HasPropertyNameCollision(IList<PropertyInfo> properties)
{
bool hasNameCollision = false;
HashSet<string> propertyNames = new HashSet<string>();
foreach (PropertyInfo propertyInfo in properties)
{
propertyNames.Add(propertyInfo.Name);
}
if (propertyNames.Contains(interopPropertyActivityType) ||
propertyNames.Contains(interopPropertyActivityProperties) ||
propertyNames.Contains(interopPropertyActivityMetaProperties))
{
hasNameCollision = true;
}
else
{
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyNames.Contains(propertyInfo.Name + Interop.OutArgumentSuffix))
{
hasNameCollision = true;
break;
}
}
}
return hasNameCollision;
}
public static bool IsBindable(PropertyInfo propertyInfo)
{
bool isMetaProperty;
if (!IsBindableOrMetaProperty(propertyInfo, out isMetaProperty))
{
return false;
}
return !isMetaProperty;
}
public static bool IsBindableOrMetaProperty(PropertyInfo propertyInfo, out bool isMetaProperty)
{
isMetaProperty = false;
// Validate the declaring type: CompositeActivity and DependencyObject
if (propertyInfo.DeclaringType.Equals(compositeActivityType) ||
propertyInfo.DeclaringType.Equals(dependencyObjectType))
{
return false;
}
// Validate the declaring type: Activity
// We allow certain meta-properties on System.Workflow.ComponentModel.Activity to be visible
if (propertyInfo.DeclaringType.Equals(activityType) &&
!String.Equals(propertyInfo.Name, activityNameMetaProperty, StringComparison.Ordinal))
{
return false;
}
//Validate the data type
if (activityConditionType.IsAssignableFrom(propertyInfo.PropertyType))
{
return false;
}
//Validate whether there is DP(Meta) backup
string dependencyPropertyName = propertyInfo.Name;
System.Workflow.ComponentModel.DependencyProperty dependencyProperty = System.Workflow.ComponentModel.DependencyProperty.FromName(dependencyPropertyName,
propertyInfo.DeclaringType);
if (dependencyProperty != null && dependencyProperty.DefaultMetadata.IsMetaProperty)
{
isMetaProperty = true;
}
return true;
}
}
}
}
| |
using Xunit;
namespace NeinLinq.Tests;
public class InjectLambdaQueryTest_Inheritance
{
[Fact]
public void Query_WithoutSibling_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable(typeof(FunctionsBase)).Select(m => functions.VelocityWithoutSibling(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutSibling: no matching parameterless member found.", error.Message);
}
[Fact]
public void Query_WithConvention_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable(typeof(FunctionsBase)).Select(m => functions.VelocityWithConvention(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithMetadata_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithMethodMetadata_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithMethodMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithNullLambda_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithNullLambda(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Lambda factory for VelocityWithNullLambda returns null.", error.Message);
}
[Fact]
public void Query_WithoutLambda_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutLambda(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutLambda: returns no lambda expression.", error.Message);
}
[Fact]
public void Query_WithoutExpression_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutExpression(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutExpression: returns no lambda expression.", error.Message);
}
[Fact]
public void Query_WithoutSignature_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutSignature(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutSignature: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithoutMatchingSignatureType_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutMatchingSignatureType(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutMatchingSignatureType: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithoutMatchingSignatureSize_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutMatchingSignatureSize(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutMatchingSignatureSize: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithGenericArgument_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithGenericArgument(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithoutMatchingGenericArgument_Throws()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithoutMatchingGenericArgument(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Inheritance+Functions.VelocityWithoutMatchingGenericArgument: no matching parameterless member found.", error.Message);
}
[Fact]
public void Query_WithPrivateSibling_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithPrivateSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithHiddenSiblingViaBase_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithHiddenSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithHiddenSiblingViaDerived_Throws()
{
var functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithHiddenSibling(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Implementing sibling has been hidden.", error.Message);
}
[Fact]
public void Query_WithAbstractSiblingViaBase_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithAbstractSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithPrivateBase_Injects()
{
FunctionsBase functions = new Functions(2);
var query = functions.CallVelocityWithPrivateBase(CreateQuery()).ToInjectable();
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithAbstractSiblingViaDerived_Injects()
{
var functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithAbstractSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithVirtualSiblingViaBase_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithVirtualSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithVirtualSiblingViaDerived_Injects()
{
var functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithVirtualSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
[Fact]
public void Query_WithCachedExpression_Injects()
{
FunctionsBase functions = new Functions(2);
var query = CreateQuery().ToInjectable().Select(m => functions.VelocityWithCachedExpression(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .12 }, result);
}
private static IQueryable<Model> CreateQuery()
{
var data = new[]
{
new Model { Id = 1, Name = "Asdf", Distance = 66, Time = .33 },
new Model { Id = 2, Name = "Narf", Distance = 0, Time = 3.14 },
new Model { Id = 3, Name = "Qwer", Distance = 8, Time = 64 }
};
return data.AsQueryable();
}
private interface IModel
{
int Id { get; set; }
string Name { get; set; }
double Distance { get; set; }
double Time { get; set; }
}
private class Model : IModel
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public double Distance { get; set; }
public double Time { get; set; }
}
private abstract class FunctionsBase
{
private readonly int digits;
protected FunctionsBase(int digits)
{
this.digits = digits;
}
public double VelocityWithoutSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public double VelocityWithConvention(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda("ignore-me")]
public abstract double VelocityWithMethodMetadata(Model value);
[InjectLambda]
public double VelocityWithNullLambda(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutLambda(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutExpression(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutSignature(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutMatchingSignatureType(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutMatchingSignatureSize(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithGenericArgument<TModel>(TModel value)
where TModel : IModel
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithoutMatchingGenericArgument<TModel>(TModel value)
where TModel : IModel
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithPrivateSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda]
public double VelocityWithHiddenSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public Expression<Func<Model, double>> VelocityWithHiddenSibling()
=> v => Math.Round(v.Distance / v.Time, digits);
[InjectLambda]
public double VelocityWithAbstractSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public IQueryable<double> CallVelocityWithPrivateBase(IQueryable<Model> query) =>
query.Select(m => VelocityWithPrivateBase(m));
[InjectLambda]
private double VelocityWithPrivateBase(Model value) =>
throw new NotSupportedException($"Unable to process {value.Name}.");
public abstract Expression<Func<Model, double>> VelocityWithAbstractSibling();
[InjectLambda]
public double VelocityWithVirtualSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public virtual Expression<Func<Model, double>> VelocityWithVirtualSibling()
=> throw new InvalidOperationException("Implementing sibling is missing.");
[InjectLambda]
public double VelocityWithCachedExpression(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
}
private class Functions : FunctionsBase
{
private readonly int digits;
public Functions(int digits)
: base(digits)
{
this.digits = digits;
}
public Expression<Func<Model, double>> VelocityWithConvention()
=> v => Math.Round(v.Distance / v.Time, digits);
public Expression<Func<Model, double>> VelocityWithMetadata()
=> v => Math.Round(v.Distance / v.Time, digits);
[InjectLambda(nameof(Narf))]
public override double VelocityWithMethodMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public Expression<Func<Model, double>> Narf()
=> v => Math.Round(v.Distance / v.Time, digits);
public Expression<Func<Model, double>> VelocityWithNullLambda()
=> digits == 0 ? _ => 0 : null!;
public IEnumerable<Func<Model, double>> VelocityWithoutLambda()
=> new Func<Model, double>[] { v => Math.Round(v.Distance / v.Time, digits) };
public Func<Model, double> VelocityWithoutExpression()
=> v => Math.Round(v.Distance / v.Time, digits);
public LambdaExpression VelocityWithoutSignature()
=> (Expression<Func<Model, double>>)(v => Math.Round(v.Distance / v.Time, digits));
public Expression<Func<Model, float>> VelocityWithoutMatchingSignatureType()
=> v => (float)Math.Round(v.Distance / v.Time, digits);
public Expression<Func<double, double, double>> VelocityWithoutMatchingSignatureSize()
=> (d, t) => Math.Round(d / t, digits);
public Expression<Func<TModel, double>> VelocityWithGenericArgument<TModel>()
where TModel : IModel
=> v => Math.Round(v.Distance / v.Time, digits);
public Expression<Func<Model, double>> VelocityWithoutMatchingGenericArgument()
=> v => Math.Round(v.Distance / v.Time, digits);
private Expression<Func<Model, double>> VelocityWithPrivateSibling()
=> v => Math.Round(v.Distance / v.Time, digits);
public new Expression<Func<Model, double>> VelocityWithHiddenSibling()
=> digits == 0 ? base.VelocityWithHiddenSibling() : throw new InvalidOperationException("Implementing sibling has been hidden.");
public override Expression<Func<Model, double>> VelocityWithAbstractSibling()
=> v => Math.Round(v.Distance / v.Time, digits);
public Expression<Func<Model, double>> VelocityWithPrivateBase() =>
v => Math.Round(v.Distance / v.Time, digits);
public override Expression<Func<Model, double>> VelocityWithVirtualSibling()
=> v => Math.Round(v.Distance / v.Time, digits);
private CachedExpression<Func<Model, double>> VelocityWithCachedExpressionExpr { get; }
= CachedExpression.From<Func<Model, double>>(v => Math.Round(v.Distance / v.Time, 2));
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
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;
public static partial class TagsOperationsExtensions
{
/// <summary>
/// Delete a subscription resource tag value.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag.
/// </param>
public static void DeleteValue(this ITagsOperations operations, string tagName, string tagValue)
{
Task.Factory.StartNew(s => ((ITagsOperations)s).DeleteValueAsync(tagName, tagValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a subscription resource tag value.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteValueAsync( this ITagsOperations operations, string tagName, string tagValue, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteValueWithHttpMessagesAsync(tagName, tagValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create a subscription resource tag value.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag.
/// </param>
public static TagValue CreateOrUpdateValue(this ITagsOperations operations, string tagName, string tagValue)
{
return Task.Factory.StartNew(s => ((ITagsOperations)s).CreateOrUpdateValueAsync(tagName, tagValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a subscription resource tag value.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TagValue> CreateOrUpdateValueAsync( this ITagsOperations operations, string tagName, string tagValue, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateValueWithHttpMessagesAsync(tagName, tagValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create a subscription resource tag.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
public static TagDetails CreateOrUpdate(this ITagsOperations operations, string tagName)
{
return Task.Factory.StartNew(s => ((ITagsOperations)s).CreateOrUpdateAsync(tagName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a subscription resource tag.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TagDetails> CreateOrUpdateAsync( this ITagsOperations operations, string tagName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(tagName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a subscription resource tag.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
public static void Delete(this ITagsOperations operations, string tagName)
{
Task.Factory.StartNew(s => ((ITagsOperations)s).DeleteAsync(tagName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a subscription resource tag.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this ITagsOperations operations, string tagName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(tagName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get a list of subscription resource tags.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<TagDetails> List(this ITagsOperations operations)
{
return Task.Factory.StartNew(s => ((ITagsOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of subscription resource tags.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<TagDetails>> ListAsync( this ITagsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of subscription resource tags.
/// </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<TagDetails> ListNext(this ITagsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ITagsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of subscription resource tags.
/// </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<TagDetails>> ListNextAsync( this ITagsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']"
[global::Android.Runtime.Register ("org/apache/cordova/CordovaBridge", DoNotGenerateAcw=true)]
public partial class CordovaBridge : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/CordovaBridge", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CordovaBridge); }
}
protected CordovaBridge (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lorg_apache_cordova_PluginManager_Lorg_apache_cordova_NativeToJsMessageQueue_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/constructor[@name='CordovaBridge' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginManager'] and parameter[2][@type='org.apache.cordova.NativeToJsMessageQueue']]"
[Register (".ctor", "(Lorg/apache/cordova/PluginManager;Lorg/apache/cordova/NativeToJsMessageQueue;)V", "")]
public CordovaBridge (global::Org.Apache.Cordova.PluginManager p0, global::Org.Apache.Cordova.NativeToJsMessageQueue p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (CordovaBridge)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginManager;Lorg/apache/cordova/NativeToJsMessageQueue;)V", new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginManager;Lorg/apache/cordova/NativeToJsMessageQueue;)V", new JValue (p0), new JValue (p1));
return;
}
if (id_ctor_Lorg_apache_cordova_PluginManager_Lorg_apache_cordova_NativeToJsMessageQueue_ == IntPtr.Zero)
id_ctor_Lorg_apache_cordova_PluginManager_Lorg_apache_cordova_NativeToJsMessageQueue_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginManager;Lorg/apache/cordova/NativeToJsMessageQueue;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginManager_Lorg_apache_cordova_NativeToJsMessageQueue_, new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginManager_Lorg_apache_cordova_NativeToJsMessageQueue_, new JValue (p0), new JValue (p1));
}
static Delegate cb_getMessageQueue;
#pragma warning disable 0169
static Delegate GetGetMessageQueueHandler ()
{
if (cb_getMessageQueue == null)
cb_getMessageQueue = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetMessageQueue);
return cb_getMessageQueue;
}
static IntPtr n_GetMessageQueue (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.MessageQueue);
}
#pragma warning restore 0169
static IntPtr id_getMessageQueue;
public virtual global::Org.Apache.Cordova.NativeToJsMessageQueue MessageQueue {
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='getMessageQueue' and count(parameter)=0]"
[Register ("getMessageQueue", "()Lorg/apache/cordova/NativeToJsMessageQueue;", "GetGetMessageQueueHandler")]
get {
if (id_getMessageQueue == IntPtr.Zero)
id_getMessageQueue = JNIEnv.GetMethodID (class_ref, "getMessageQueue", "()Lorg/apache/cordova/NativeToJsMessageQueue;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (JNIEnv.CallObjectMethod (Handle, id_getMessageQueue), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMessageQueue", "()Lorg/apache/cordova/NativeToJsMessageQueue;")), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetJsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == null)
cb_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_JsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_);
return cb_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
}
static IntPtr n_JsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3, IntPtr native_p4)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
string p3 = JNIEnv.GetString (native_p3, JniHandleOwnership.DoNotTransfer);
string p4 = JNIEnv.GetString (native_p4, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.NewString (__this.JsExec (p0, p1, p2, p3, p4));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='jsExec' and count(parameter)=5 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String'] and parameter[5][@type='java.lang.String']]"
[Register ("jsExec", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", "GetJsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual string JsExec (int p0, string p1, string p2, string p3, string p4)
{
if (id_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "jsExec", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
IntPtr native_p3 = JNIEnv.NewString (p3);
IntPtr native_p4 = JNIEnv.NewString (p4);
string __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_jsExec_ILjava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3), new JValue (native_p4)), JniHandleOwnership.TransferLocalRef);
else
__ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "jsExec", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), new JValue (p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3), new JValue (native_p4)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
JNIEnv.DeleteLocalRef (native_p4);
return __ret;
}
static Delegate cb_jsRetrieveJsMessages_IZ;
#pragma warning disable 0169
static Delegate GetJsRetrieveJsMessages_IZHandler ()
{
if (cb_jsRetrieveJsMessages_IZ == null)
cb_jsRetrieveJsMessages_IZ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, bool, IntPtr>) n_JsRetrieveJsMessages_IZ);
return cb_jsRetrieveJsMessages_IZ;
}
static IntPtr n_JsRetrieveJsMessages_IZ (IntPtr jnienv, IntPtr native__this, int p0, bool p1)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.JsRetrieveJsMessages (p0, p1));
}
#pragma warning restore 0169
static IntPtr id_jsRetrieveJsMessages_IZ;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='jsRetrieveJsMessages' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='boolean']]"
[Register ("jsRetrieveJsMessages", "(IZ)Ljava/lang/String;", "GetJsRetrieveJsMessages_IZHandler")]
public virtual string JsRetrieveJsMessages (int p0, bool p1)
{
if (id_jsRetrieveJsMessages_IZ == IntPtr.Zero)
id_jsRetrieveJsMessages_IZ = JNIEnv.GetMethodID (class_ref, "jsRetrieveJsMessages", "(IZ)Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_jsRetrieveJsMessages_IZ, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "jsRetrieveJsMessages", "(IZ)Ljava/lang/String;"), new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_jsSetNativeToJsBridgeMode_II;
#pragma warning disable 0169
static Delegate GetJsSetNativeToJsBridgeMode_IIHandler ()
{
if (cb_jsSetNativeToJsBridgeMode_II == null)
cb_jsSetNativeToJsBridgeMode_II = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int>) n_JsSetNativeToJsBridgeMode_II);
return cb_jsSetNativeToJsBridgeMode_II;
}
static void n_JsSetNativeToJsBridgeMode_II (IntPtr jnienv, IntPtr native__this, int p0, int p1)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.JsSetNativeToJsBridgeMode (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_jsSetNativeToJsBridgeMode_II;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='jsSetNativeToJsBridgeMode' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]"
[Register ("jsSetNativeToJsBridgeMode", "(II)V", "GetJsSetNativeToJsBridgeMode_IIHandler")]
public virtual void JsSetNativeToJsBridgeMode (int p0, int p1)
{
if (id_jsSetNativeToJsBridgeMode_II == IntPtr.Zero)
id_jsSetNativeToJsBridgeMode_II = JNIEnv.GetMethodID (class_ref, "jsSetNativeToJsBridgeMode", "(II)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_jsSetNativeToJsBridgeMode_II, new JValue (p0), new JValue (p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "jsSetNativeToJsBridgeMode", "(II)V"), new JValue (p0), new JValue (p1));
}
static Delegate cb_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetPromptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == null)
cb_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_PromptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_);
return cb_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
}
static IntPtr n_PromptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.NewString (__this.PromptOnJsPrompt (p0, p1, p2));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='promptOnJsPrompt' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]"
[Register ("promptOnJsPrompt", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", "GetPromptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual string PromptOnJsPrompt (string p0, string p1, string p2)
{
if (id_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "promptOnJsPrompt", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
string __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_promptOnJsPrompt_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1), new JValue (native_p2)), JniHandleOwnership.TransferLocalRef);
else
__ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "promptOnJsPrompt", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), new JValue (native_p0), new JValue (native_p1), new JValue (native_p2)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
return __ret;
}
static Delegate cb_reset_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetReset_Ljava_lang_String_Handler ()
{
if (cb_reset_Ljava_lang_String_ == null)
cb_reset_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Reset_Ljava_lang_String_);
return cb_reset_Ljava_lang_String_;
}
static void n_Reset_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CordovaBridge __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaBridge> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Reset (p0);
}
#pragma warning restore 0169
static IntPtr id_reset_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaBridge']/method[@name='reset' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("reset", "(Ljava/lang/String;)V", "GetReset_Ljava_lang_String_Handler")]
public virtual void Reset (string p0)
{
if (id_reset_Ljava_lang_String_ == IntPtr.Zero)
id_reset_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "reset", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_reset_Ljava_lang_String_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "reset", "(Ljava/lang/String;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Compression.Tests
{
public class zip_CreateTests : ZipFileTestBase
{
[Fact]
public static void CreateModeInvalidOperations()
{
MemoryStream ms = new MemoryStream();
ZipArchive z = new ZipArchive(ms, ZipArchiveMode.Create);
Assert.Throws<NotSupportedException>(() => { var x = z.Entries; }); //"Entries not applicable on Create"
Assert.Throws<NotSupportedException>(() => z.GetEntry("dirka")); //"GetEntry not applicable on Create"
ZipArchiveEntry e = z.CreateEntry("hey");
Assert.Throws<NotSupportedException>(() => e.Delete()); //"Can't delete new entry"
Stream s = e.Open();
Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"Can't read on new entry"
Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"Can't seek on new entry"
Assert.Throws<NotSupportedException>(() => s.Position = 0); //"Can't set position on new entry"
Assert.Throws<NotSupportedException>(() => { var x = s.Length; }); //"Can't get length on new entry"
Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset()); //"Can't get LastWriteTime on new entry"
Assert.Throws<InvalidOperationException>(() => { var x = e.Length; }); //"Can't get length on new entry"
Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; }); //"can't get CompressedLength on new entry"
Assert.Throws<IOException>(() => z.CreateEntry("bad"));
s.Dispose();
Assert.Throws<ObjectDisposedException>(() => s.WriteByte(25)); //"Can't write to disposed entry"
Assert.Throws<IOException>(() => e.Open());
Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset());
Assert.Throws<InvalidOperationException>(() => { var x = e.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; });
ZipArchiveEntry e1 = z.CreateEntry("e1");
ZipArchiveEntry e2 = z.CreateEntry("e2");
Assert.Throws<IOException>(() => e1.Open()); //"Can't open previous entry after new entry created"
z.Dispose();
Assert.Throws<ObjectDisposedException>(() => z.CreateEntry("dirka")); //"Can't create after dispose"
}
[Theory]
[InlineData("small", false, false)]
[InlineData("normal", false, false)]
[InlineData("empty", false, false)]
[InlineData("emptydir", false, false)]
[InlineData("small", true, false)]
[InlineData("normal", true, false)]
[InlineData("small", false, true)]
[InlineData("normal", false, true)]
public static async Task CreateNormal_Seekable(string folder, bool useSpansForWriting, bool writeInChunks)
{
using (var s = new MemoryStream())
{
var testStream = new WrappedStream(s, false, true, true, null);
await CreateFromDir(zfolder(folder), testStream, ZipArchiveMode.Create, useSpansForWriting, writeInChunks);
IsZipSameAsDir(s, zfolder(folder), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
}
[Theory]
[InlineData("small")]
[InlineData("normal")]
[InlineData("empty")]
[InlineData("emptydir")]
public static async Task CreateNormal_Unseekable(string folder)
{
using (var s = new MemoryStream())
{
var testStream = new WrappedStream(s, false, true, false, null);
await CreateFromDir(zfolder(folder), testStream, ZipArchiveMode.Create);
IsZipSameAsDir(s, zfolder(folder), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
}
[Fact]
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Jenkins fails with unicode characters [JENKINS-12610]
public static async Task CreateNormal_Unicode_Seekable()
{
using (var s = new MemoryStream())
{
var testStream = new WrappedStream(s, false, true, true, null);
await CreateFromDir(zfolder("unicode"), testStream, ZipArchiveMode.Create);
IsZipSameAsDir(s, zfolder("unicode"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
}
[Fact]
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Jenkins fails with unicode characters [JENKINS-12610]
public static async Task CreateNormal_Unicode_Unseekable()
{
using (var s = new MemoryStream())
{
var testStream = new WrappedStream(s, false, true, false, null);
await CreateFromDir(zfolder("unicode"), testStream, ZipArchiveMode.Create);
IsZipSameAsDir(s, zfolder("unicode"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
}
[Fact]
public static void CreateUncompressedArchive()
{
using (var testStream = new MemoryStream())
{
var testfilename = "testfile";
var testFileContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
using (var zip = new ZipArchive(testStream, ZipArchiveMode.Create))
{
var utf8WithoutBom = new Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
ZipArchiveEntry newEntry = zip.CreateEntry(testfilename, CompressionLevel.NoCompression);
using (var writer = new StreamWriter(newEntry.Open(), utf8WithoutBom))
{
writer.Write(testFileContent);
writer.Flush();
}
byte[] fileContent = testStream.ToArray();
// zip file header stores values as little-endian
byte compressionMethod = fileContent[8];
Assert.Equal(0, compressionMethod); // stored => 0, deflate => 8
uint compressedSize = BitConverter.ToUInt32(fileContent, 18);
uint uncompressedSize = BitConverter.ToUInt32(fileContent, 22);
Assert.Equal(uncompressedSize, compressedSize);
byte filenamelength = fileContent[26];
Assert.Equal(testfilename.Length, filenamelength);
string readFileName = ReadStringFromSpan(fileContent.AsSpan(30, filenamelength));
Assert.Equal(testfilename, readFileName);
string readFileContent = ReadStringFromSpan(fileContent.AsSpan(30 + filenamelength, testFileContent.Length));
Assert.Equal(testFileContent, readFileContent);
}
}
}
[Fact]
public static void CreateNormal_VerifyDataDescriptor()
{
using var memoryStream = new MemoryStream();
// We need an non-seekable stream so the data descriptor bit is turned on when saving
var wrappedStream = new WrappedStream(memoryStream, true, true, false, null);
// Creation will go through the path that sets the data descriptor bit when the stream is unseekable
using (var archive = new ZipArchive(wrappedStream, ZipArchiveMode.Create))
{
CreateEntry(archive, "A", "xxx");
CreateEntry(archive, "B", "yyy");
}
AssertDataDescriptor(memoryStream, true);
// Update should flip the data descriptor bit to zero on save
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Update))
{
ZipArchiveEntry entry = archive.Entries[0];
using Stream entryStream = entry.Open();
StreamReader reader = new StreamReader(entryStream);
string content = reader.ReadToEnd();
// Append a string to this entry
entryStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(entryStream);
writer.Write("zzz");
writer.Flush();
}
AssertDataDescriptor(memoryStream, false);
}
private static string ReadStringFromSpan(Span<byte> input)
{
return Text.Encoding.UTF8.GetString(input.ToArray());
}
private static void CreateEntry(ZipArchive archive, string fileName, string fileContents)
{
ZipArchiveEntry entry = archive.CreateEntry(fileName);
using StreamWriter writer = new StreamWriter(entry.Open());
writer.Write(fileContents);
}
private static void AssertDataDescriptor(MemoryStream memoryStream, bool hasDataDescriptor)
{
byte[] fileBytes = memoryStream.ToArray();
Assert.Equal(hasDataDescriptor ? 8 : 0, fileBytes[6]);
Assert.Equal(0, fileBytes[7]);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.XMLBasedFieldsAndContentTypesWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
//------------------------------------------------------------------------------
// <copyright file="UserGroupService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// 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>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.UserGroup
{
public class UserGroupService : ServiceBase
{
public UserGroupService(ISession session)
: base(session)
{
}
public async Task AddGroupUserGroupsAsync(long groupId, IEnumerable<long> userGroupIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userGroupIds", userGroupIds);
var _command = new JsonObject()
{
{ "/usergroup/add-group-user-groups", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task AddTeamUserGroupsAsync(long teamId, IEnumerable<long> userGroupIds)
{
var _parameters = new JsonObject();
_parameters.Add("teamId", teamId);
_parameters.Add("userGroupIds", userGroupIds);
var _command = new JsonObject()
{
{ "/usergroup/add-team-user-groups", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> AddUserGroupAsync(string name, string description)
{
var _parameters = new JsonObject();
_parameters.Add("name", name);
_parameters.Add("description", description);
var _command = new JsonObject()
{
{ "/usergroup/add-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddUserGroupAsync(string name, string description, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("name", name);
_parameters.Add("description", description);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/usergroup/add-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task DeleteUserGroupAsync(long userGroupId)
{
var _parameters = new JsonObject();
_parameters.Add("userGroupId", userGroupId);
var _command = new JsonObject()
{
{ "/usergroup/delete-user-group", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> GetUserGroupAsync(string name)
{
var _parameters = new JsonObject();
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/usergroup/get-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetUserGroupAsync(long userGroupId)
{
var _parameters = new JsonObject();
_parameters.Add("userGroupId", userGroupId);
var _command = new JsonObject()
{
{ "/usergroup/get-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserUserGroupsAsync(long userId)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
var _command = new JsonObject()
{
{ "/usergroup/get-user-user-groups", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task UnsetGroupUserGroupsAsync(long groupId, IEnumerable<long> userGroupIds)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userGroupIds", userGroupIds);
var _command = new JsonObject()
{
{ "/usergroup/unset-group-user-groups", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnsetTeamUserGroupsAsync(long teamId, IEnumerable<long> userGroupIds)
{
var _parameters = new JsonObject();
_parameters.Add("teamId", teamId);
_parameters.Add("userGroupIds", userGroupIds);
var _command = new JsonObject()
{
{ "/usergroup/unset-team-user-groups", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> UpdateUserGroupAsync(long userGroupId, string name, string description)
{
var _parameters = new JsonObject();
_parameters.Add("userGroupId", userGroupId);
_parameters.Add("name", name);
_parameters.Add("description", description);
var _command = new JsonObject()
{
{ "/usergroup/update-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateUserGroupAsync(long userGroupId, string name, string description, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("userGroupId", userGroupId);
_parameters.Add("name", name);
_parameters.Add("description", description);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/usergroup/update-user-group", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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 Http.Shared.Contexts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.Instrumentation;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.WebSockets;
namespace Http.Contexts
{
public class DefaultHttpContext : HttpContextBase, IHttpContext
{
public DefaultHttpContext()
{
RouteParams = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
public void ForceRootDir(string rootDir)
{
RootDir = rootDir;
}
public string RootDir { get; private set; }
public IHttpContext RootContext
{
get
{
if (Parent == null) return this;
return Parent.RootContext;
}
}
public Dictionary<string, object> RouteParams { get; set; }
private readonly HttpContext _httpContext;
public object SourceObject { get { return _httpContext; } }
private static readonly MethodInfo _getInnerCollection;
static DefaultHttpContext()
{
var innerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.NonPublic | BindingFlags.Instance);
_getInnerCollection = innerCollectionProperty.GetGetMethod(true);
}
public void ForceHeader(string key, string value)
{
var nameValueCollection = (NameValueCollection)_getInnerCollection.Invoke(_response.Headers, new object[] { });
if (!_response.Headers.AllKeys.ToArray().Contains(key))
{
nameValueCollection.Add(key, value);
}
else
{
nameValueCollection.Set(key, value);
}
}
public DefaultHttpContext(HttpContext httpContext)
{
_httpContext = httpContext;
InitializeUnsettable();
}
public IHttpContext Parent
{
get { return null; }
}
public override ISubscriptionToken AddOnRequestCompleted(Action<HttpContextBase> callback)
{
throw new NotImplementedException();
}
public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc)
{
_httpContext.AcceptWebSocketRequest(userFunc);
}
public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options)
{
_httpContext.AcceptWebSocketRequest(userFunc, options);
}
public override void AddError(Exception errorInfo)
{
_httpContext.AddError(errorInfo);
}
public override void ClearError()
{
_httpContext.ClearError();
}
public override ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target)
{
return _httpContext.DisposeOnPipelineCompleted(target);
}
public override Object GetGlobalResourceObject(String classKey, String resourceKey)
{
//TODO Missing GetGlobalResourceObject for HttpContext
return null;
}
public override Object GetGlobalResourceObject(String classKey, String resourceKey, CultureInfo culture)
{
//TODO Missing GetGlobalResourceObject for HttpContext
return null;
}
public override Object GetLocalResourceObject(String virtualPath, String resourceKey)
{
//TODO Missing GetLocalResourceObject for HttpContext
return null;
}
public override Object GetLocalResourceObject(String virtualPath, String resourceKey, CultureInfo culture)
{
//TODO Missing GetLocalResourceObject for HttpContext
return null;
}
public override Object GetSection(String sectionName)
{
return _httpContext.GetSection(sectionName);
}
public override void RemapHandler(IHttpHandler handler)
{
_httpContext.RemapHandler(handler);
}
public override void RewritePath(String path)
{
_httpContext.RewritePath(path);
}
public override void RewritePath(String path, Boolean rebaseClientPath)
{
_httpContext.RewritePath(path, rebaseClientPath);
}
public override void RewritePath(String filePath, String pathInfo, String queryString)
{
_httpContext.RewritePath(filePath, pathInfo, queryString);
}
public override void RewritePath(String filePath, String pathInfo, String queryString, Boolean setClientFilePath)
{
_httpContext.RewritePath(filePath, pathInfo, queryString, setClientFilePath);
}
public override void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior)
{
_httpContext.SetSessionStateBehavior(sessionStateBehavior);
}
public override Object GetService(Type serviceType)
{
//TODO Missing GetService for HttpContext
return null;
}
public override Exception[] AllErrors { get { return _httpContext.AllErrors; } }
public void SetAllErrors(Exception[] val)
{
}
public override Boolean AllowAsyncDuringSyncStages
{
set
{
_httpContext.AllowAsyncDuringSyncStages = value;
}
get
{
return _httpContext.AllowAsyncDuringSyncStages;
}
}
public override HttpApplication ApplicationInstance
{
set
{
_httpContext.ApplicationInstance = value;
}
get
{
return _httpContext.ApplicationInstance;
}
}
public override AsyncPreloadModeFlags AsyncPreloadMode
{
set
{
_httpContext.AsyncPreloadMode = value;
}
get
{
return _httpContext.AsyncPreloadMode;
}
}
public override Cache Cache { get { return _httpContext.Cache; } }
public void SetCache(Cache val)
{
}
public override IHttpHandler CurrentHandler { get { return _httpContext.CurrentHandler; } }
public void SetCurrentHandler(IHttpHandler val)
{
}
public override RequestNotification CurrentNotification { get { return _httpContext.CurrentNotification; } }
public void SetCurrentNotification(RequestNotification val)
{
}
public override Exception Error { get { return _httpContext.Error; } }
public void SetError(Exception val)
{
}
public override IHttpHandler Handler
{
set
{
_httpContext.Handler = value;
}
get
{
return _httpContext.Handler;
}
}
public override Boolean IsCustomErrorEnabled { get { return _httpContext.IsCustomErrorEnabled; } }
public void SetIsCustomErrorEnabled(Boolean val)
{
}
public override Boolean IsDebuggingEnabled { get { return _httpContext.IsDebuggingEnabled; } }
public void SetIsDebuggingEnabled(Boolean val)
{
}
public override Boolean IsPostNotification { get { return _httpContext.IsPostNotification; } }
public void SetIsPostNotification(Boolean val)
{
}
public override Boolean IsWebSocketRequest { get { return _httpContext.IsWebSocketRequest; } }
public void SetIsWebSocketRequest(Boolean val)
{
}
public override Boolean IsWebSocketRequestUpgrading { get { return _httpContext.IsWebSocketRequestUpgrading; } }
public void SetIsWebSocketRequestUpgrading(Boolean val)
{
}
public override IDictionary Items { get { return _httpContext.Items; } }
public void SetItems(IDictionary val)
{
}
public override PageInstrumentationService PageInstrumentation { get { return _httpContext.PageInstrumentation; } }
public void SetPageInstrumentation(PageInstrumentationService val)
{
}
public override IHttpHandler PreviousHandler { get { return _httpContext.PreviousHandler; } }
public void SetPreviousHandler(IHttpHandler val)
{
}
public override ProfileBase Profile { get { return _httpContext.Profile; } }
public void SetProfile(ProfileBase val)
{
}
public override Boolean SkipAuthorization
{
set
{
_httpContext.SkipAuthorization = value;
}
get
{
return _httpContext.SkipAuthorization;
}
}
public override DateTime Timestamp { get { return _httpContext.Timestamp; } }
public void SetTimestamp(DateTime val)
{
}
public override Boolean ThreadAbortOnTimeout
{
set
{
_httpContext.ThreadAbortOnTimeout = value;
}
get
{
return _httpContext.ThreadAbortOnTimeout;
}
}
public override TraceContext Trace { get { return _httpContext.Trace; } }
public void SetTrace(TraceContext val)
{
}
public override IPrincipal User
{
set
{
_httpContext.User = value;
}
get
{
return _httpContext.User;
}
}
public override String WebSocketNegotiatedProtocol { get { return _httpContext.WebSocketNegotiatedProtocol; } }
public void SetWebSocketNegotiatedProtocol(String val)
{
}
public override IList<String> WebSocketRequestedProtocols { get { return _httpContext.WebSocketRequestedProtocols; } }
public void SetWebSocketRequestedProtocols(IList<String> val)
{
}
public void InitializeUnsettable()
{
_application = ConvertApplication(_httpContext.Application);
_server = ConvertServer(_httpContext.Server);
_session = ConvertSession(_httpContext.Session);
_request = new DefaultHttpRequest(_httpContext.Request);
_response = new DefaultHttpResponse(_httpContext.Response);
_response.ContentEncoding = _request.ContentEncoding;
}
private HttpApplicationStateBase _application;
public override HttpApplicationStateBase Application { get { return _application; } }
public void SetApplication(HttpApplicationStateBase val)
{
}
private HttpRequestBase _request;
private HttpResponseBase _response;
public override HttpRequestBase Request { get { return _request; } }
public void SetRequest(HttpRequestBase val)
{
_request = val;
}
public override HttpResponseBase Response { get { return _response; } }
public void SetResponse(HttpResponseBase val)
{
_response = val;
}
private HttpServerUtilityBase _server;
public override HttpServerUtilityBase Server { get { return _server; } }
public void SetServer(HttpServerUtilityBase val)
{
_server = val;
}
private HttpSessionStateBase _session;
public override HttpSessionStateBase Session { get { return _session; } }
public void SetSession(HttpSessionStateBase val)
{
_session = val;
}
private HttpSessionStateBase ConvertSession(HttpSessionState session)
{
return new DefaultHttpSessionState(session);
}
// ReSharper disable once UnusedParameter.Local
private HttpApplicationStateBase ConvertApplication(HttpApplicationState application)
{
return null;
}
// ReSharper disable once UnusedParameter.Local
private HttpServerUtilityBase ConvertServer(HttpServerUtility server)
{
return null;
}
public Task InitializeWebSocket()
{
throw new NotImplementedException();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.BackupServices
{
/// <summary>
/// Definition of Container operations for the Azure Backup extension.
/// </summary>
internal partial class MarsContainerOperations : IServiceOperations<BackupVaultServicesManagementClient>, IMarsContainerOperations
{
/// <summary>
/// Initializes a new instance of the MarsContainerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal MarsContainerOperations(BackupVaultServicesManagementClient client)
{
this._client = client;
}
private BackupVaultServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.BackupServices.BackupVaultServicesManagementClient.
/// </summary>
public BackupVaultServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Enable the container reregistration.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='enableReregistrationRequest'>
/// Required. Enable Reregistration Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public async Task<OperationResponse> EnableMarsContainerReregistrationAsync(string resourceGroupName, string resourceName, string containerId, EnableReregistrationRequest enableReregistrationRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (containerId == null)
{
throw new ArgumentNullException("containerId");
}
if (enableReregistrationRequest == null)
{
throw new ArgumentNullException("enableReregistrationRequest");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("containerId", containerId);
tracingParameters.Add("enableReregistrationRequest", enableReregistrationRequest);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "EnableMarsContainerReregistrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/backupContainers/";
url = url + Uri.EscapeDataString(containerId);
url = url + "/enableReRegister";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject enableReregistrationRequestValue = new JObject();
requestDoc = enableReregistrationRequestValue;
if (enableReregistrationRequest.ContainerReregistrationState != null)
{
JObject propertiesValue = new JObject();
enableReregistrationRequestValue["properties"] = propertiesValue;
propertiesValue["enableReRegister"] = enableReregistrationRequest.ContainerReregistrationState.EnableReregistration;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Guid operationIdInstance = Guid.Parse(((string)responseDoc));
result.OperationId = operationIdInstance;
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public async Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAsync(string resourceGroupName, string resourceName, MarsContainerType containerType, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("containerType", containerType);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListMarsContainersByTypeAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/backupContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
List<string> odataFilter = new List<string>();
odataFilter.Add("type eq '" + Uri.EscapeDataString(containerType.ToString()) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ListMarsContainerOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ListMarsContainerOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ListMarsContainerResponse listMarsContainerResponseInstance = new ListMarsContainerResponse();
result.ListMarsContainerResponse = listMarsContainerResponseInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MarsContainerResponse marsContainerResponseInstance = new MarsContainerResponse();
listMarsContainerResponseInstance.Value.Add(marsContainerResponseInstance);
JToken uniqueNameValue = valueValue["uniqueName"];
if (uniqueNameValue != null && uniqueNameValue.Type != JTokenType.Null)
{
string uniqueNameInstance = ((string)uniqueNameValue);
marsContainerResponseInstance.UniqueName = uniqueNameInstance;
}
JToken containerTypeValue = valueValue["containerType"];
if (containerTypeValue != null && containerTypeValue.Type != JTokenType.Null)
{
string containerTypeInstance = ((string)containerTypeValue);
marsContainerResponseInstance.ContainerType = containerTypeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
MarsContainerProperties propertiesInstance = new MarsContainerProperties();
marsContainerResponseInstance.Properties = propertiesInstance;
JToken containerIdValue = propertiesValue["containerId"];
if (containerIdValue != null && containerIdValue.Type != JTokenType.Null)
{
long containerIdInstance = ((long)containerIdValue);
propertiesInstance.ContainerId = containerIdInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken containerStampIdValue = propertiesValue["containerStampId"];
if (containerStampIdValue != null && containerStampIdValue.Type != JTokenType.Null)
{
Guid containerStampIdInstance = Guid.Parse(((string)containerStampIdValue));
propertiesInstance.ContainerStampId = containerStampIdInstance;
}
JToken containerStampUriValue = propertiesValue["containerStampUri"];
if (containerStampUriValue != null && containerStampUriValue.Type != JTokenType.Null)
{
string containerStampUriInstance = ((string)containerStampUriValue);
propertiesInstance.ContainerStampUri = containerStampUriInstance;
}
JToken canReRegisterValue = propertiesValue["canReRegister"];
if (canReRegisterValue != null && canReRegisterValue.Type != JTokenType.Null)
{
bool canReRegisterInstance = ((bool)canReRegisterValue);
propertiesInstance.CanReRegister = canReRegisterInstance;
}
JToken customerTypeValue = propertiesValue["customerType"];
if (customerTypeValue != null && customerTypeValue.Type != JTokenType.Null)
{
string customerTypeInstance = ((string)customerTypeValue);
propertiesInstance.CustomerType = customerTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
marsContainerResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
marsContainerResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
marsContainerResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
listMarsContainerResponseInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
listMarsContainerResponseInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
listMarsContainerResponseInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
listMarsContainerResponseInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
customRequestHeaders.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='friendlyName'>
/// Required. Friendly name of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public async Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAndFriendlyNameAsync(string resourceGroupName, string resourceName, MarsContainerType containerType, string friendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (friendlyName == null)
{
throw new ArgumentNullException("friendlyName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("containerType", containerType);
tracingParameters.Add("friendlyName", friendlyName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListMarsContainersByTypeAndFriendlyNameAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/backupContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
List<string> odataFilter = new List<string>();
odataFilter.Add("type eq '" + Uri.EscapeDataString(containerType.ToString()) + "'");
odataFilter.Add("friendlyName eq '" + Uri.EscapeDataString(friendlyName) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ListMarsContainerOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ListMarsContainerOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ListMarsContainerResponse listMarsContainerResponseInstance = new ListMarsContainerResponse();
result.ListMarsContainerResponse = listMarsContainerResponseInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MarsContainerResponse marsContainerResponseInstance = new MarsContainerResponse();
listMarsContainerResponseInstance.Value.Add(marsContainerResponseInstance);
JToken uniqueNameValue = valueValue["uniqueName"];
if (uniqueNameValue != null && uniqueNameValue.Type != JTokenType.Null)
{
string uniqueNameInstance = ((string)uniqueNameValue);
marsContainerResponseInstance.UniqueName = uniqueNameInstance;
}
JToken containerTypeValue = valueValue["containerType"];
if (containerTypeValue != null && containerTypeValue.Type != JTokenType.Null)
{
string containerTypeInstance = ((string)containerTypeValue);
marsContainerResponseInstance.ContainerType = containerTypeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
MarsContainerProperties propertiesInstance = new MarsContainerProperties();
marsContainerResponseInstance.Properties = propertiesInstance;
JToken containerIdValue = propertiesValue["containerId"];
if (containerIdValue != null && containerIdValue.Type != JTokenType.Null)
{
long containerIdInstance = ((long)containerIdValue);
propertiesInstance.ContainerId = containerIdInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken containerStampIdValue = propertiesValue["containerStampId"];
if (containerStampIdValue != null && containerStampIdValue.Type != JTokenType.Null)
{
Guid containerStampIdInstance = Guid.Parse(((string)containerStampIdValue));
propertiesInstance.ContainerStampId = containerStampIdInstance;
}
JToken containerStampUriValue = propertiesValue["containerStampUri"];
if (containerStampUriValue != null && containerStampUriValue.Type != JTokenType.Null)
{
string containerStampUriInstance = ((string)containerStampUriValue);
propertiesInstance.ContainerStampUri = containerStampUriInstance;
}
JToken canReRegisterValue = propertiesValue["canReRegister"];
if (canReRegisterValue != null && canReRegisterValue.Type != JTokenType.Null)
{
bool canReRegisterInstance = ((bool)canReRegisterValue);
propertiesInstance.CanReRegister = canReRegisterInstance;
}
JToken customerTypeValue = propertiesValue["customerType"];
if (customerTypeValue != null && customerTypeValue.Type != JTokenType.Null)
{
string customerTypeInstance = ((string)customerTypeValue);
propertiesInstance.CustomerType = customerTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
marsContainerResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
marsContainerResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
marsContainerResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
listMarsContainerResponseInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
listMarsContainerResponseInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
listMarsContainerResponseInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
listMarsContainerResponseInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister the container.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public async Task<OperationResponse> UnregisterMarsContainerAsync(string resourceGroupName, string resourceName, string containerId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (containerId == null)
{
throw new ArgumentNullException("containerId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("containerId", containerId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "UnregisterMarsContainerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/backupContainers/";
url = url + Uri.EscapeDataString(containerId);
url = url + "/UnRegisterContainer";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Guid operationIdInstance = Guid.Parse(((string)responseDoc));
result.OperationId = operationIdInstance;
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618 // deprecated SpringConfigUrl
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Lifecycle;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Grid configuration.
/// </summary>
public class IgniteConfiguration
{
/// <summary>
/// Default initial JVM memory in megabytes.
/// </summary>
public const int DefaultJvmInitMem = 512;
/// <summary>
/// Default maximum JVM memory in megabytes.
/// </summary>
public const int DefaultJvmMaxMem = 1024;
/// <summary>
/// Default metrics expire time.
/// </summary>
public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue;
/// <summary>
/// Default metrics history size.
/// </summary>
public const int DefaultMetricsHistorySize = 10000;
/// <summary>
/// Default metrics log frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000);
/// <summary>
/// Default metrics update frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000);
/// <summary>
/// Default network timeout.
/// </summary>
public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000);
/// <summary>
/// Default network retry delay.
/// </summary>
public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000);
/// <summary>
/// Default network retry count.
/// </summary>
public const int DefaultNetworkSendRetryCount = 3;
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
public IgniteConfiguration()
{
JvmInitialMemoryMb = DefaultJvmInitMem;
JvmMaxMemoryMb = DefaultJvmMaxMem;
MetricsExpireTime = DefaultMetricsExpireTime;
MetricsHistorySize = DefaultMetricsHistorySize;
MetricsLogFrequency = DefaultMetricsLogFrequency;
MetricsUpdateFrequency = DefaultMetricsUpdateFrequency;
NetworkTimeout = DefaultNetworkTimeout;
NetworkSendRetryCount = DefaultNetworkSendRetryCount;
NetworkSendRetryDelay = DefaultNetworkSendRetryDelay;
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
/// <param name="configuration">The configuration to copy.</param>
public IgniteConfiguration(IgniteConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
CopyLocalProperties(configuration);
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var marsh = new Marshaller(configuration.BinaryConfiguration);
configuration.WriteCore(marsh.StartMarshal(stream));
stream.SynchronizeOutput();
stream.Seek(0, SeekOrigin.Begin);
ReadCore(marsh.StartUnmarshal(stream));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class from a reader.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
internal IgniteConfiguration(BinaryReader binaryReader)
{
Read(binaryReader);
}
/// <summary>
/// Writes this instance to a writer.
/// </summary>
/// <param name="writer">The writer.</param>
internal void Write(BinaryWriter writer)
{
Debug.Assert(writer != null);
if (!string.IsNullOrEmpty(SpringConfigUrl))
{
// Do not write details when there is Spring config.
writer.WriteBoolean(false);
return;
}
writer.WriteBoolean(true); // details are present
WriteCore(writer);
}
/// <summary>
/// Writes this instance to a writer.
/// </summary>
/// <param name="writer">The writer.</param>
private void WriteCore(BinaryWriter writer)
{
// Simple properties
writer.WriteBoolean(ClientMode);
writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray());
writer.WriteLong((long) MetricsExpireTime.TotalMilliseconds);
writer.WriteInt(MetricsHistorySize);
writer.WriteLong((long) MetricsLogFrequency.TotalMilliseconds);
var metricsUpdateFreq = (long) MetricsUpdateFrequency.TotalMilliseconds;
writer.WriteLong(metricsUpdateFreq >= 0 ? metricsUpdateFreq : -1);
writer.WriteInt(NetworkSendRetryCount);
writer.WriteLong((long) NetworkSendRetryDelay.TotalMilliseconds);
writer.WriteLong((long) NetworkTimeout.TotalMilliseconds);
writer.WriteString(WorkDirectory);
writer.WriteString(Localhost);
// Cache config
var caches = CacheConfiguration;
if (caches == null)
writer.WriteInt(0);
else
{
writer.WriteInt(caches.Count);
foreach (var cache in caches)
cache.Write(writer);
}
// Discovery config
var disco = DiscoverySpi;
if (disco != null)
{
writer.WriteBoolean(true);
var tcpDisco = disco as TcpDiscoverySpi;
if (tcpDisco == null)
throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType());
tcpDisco.Write(writer);
}
else
writer.WriteBoolean(false);
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="r">The binary reader.</param>
private void ReadCore(BinaryReader r)
{
// Simple properties
ClientMode = r.ReadBoolean();
IncludedEventTypes = r.ReadIntArray();
MetricsExpireTime = r.ReadLongAsTimespan();
MetricsHistorySize = r.ReadInt();
MetricsLogFrequency = r.ReadLongAsTimespan();
MetricsUpdateFrequency = r.ReadLongAsTimespan();
NetworkSendRetryCount = r.ReadInt();
NetworkSendRetryDelay = r.ReadLongAsTimespan();
NetworkTimeout = r.ReadLongAsTimespan();
WorkDirectory = r.ReadString();
Localhost = r.ReadString();
// Cache config
var cacheCfgCount = r.ReadInt();
CacheConfiguration = new List<CacheConfiguration>(cacheCfgCount);
for (int i = 0; i < cacheCfgCount; i++)
CacheConfiguration.Add(new CacheConfiguration(r));
// Discovery config
DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null;
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
private void Read(BinaryReader binaryReader)
{
var r = binaryReader;
CopyLocalProperties(r.Marshaller.Ignite.Configuration);
ReadCore(r);
// Misc
IgniteHome = r.ReadString();
JvmInitialMemoryMb = (int) (r.ReadLong()/1024/2014);
JvmMaxMemoryMb = (int) (r.ReadLong()/1024/2014);
// Local data (not from reader)
JvmDllPath = Process.GetCurrentProcess().Modules.OfType<ProcessModule>()
.Single(x => string.Equals(x.ModuleName, IgniteUtils.FileJvmDll, StringComparison.OrdinalIgnoreCase))
.FileName;
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
private void CopyLocalProperties(IgniteConfiguration cfg)
{
GridName = cfg.GridName;
BinaryConfiguration = cfg.BinaryConfiguration == null
? null
: new BinaryConfiguration(cfg.BinaryConfiguration);
JvmClasspath = cfg.JvmClasspath;
JvmOptions = cfg.JvmOptions;
Assemblies = cfg.Assemblies;
SuppressWarnings = cfg.SuppressWarnings;
LifecycleBeans = cfg.LifecycleBeans;
}
/// <summary>
/// Grid name which is used if not provided in configuration file.
/// </summary>
public string GridName { get; set; }
/// <summary>
/// Gets or sets the binary configuration.
/// </summary>
/// <value>
/// The binary configuration.
/// </value>
public BinaryConfiguration BinaryConfiguration { get; set; }
/// <summary>
/// Gets or sets the cache configuration.
/// </summary>
/// <value>
/// The cache configuration.
/// </value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<CacheConfiguration> CacheConfiguration { get; set; }
/// <summary>
/// URL to Spring configuration file.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
[Obsolete("Ignite.NET can be configured natively without Spring. " +
"Setting this property will ignore all other properties except " +
"IgniteHome, Assemblies, SuppressWarnings, LifecycleBeans, JvmOptions, JvmdllPath, IgniteHome, " +
"JvmInitialMemoryMb, JvmMaxMemoryMb.")]
public string SpringConfigUrl { get; set; }
/// <summary>
/// Path jvm.dll file. If not set, it's location will be determined
/// using JAVA_HOME environment variable.
/// If path is neither set nor determined automatically, an exception
/// will be thrown.
/// </summary>
public string JvmDllPath { get; set; }
/// <summary>
/// Path to Ignite home. If not set environment variable IGNITE_HOME will be used.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Classpath used by JVM on Ignite start.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// Collection of options passed to JVM on Ignite start.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// List of additional .Net assemblies to load on Ignite start. Each item can be either
/// fully qualified assembly name, path to assembly to DLL or path to a directory when
/// assemblies reside.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Whether to suppress warnings.
/// </summary>
public bool SuppressWarnings { get; set; }
/// <summary>
/// Lifecycle beans.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<ILifecycleBean> LifecycleBeans { get; set; }
/// <summary>
/// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option.
/// Defaults to <see cref="DefaultJvmInitMem"/>.
/// </summary>
[DefaultValue(DefaultJvmInitMem)]
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option.
/// Defaults to <see cref="DefaultJvmMaxMem"/>.
/// </summary>
[DefaultValue(DefaultJvmMaxMem)]
public int JvmMaxMemoryMb { get; set; }
/// <summary>
/// Gets or sets the discovery service provider.
/// Null for default discovery.
/// </summary>
public IDiscoverySpi DiscoverySpi { get; set; }
/// <summary>
/// Gets or sets a value indicating whether node should start in client mode.
/// Client node cannot hold data in the caches.
/// Default is null and takes this setting from Spring configuration.
/// </summary>
public bool ClientMode { get; set; }
/// <summary>
/// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<int> IncludedEventTypes { get; set; }
/// <summary>
/// Gets or sets the time after which a certain metric value is considered expired.
/// </summary>
[DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")]
public TimeSpan MetricsExpireTime { get; set; }
/// <summary>
/// Gets or sets the number of metrics kept in history to compute totals and averages.
/// </summary>
[DefaultValue(DefaultMetricsHistorySize)]
public int MetricsHistorySize { get; set; }
/// <summary>
/// Gets or sets the frequency of metrics log print out.
/// <see cref="TimeSpan.Zero"/> to disable metrics print out.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:01:00")]
public TimeSpan MetricsLogFrequency { get; set; }
/// <summary>
/// Gets or sets the job metrics update frequency.
/// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish.
/// Negative value to never update metrics.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:02")]
public TimeSpan MetricsUpdateFrequency { get; set; }
/// <summary>
/// Gets or sets the network send retry count.
/// </summary>
[DefaultValue(DefaultNetworkSendRetryCount)]
public int NetworkSendRetryCount { get; set; }
/// <summary>
/// Gets or sets the network send retry delay.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:01")]
public TimeSpan NetworkSendRetryDelay { get; set; }
/// <summary>
/// Gets or sets the network timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:05")]
public TimeSpan NetworkTimeout { get; set; }
/// <summary>
/// Gets or sets the work directory.
/// If not provided, a folder under <see cref="IgniteHome"/> will be used.
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Gets or sets system-wide local address or host for all Ignite components to bind to.
/// If provided it will override all default local bind settings within Ignite.
/// <para />
/// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services
/// will be available on all network interfaces of the host machine.
/// <para />
/// It is strongly recommended to set this parameter for all production environments.
/// </summary>
public string Localhost { get; set; }
}
}
| |
/*
* 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.Timers;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public class SimStatsReporter
{
public delegate void SendStatResult(SimStats stats);
public delegate void YourStatsAreWrong();
public event SendStatResult OnSendStatsResult;
public event YourStatsAreWrong OnStatsIncorrect;
private SendStatResult handlerSendStatResult = null;
private YourStatsAreWrong handlerStatsIncorrect = null;
private enum Stats : uint
{
TimeDilation = 0,
SimFPS = 1,
PhysicsFPS = 2,
AgentUpdates = 3,
FrameMS = 4,
NetMS = 5,
OtherMS = 6,
PhysicsMS = 7,
AgentMS = 8,
ImageMS = 9,
ScriptMS = 10,
TotalPrim = 11,
ActivePrim = 12,
Agents = 13,
ChildAgents = 14,
ActiveScripts = 15,
ScriptLinesPerSecond = 16,
InPacketsPerSecond = 17,
OutPacketsPerSecond = 18,
PendingDownloads = 19,
PendingUploads = 20,
UnAckedBytes = 24,
}
// Sending a stats update every 3 seconds-
private int statsUpdatesEveryMS = 3000;
private float statsUpdateFactor = 0;
private float m_timeDilation = 0;
private int m_fps = 0;
// saved last reported value so there is something available for llGetRegionFPS
private float lastReportedSimFPS = 0;
private float[] lastReportedSimStats = new float[21];
private float m_pfps = 0;
private int m_agentUpdates = 0;
private int m_frameMS = 0;
private int m_netMS = 0;
private int m_agentMS = 0;
private int m_physicsMS = 0;
private int m_imageMS = 0;
private int m_otherMS = 0;
//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
//Ckrinke private int m_scriptMS = 0;
private int m_rootAgents = 0;
private int m_childAgents = 0;
private int m_numPrim = 0;
private int m_inPacketsPerSecond = 0;
private int m_outPacketsPerSecond = 0;
private int m_activePrim = 0;
private int m_unAckedBytes = 0;
private int m_pendingDownloads = 0;
private int m_pendingUploads = 0;
private int m_activeScripts = 0;
private int m_scriptLinesPerSecond = 0;
private int objectCapacity = 45000;
private Scene m_scene;
private RegionInfo ReportingRegion;
private Timer m_report = new Timer();
private IEstateModule estateModule;
public SimStatsReporter(Scene scene)
{
statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000);
m_scene = scene;
ReportingRegion = scene.RegionInfo;
m_report.AutoReset = true;
m_report.Interval = statsUpdatesEveryMS;
m_report.Elapsed += new ElapsedEventHandler(statsHeartBeat);
m_report.Enabled = true;
if (StatsManager.SimExtraStats != null)
OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket;
}
public void SetUpdateMS(int ms)
{
statsUpdatesEveryMS = ms;
statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000);
m_report.Interval = statsUpdatesEveryMS;
}
private void statsHeartBeat(object sender, EventArgs e)
{
SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[21];
SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
// Know what's not thread safe in Mono... modifying timers.
// m_log.Debug("Firing Stats Heart Beat");
lock (m_report)
{
uint regionFlags = 0;
try
{
if (estateModule == null)
estateModule = m_scene.RequestModuleInterface<IEstateModule>();
regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0;
}
catch (Exception)
{
// leave region flags at 0
}
#region various statistic googly moogly
// Our FPS is actually 10fps, so multiplying by 5 to get the amount that people expect there
// 0-50 is pretty close to 0-45
float simfps = (int) ((m_fps * 5));
// save the reported value so there is something available for llGetRegionFPS
lastReportedSimFPS = (float)simfps / statsUpdateFactor;
//if (simfps > 45)
//simfps = simfps - (simfps - 45);
//if (simfps < 0)
//simfps = 0;
//
float physfps = ((m_pfps / 1000));
//if (physfps > 600)
//physfps = physfps - (physfps - 600);
if (physfps < 0)
physfps = 0;
#endregion
//Our time dilation is 0.91 when we're running a full speed,
// therefore to make sure we get an appropriate range,
// we have to factor in our error. (0.10f * statsUpdateFactor)
// multiplies the fix for the error times the amount of times it'll occur a second
// / 10 divides the value by the number of times the sim heartbeat runs (10fps)
// Then we divide the whole amount by the amount of seconds pass in between stats updates.
// 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
// values to X-per-second values.
for (int i = 0; i<21;i++)
{
sb[i] = new SimStatsPacket.StatBlock();
}
sb[0].StatID = (uint) Stats.TimeDilation;
sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor));
sb[1].StatID = (uint) Stats.SimFPS;
sb[1].StatValue = simfps/statsUpdateFactor;
sb[2].StatID = (uint) Stats.PhysicsFPS;
sb[2].StatValue = physfps / statsUpdateFactor;
sb[3].StatID = (uint) Stats.AgentUpdates;
sb[3].StatValue = (m_agentUpdates / statsUpdateFactor);
sb[4].StatID = (uint) Stats.Agents;
sb[4].StatValue = m_rootAgents;
sb[5].StatID = (uint) Stats.ChildAgents;
sb[5].StatValue = m_childAgents;
sb[6].StatID = (uint) Stats.TotalPrim;
sb[6].StatValue = m_numPrim;
sb[7].StatID = (uint) Stats.ActivePrim;
sb[7].StatValue = m_activePrim;
sb[8].StatID = (uint)Stats.FrameMS;
sb[8].StatValue = m_frameMS / statsUpdateFactor;
sb[9].StatID = (uint)Stats.NetMS;
sb[9].StatValue = m_netMS / statsUpdateFactor;
sb[10].StatID = (uint)Stats.PhysicsMS;
sb[10].StatValue = m_physicsMS / statsUpdateFactor;
sb[11].StatID = (uint)Stats.ImageMS ;
sb[11].StatValue = m_imageMS / statsUpdateFactor;
sb[12].StatID = (uint)Stats.OtherMS;
sb[12].StatValue = m_otherMS / statsUpdateFactor;
sb[13].StatID = (uint)Stats.InPacketsPerSecond;
sb[13].StatValue = (m_inPacketsPerSecond / statsUpdateFactor);
sb[14].StatID = (uint)Stats.OutPacketsPerSecond;
sb[14].StatValue = (m_outPacketsPerSecond / statsUpdateFactor);
sb[15].StatID = (uint)Stats.UnAckedBytes;
sb[15].StatValue = m_unAckedBytes;
sb[16].StatID = (uint)Stats.AgentMS;
sb[16].StatValue = m_agentMS / statsUpdateFactor;
sb[17].StatID = (uint)Stats.PendingDownloads;
sb[17].StatValue = m_pendingDownloads;
sb[18].StatID = (uint)Stats.PendingUploads;
sb[18].StatValue = m_pendingUploads;
sb[19].StatID = (uint)Stats.ActiveScripts;
sb[19].StatValue = m_activeScripts;
sb[20].StatID = (uint)Stats.ScriptLinesPerSecond;
sb[20].StatValue = m_scriptLinesPerSecond / statsUpdateFactor;
for (int i = 0; i < 21; i++)
{
lastReportedSimStats[i] = sb[i].StatValue;
}
SimStats simStats
= new SimStats(
ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)objectCapacity, rb, sb, m_scene.RegionInfo.originRegionID);
handlerSendStatResult = OnSendStatsResult;
if (handlerSendStatResult != null)
{
handlerSendStatResult(simStats);
}
resetvalues();
}
}
private void resetvalues()
{
m_timeDilation = 0;
m_fps = 0;
m_pfps = 0;
m_agentUpdates = 0;
//m_inPacketsPerSecond = 0;
//m_outPacketsPerSecond = 0;
m_unAckedBytes = 0;
m_scriptLinesPerSecond = 0;
m_frameMS = 0;
m_agentMS = 0;
m_netMS = 0;
m_physicsMS = 0;
m_imageMS = 0;
m_otherMS = 0;
//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
//Ckrinke m_scriptMS = 0;
}
# region methods called from Scene
// The majority of these functions are additive
// so that you can easily change the amount of
// seconds in between sim stats updates
public void AddTimeDilation(float td)
{
//float tdsetting = td;
//if (tdsetting > 1.0f)
//tdsetting = (tdsetting - (tdsetting - 0.91f));
//if (tdsetting < 0)
//tdsetting = 0.0f;
m_timeDilation = td;
}
public void SetRootAgents(int rootAgents)
{
m_rootAgents = rootAgents;
CheckStatSanity();
}
internal void CheckStatSanity()
{
if (m_rootAgents < 0 || m_childAgents < 0)
{
handlerStatsIncorrect = OnStatsIncorrect;
if (handlerStatsIncorrect != null)
{
handlerStatsIncorrect();
}
}
if (m_rootAgents == 0 && m_childAgents == 0)
{
m_unAckedBytes = 0;
}
}
public void SetChildAgents(int childAgents)
{
m_childAgents = childAgents;
CheckStatSanity();
}
public void SetObjects(int objects)
{
m_numPrim = objects;
}
public void SetActiveObjects(int objects)
{
m_activePrim = objects;
}
public void AddFPS(int frames)
{
m_fps += frames;
}
public void AddPhysicsFPS(float frames)
{
m_pfps += frames;
}
public void AddAgentUpdates(int numUpdates)
{
m_agentUpdates += numUpdates;
}
public void AddInPackets(int numPackets)
{
m_inPacketsPerSecond = numPackets;
}
public void AddOutPackets(int numPackets)
{
m_outPacketsPerSecond = numPackets;
}
public void AddunAckedBytes(int numBytes)
{
m_unAckedBytes += numBytes;
if (m_unAckedBytes < 0) m_unAckedBytes = 0;
}
public void addFrameMS(int ms)
{
m_frameMS += ms;
}
public void addNetMS(int ms)
{
m_netMS += ms;
}
public void addAgentMS(int ms)
{
m_agentMS += ms;
}
public void addPhysicsMS(int ms)
{
m_physicsMS += ms;
}
public void addImageMS(int ms)
{
m_imageMS += ms;
}
public void addOtherMS(int ms)
{
m_otherMS += ms;
}
// private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void AddPendingDownloads(int count)
{
m_pendingDownloads += count;
if (m_pendingDownloads < 0) m_pendingDownloads = 0;
//m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads);
}
public void addScriptLines(int count)
{
m_scriptLinesPerSecond += count;
}
public void SetActiveScripts(int count)
{
m_activeScripts = count;
}
public void SetObjectCapacity(int objects)
{
objectCapacity = objects;
}
/// <summary>
/// This is for llGetRegionFPS
/// </summary>
public float getLastReportedSimFPS()
{
return lastReportedSimFPS;
}
public float[] getLastReportedSimStats()
{
return lastReportedSimStats;
}
public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes)
{
AddInPackets(inPackets);
AddOutPackets(outPackets);
AddunAckedBytes(unAckedBytes);
}
public void AddAgentTime(int ms)
{
addFrameMS(ms);
addAgentMS(ms);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System;
using System.Data.SqlTypes;
using System.Diagnostics;
namespace Microsoft.SqlServer.Server
{
// Class for implementing a record object used in out-of-proc scenarios.
internal sealed class MemoryRecordBuffer : SmiRecordBuffer
{
private SqlRecordBuffer[] _buffer;
internal MemoryRecordBuffer(SmiMetaData[] metaData)
{
Debug.Assert(null != metaData, "invalid attempt to instantiate MemoryRecordBuffer with null SmiMetaData[]");
_buffer = new SqlRecordBuffer[metaData.Length];
for (int i = 0; i < _buffer.Length; ++i)
{
_buffer[i] = new SqlRecordBuffer(metaData[i]);
}
}
#region Getters
// Null test
// valid for all types
public override bool IsDBNull(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].IsNull;
}
// Check what type current sql_variant value is
// valid for SqlDbType.Variant
public override SmiMetaData GetVariantType(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].VariantType;
}
// valid for SqlDbType.Bit
public override Boolean GetBoolean(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Boolean;
}
// valid for SqlDbType.TinyInt
public override Byte GetByte(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Byte;
}
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
// (Character type support needed for ExecuteXmlReader handling)
public override Int64 GetBytesLength(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].BytesLength;
}
public override int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
return _buffer[ordinal].GetBytes(fieldOffset, buffer, bufferOffset, length);
}
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
public override Int64 GetCharsLength(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].CharsLength;
}
public override int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
return _buffer[ordinal].GetChars(fieldOffset, buffer, bufferOffset, length);
}
public override String GetString(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].String;
}
// valid for SqlDbType.SmallInt
public override Int16 GetInt16(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Int16;
}
// valid for SqlDbType.Int
public override Int32 GetInt32(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Int32;
}
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
public override Int64 GetInt64(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Int64;
}
// valid for SqlDbType.Real
public override Single GetSingle(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Single;
}
// valid for SqlDbType.Float
public override Double GetDouble(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Double;
}
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
public override SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].SqlDecimal;
}
// valid for DateTime, SmallDateTime, Date, and DateTime2
public override DateTime GetDateTime(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].DateTime;
}
// valid for UniqueIdentifier
public override Guid GetGuid(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].Guid;
}
// valid for SqlDbType.Time
public override TimeSpan GetTimeSpan(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].TimeSpan;
}
// valid for DateTimeOffset
public override DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal)
{
return _buffer[ordinal].DateTimeOffset;
}
#endregion
#region Setters
// Set value to null
// valid for all types
public override void SetDBNull(SmiEventSink sink, int ordinal)
{
_buffer[ordinal].SetNull();
}
// valid for SqlDbType.Bit
public override void SetBoolean(SmiEventSink sink, int ordinal, Boolean value)
{
_buffer[ordinal].Boolean = value;
}
// valid for SqlDbType.TinyInt
public override void SetByte(SmiEventSink sink, int ordinal, Byte value)
{
_buffer[ordinal].Byte = value;
}
// Semantics for SetBytes are to modify existing value, not overwrite
// Use in combination with SetLength to ensure overwriting when necessary
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
// (VarBinary assumed for variants)
public override int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
return _buffer[ordinal].SetBytes(fieldOffset, buffer, bufferOffset, length);
}
public override void SetBytesLength(SmiEventSink sink, int ordinal, long length)
{
_buffer[ordinal].BytesLength = length;
}
// Semantics for SetChars are to modify existing value, not overwrite
// Use in combination with SetLength to ensure overwriting when necessary
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
// (NVarChar and global clr collation assumed for variants)
public override int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
return _buffer[ordinal].SetChars(fieldOffset, buffer, bufferOffset, length);
}
public override void SetCharsLength(SmiEventSink sink, int ordinal, long length)
{
_buffer[ordinal].CharsLength = length;
}
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
public override void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length)
{
Debug.Assert(offset == 0 && length <= value.Length, "Invalid string length or offset"); // for sqlvariant, length could be less than value.Length
_buffer[ordinal].String = value.Substring(offset, length); // Perf test shows that Substring method has already optimized the case where length = value.Length
}
// valid for SqlDbType.SmallInt
public override void SetInt16(SmiEventSink sink, int ordinal, Int16 value)
{
_buffer[ordinal].Int16 = value;
}
// valid for SqlDbType.Int
public override void SetInt32(SmiEventSink sink, int ordinal, Int32 value)
{
_buffer[ordinal].Int32 = value;
}
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
public override void SetInt64(SmiEventSink sink, int ordinal, Int64 value)
{
_buffer[ordinal].Int64 = value;
}
// valid for SqlDbType.Real
public override void SetSingle(SmiEventSink sink, int ordinal, Single value)
{
_buffer[ordinal].Single = value;
}
// valid for SqlDbType.Float
public override void SetDouble(SmiEventSink sink, int ordinal, Double value)
{
_buffer[ordinal].Double = value;
}
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
public override void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value)
{
_buffer[ordinal].SqlDecimal = value;
}
// valid for DateTime, SmallDateTime, Date, and DateTime2
public override void SetDateTime(SmiEventSink sink, int ordinal, DateTime value)
{
_buffer[ordinal].DateTime = value;
}
// valid for UniqueIdentifier
public override void SetGuid(SmiEventSink sink, int ordinal, Guid value)
{
_buffer[ordinal].Guid = value;
}
// SqlDbType.Time
public override void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value)
{
_buffer[ordinal].TimeSpan = value;
}
// DateTimeOffset
public override void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value)
{
_buffer[ordinal].DateTimeOffset = value;
}
// valid for SqlDbType.Variant
public override void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData)
{
_buffer[ordinal].VariantType = metaData;
}
#endregion
}
}
| |
/* 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 XenAdmin.Network;
using XenAPI;
using XenAdmin.Core;
using System.Xml;
namespace XenAdmin.CustomFields
{
/// <summary>
/// Provide custom fields management support for VMs. The coordinator list of custom fields will be
/// maintained in the pool class using the same conventions as the tags implementation (see
/// XenAdmin.XenSearch.Tags). When persisting the label-value pairs in the VMs, the
/// following key/value convention will be used:
/// "XenCenter.CustomFields.foo1" value
/// "XenCenter.CustomFields.foo2" value
/// </summary>
public class CustomFieldsManager
{
#region These functions deal with caching the list of custom fields
private static readonly CustomFieldsCache customFieldsCache = new CustomFieldsCache();
private const String CUSTOM_FIELD_DELIM = ".";
public const String CUSTOM_FIELD_BASE_KEY = "XenCenter.CustomFields";
public const String CUSTOM_FIELD = "CustomField:";
public static event Action CustomFieldsChanged;
static CustomFieldsManager()
{
OtherConfigAndTagsWatcher.GuiConfigChanged += OtherConfigAndTagsWatcher_GuiConfigChanged;
}
private static void OtherConfigAndTagsWatcher_GuiConfigChanged()
{
InvokeHelper.AssertOnEventThread();
customFieldsCache.RecalculateCustomFields();
OnCustomFieldsChanged();
}
private static void OnCustomFieldsChanged()
{
Action handler = CustomFieldsChanged;
if (handler != null)
{
handler();
}
}
#endregion
#region These functions deal with custom field definitions on the pool object
public static List<CustomFieldDefinition> GetCustomFields()
{
return customFieldsCache.GetCustomFields();
}
public static List<CustomFieldDefinition> GetCustomFields(IXenConnection connection)
{
return customFieldsCache.GetCustomFields(connection);
}
/// <returns>The CustomFieldDefinition with the given name, or null if none is found.</returns>
public static CustomFieldDefinition GetCustomFieldDefinition(string name)
{
foreach (CustomFieldDefinition d in GetCustomFields())
{
if (d.Name == name)
return d;
}
return null;
}
public static void RemoveCustomField(Session session, IXenConnection connection, CustomFieldDefinition definition)
{
List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection);
if (customFields.Remove(definition))
{
SaveCustomFields(session, connection, customFields);
// Remove from all Objects
RemoveCustomFieldsFrom(session, connection.Cache.VMs, definition);
RemoveCustomFieldsFrom(session, connection.Cache.Hosts, definition);
RemoveCustomFieldsFrom(session, connection.Cache.Pools, definition);
RemoveCustomFieldsFrom(session, connection.Cache.SRs, definition);
}
}
public static void AddCustomField(Session session, IXenConnection connection, CustomFieldDefinition customField)
{
List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection);
if (!customFields.Contains(customField))
{
customFields.Add(customField);
SaveCustomFields(session, connection, customFields);
}
}
private static String GetCustomFieldDefinitionXML(List<CustomFieldDefinition> customFieldDefinitions)
{
XmlDocument doc = new XmlDocument();
XmlNode parentNode = doc.CreateElement("CustomFieldDefinitions");
doc.AppendChild(parentNode);
foreach (CustomFieldDefinition customFieldDefinition in customFieldDefinitions)
{
parentNode.AppendChild(customFieldDefinition.ToXmlNode(doc));
}
return doc.OuterXml;
}
#endregion
#region These functions deal with the custom fields themselves
public static string GetCustomFieldKey(CustomFieldDefinition customFieldDefinition)
{
return CUSTOM_FIELD_BASE_KEY + CUSTOM_FIELD_DELIM + customFieldDefinition.Name;
}
private static void RemoveCustomFieldsFrom(Session session, IEnumerable<IXenObject> os, CustomFieldDefinition customFieldDefinition)
{
InvokeHelper.AssertOffEventThread();
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
foreach (IXenObject o in os)
{
Helpers.RemoveFromOtherConfig(session, o, customFieldKey);
}
}
private static void SaveCustomFields(Session session, IXenConnection connection, List<CustomFieldDefinition> customFields)
{
Pool pool = Helpers.GetPoolOfOne(connection);
if (pool != null)
{
String customFieldXML = GetCustomFieldDefinitionXML(customFields);
Helpers.SetGuiConfig(session, pool, CUSTOM_FIELD_BASE_KEY, customFieldXML);
}
}
public static List<CustomField> CustomFieldValues(IXenObject o)
{
//Program.AssertOnEventThread();
List<CustomField> customFields = new List<CustomField>();
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig != null)
{
foreach (CustomFieldDefinition customFieldDefinition in customFieldsCache.GetCustomFields(o.Connection))
{
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
if (!otherConfig.ContainsKey(customFieldKey) || otherConfig[customFieldKey] == String.Empty)
{
continue;
}
object value = ParseValue(customFieldDefinition.Type, otherConfig[customFieldKey]);
if (value != null)
{
customFields.Add(new CustomField(customFieldDefinition, value));
}
}
}
return customFields;
}
// The same as CustomFieldValues(), but with each custom field unwound into an array
public static List<object[]> CustomFieldArrays(IXenObject o)
{
List<object[]> ans = new List<object[]>();
foreach (CustomField cf in CustomFieldValues(o))
{
ans.Add(cf.ToArray());
}
return ans;
}
// Whether the object has any custom fields defined
public static bool HasCustomFields(IXenObject o)
{
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig != null)
{
foreach (CustomFieldDefinition customFieldDefinition in GetCustomFields(o.Connection))
{
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
if (otherConfig.ContainsKey(customFieldKey) && otherConfig[customFieldKey] != String.Empty)
{
return true;
}
}
}
return false;
}
public static Object GetCustomFieldValue(IXenObject o, CustomFieldDefinition customFieldDefinition)
{
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig == null)
return null;
String key = GetCustomFieldKey(customFieldDefinition);
if (!otherConfig.ContainsKey(key))
return null;
String value = otherConfig[key];
if (value == String.Empty)
return null;
return ParseValue(customFieldDefinition.Type, value);
}
private static object ParseValue(CustomFieldDefinition.Types type, string value)
{
switch (type)
{
case CustomFieldDefinition.Types.Date:
DateTime datetime;
if (DateTime.TryParse(value, out datetime))
return datetime;
return null;
case CustomFieldDefinition.Types.String:
return value;
default:
return null;
}
}
private static Dictionary<string, string> GetOtherConfigCopy(IXenObject o)
{
Dictionary<string, string> output = new Dictionary<string, string>();
InvokeHelper.Invoke(delegate()
{
Dictionary<String, String> otherConfig = Helpers.GetOtherConfig(o);
if (otherConfig == null)
{
output = null;
}
else
{
output = new Dictionary<string, string>(otherConfig);
}
});
return output;
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.IO.Pipes.PipeStream.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.IO.Pipes
{
abstract public partial class PipeStream : Stream
{
#region Methods and constructors
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
return default(IAsyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
return default(IAsyncResult);
}
protected internal virtual new void CheckPipePropertyOperations()
{
}
protected internal void CheckReadOperations()
{
}
protected internal void CheckWriteOperations()
{
}
protected override void Dispose(bool disposing)
{
}
public override int EndRead(IAsyncResult asyncResult)
{
return default(int);
}
public override void EndWrite(IAsyncResult asyncResult)
{
}
public override void Flush()
{
}
public PipeSecurity GetAccessControl()
{
Contract.Ensures(Contract.Result<System.IO.Pipes.PipeSecurity>() != null);
return default(PipeSecurity);
}
protected void InitializeHandle(Microsoft.Win32.SafeHandles.SafePipeHandle handle, bool isExposed, bool isAsync)
{
}
protected PipeStream(PipeDirection direction, int bufferSize)
{
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
}
public override int Read(byte[] buffer, int offset, int count)
{
return default(int);
}
public override int ReadByte()
{
return default(int);
}
public override long Seek(long offset, SeekOrigin origin)
{
return default(long);
}
public void SetAccessControl(PipeSecurity pipeSecurity)
{
}
public override void SetLength(long value)
{
}
public void WaitForPipeDrain()
{
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override void WriteByte(byte value)
{
}
#endregion
#region Properties and indexers
public override bool CanRead
{
get
{
return default(bool);
}
}
public override bool CanSeek
{
get
{
return default(bool);
}
}
public override bool CanWrite
{
get
{
return default(bool);
}
}
public virtual new int InBufferSize
{
get
{
return default(int);
}
}
public bool IsAsync
{
get
{
return default(bool);
}
}
public bool IsConnected
{
get
{
return default(bool);
}
protected set
{
}
}
protected bool IsHandleExposed
{
get
{
return default(bool);
}
}
public bool IsMessageComplete
{
get
{
return default(bool);
}
}
public override long Length
{
get
{
return default(long);
}
}
public virtual new int OutBufferSize
{
get
{
return default(int);
}
}
public override long Position
{
get
{
return default(long);
}
set
{
}
}
public virtual new PipeTransmissionMode ReadMode
{
get
{
return default(PipeTransmissionMode);
}
set
{
}
}
public Microsoft.Win32.SafeHandles.SafePipeHandle SafePipeHandle
{
get
{
Contract.Ensures(Contract.Result<Microsoft.Win32.SafeHandles.SafePipeHandle>() != null);
return default(Microsoft.Win32.SafeHandles.SafePipeHandle);
}
}
public virtual new PipeTransmissionMode TransmissionMode
{
get
{
return default(PipeTransmissionMode);
}
}
#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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Specifies details of a Job Manager task.
/// </summary>
/// <remarks>
/// The Job Manager task is automatically started when the job is created.
/// The Batch service tries to schedule the Job Manager task before any
/// other tasks in the job. When shrinking a pool, the Batch service tries
/// to preserve compute nodes where Job Manager tasks are running for as
/// long as possible (that is, nodes running 'normal' tasks are removed
/// before nodes running Job Manager tasks). When a Job Manager task fails
/// and needs to be restarted, the system tries to schedule it at the
/// highest priority. If there are no idle nodes available, the system may
/// terminate one of the running tasks in the pool and return it to the
/// queue in order to make room for the Job Manager task to restart. Note
/// that a Job Manager task in one job does not have priority over tasks in
/// other jobs. Across jobs, only job level priorities are observed. For
/// example, if a Job Manager in a priority 0 job needs to be restarted, it
/// will not displace tasks of a priority 1 job.
/// </remarks>
public partial class JobManagerTask
{
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
public JobManagerTask()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
/// <param name="id">A string that uniquely identifies the Job Manager
/// task within the job.</param>
/// <param name="commandLine">The command line of the Job Manager
/// task.</param>
/// <param name="displayName">The display name of the Job Manager
/// task.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="outputFiles">A list of files that the Batch service
/// will upload from the compute node after running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the Job Manager task.</param>
/// <param name="constraints">Constraints that apply to the Job Manager
/// task.</param>
/// <param name="killJobOnCompletion">Whether completion of the Job
/// Manager task signifies completion of the entire job.</param>
/// <param name="userIdentity">The user identity under which the Job
/// Manager task runs.</param>
/// <param name="runExclusive">Whether the Job Manager task requires
/// exclusive use of the compute node where it runs.</param>
/// <param name="applicationPackageReferences">A list of application
/// packages that the Batch service will deploy to the compute node
/// before running the command line.</param>
/// <param name="authenticationTokenSettings">The settings for an
/// authentication token that the task can use to perform Batch service
/// operations.</param>
/// <param name="allowLowPriorityNode">Whether the Job Manager task may
/// run on a low-priority compute node.</param>
public JobManagerTask(string id, string commandLine, string displayName = default(string), IList<ResourceFile> resourceFiles = default(IList<ResourceFile>), IList<OutputFile> outputFiles = default(IList<OutputFile>), IList<EnvironmentSetting> environmentSettings = default(IList<EnvironmentSetting>), TaskConstraints constraints = default(TaskConstraints), bool? killJobOnCompletion = default(bool?), UserIdentity userIdentity = default(UserIdentity), bool? runExclusive = default(bool?), IList<ApplicationPackageReference> applicationPackageReferences = default(IList<ApplicationPackageReference>), AuthenticationTokenSettings authenticationTokenSettings = default(AuthenticationTokenSettings), bool? allowLowPriorityNode = default(bool?))
{
Id = id;
DisplayName = displayName;
CommandLine = commandLine;
ResourceFiles = resourceFiles;
OutputFiles = outputFiles;
EnvironmentSettings = environmentSettings;
Constraints = constraints;
KillJobOnCompletion = killJobOnCompletion;
UserIdentity = userIdentity;
RunExclusive = runExclusive;
ApplicationPackageReferences = applicationPackageReferences;
AuthenticationTokenSettings = authenticationTokenSettings;
AllowLowPriorityNode = allowLowPriorityNode;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a string that uniquely identifies the Job Manager task
/// within the job.
/// </summary>
/// <remarks>
/// The ID can contain any combination of alphanumeric characters
/// including hyphens and underscores and cannot contain more than 64
/// characters.
/// </remarks>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name of the Job Manager task.
/// </summary>
/// <remarks>
/// It need not be unique and can contain any Unicode characters up to
/// a maximum length of 1024.
/// </remarks>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the command line of the Job Manager task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot
/// take advantage of shell features such as environment variable
/// expansion. If you want to take advantage of such features, you
/// should invoke the shell in the command line, for example using "cmd
/// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
[JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Files listed under this element are located in the task's working
/// directory.
/// </remarks>
[JsonProperty(PropertyName = "resourceFiles")]
public IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will upload
/// from the compute node after running the command line.
/// </summary>
/// <remarks>
/// For multi-instance tasks, the files will only be uploaded from the
/// compute node on which the primary task is executed.
/// </remarks>
[JsonProperty(PropertyName = "outputFiles")]
public IList<OutputFile> OutputFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the Job
/// Manager task.
/// </summary>
[JsonProperty(PropertyName = "environmentSettings")]
public IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets constraints that apply to the Job Manager task.
/// </summary>
[JsonProperty(PropertyName = "constraints")]
public TaskConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets whether completion of the Job Manager task signifies
/// completion of the entire job.
/// </summary>
/// <remarks>
/// If true, when the Job Manager task completes, the Batch service
/// marks the job as complete. If any tasks are still running at this
/// time (other than Job Release), those tasks are terminated. If
/// false, the completion of the Job Manager task does not affect the
/// job status. In this case, you should either use the
/// onAllTasksComplete attribute to terminate the job, or have a client
/// or user terminate the job explicitly. An example of this is if the
/// Job Manager creates a set of tasks but then takes no further role
/// in their execution. The default value is true. If you are using the
/// onAllTasksComplete and onTaskFailure attributes to control job
/// lifetime, and using the Job Manager task only to create the tasks
/// for the job (not to monitor progress), then it is important to set
/// killJobOnCompletion to false.
/// </remarks>
[JsonProperty(PropertyName = "killJobOnCompletion")]
public bool? KillJobOnCompletion { get; set; }
/// <summary>
/// Gets or sets the user identity under which the Job Manager task
/// runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Gets or sets whether the Job Manager task requires exclusive use of
/// the compute node where it runs.
/// </summary>
/// <remarks>
/// If true, no other tasks will run on the same compute node for as
/// long as the Job Manager is running. If false, other tasks can run
/// simultaneously with the Job Manager on a compute node. The Job
/// Manager task counts normally against the node's concurrent task
/// limit, so this is only relevant if the node allows multiple
/// concurrent tasks. The default value is true.
/// </remarks>
[JsonProperty(PropertyName = "runExclusive")]
public bool? RunExclusive { get; set; }
/// <summary>
/// Gets or sets a list of application packages that the Batch service
/// will deploy to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Application packages are downloaded and deployed to a shared
/// directory, not the task working directory. Therefore, if a
/// referenced package is already on the compute node, and is up to
/// date, then it is not re-downloaded; the existing copy on the
/// compute node is used. If a referenced application package cannot be
/// installed, for example because the package has been deleted or
/// because download failed, the task fails.
/// </remarks>
[JsonProperty(PropertyName = "applicationPackageReferences")]
public IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; }
/// <summary>
/// Gets or sets the settings for an authentication token that the task
/// can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with
/// an authentication token which can be used to authenticate Batch
/// service operations without requiring an account access key. The
/// token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment
/// variable. The operations that the task can carry out using the
/// token depend on the settings. For example, a task can request job
/// permissions in order to add other tasks to the job, or check the
/// status of the job or of other tasks under the job.
/// </remarks>
[JsonProperty(PropertyName = "authenticationTokenSettings")]
public AuthenticationTokenSettings AuthenticationTokenSettings { get; set; }
/// <summary>
/// Gets or sets whether the Job Manager task may run on a low-priority
/// compute node.
/// </summary>
/// <remarks>
/// The default value is false.
/// </remarks>
[JsonProperty(PropertyName = "allowLowPriorityNode")]
public bool? AllowLowPriorityNode { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Id");
}
if (CommandLine == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "CommandLine");
}
if (ResourceFiles != null)
{
foreach (var element in ResourceFiles)
{
if (element != null)
{
element.Validate();
}
}
}
if (OutputFiles != null)
{
foreach (var element1 in OutputFiles)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (EnvironmentSettings != null)
{
foreach (var element2 in EnvironmentSettings)
{
if (element2 != null)
{
element2.Validate();
}
}
}
if (ApplicationPackageReferences != null)
{
foreach (var element3 in ApplicationPackageReferences)
{
if (element3 != null)
{
element3.Validate();
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
internal class CalendricalCalculationsHelper
{
private const double FullCircleOfArc = 360.0; // 360.0;
private const int HalfCircleOfArc = 180;
private const double TwelveHours = 0.5; // half a day
private const double Noon2000Jan01 = 730120.5;
internal const double MeanTropicalYearInDays = 365.242189;
private const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc;
private const double LongitudeSpring = 0.0;
private const double TwoDegreesAfterSpring = 2.0;
private const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
private const int DaysInUniformLengthCentury = 36525;
private const int SecondsPerMinute = 60;
private const int MinutesPerDegree = 60;
private static long s_startOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1));
private static long s_startOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1));
private static double[] s_coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 };
private static double[] s_coefficients1800to1899 = new double[] { -0.000009, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 };
private static double[] s_coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 };
private static double[] s_coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 };
private static double[] s_lambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 };
private static double[] s_anomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 };
private static double[] s_eccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 };
private static double[] s_coefficients = new double[] { Angle(23, 26, 21.448), Angle(0, 0, -46.8150), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) };
private static double[] s_coefficientsA = new double[] { 124.90, -1934.134, 0.002063 };
private static double[] s_coefficientsB = new double[] { 201.11, 72001.5377, 0.00057 };
private static double RadiansFromDegrees(double degree)
{
return degree * Math.PI / 180;
}
private static double SinOfDegree(double degree)
{
return Math.Sin(RadiansFromDegrees(degree));
}
private static double CosOfDegree(double degree)
{
return Math.Cos(RadiansFromDegrees(degree));
}
private static double TanOfDegree(double degree)
{
return Math.Tan(RadiansFromDegrees(degree));
}
public static double Angle(int degrees, int minutes, double seconds)
{
return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees;
}
private static double Obliquity(double julianCenturies)
{
return PolynomialSum(s_coefficients, julianCenturies);
}
internal static long GetNumberOfDays(DateTime date)
{
return date.Ticks / GregorianCalendar.TicksPerDay;
}
private static int GetGregorianYear(double numberOfDays)
{
return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year;
}
private enum CorrectionAlgorithm
{
Default,
Year1988to2019,
Year1900to1987,
Year1800to1899,
Year1700to1799,
Year1620to1699
}
private struct EphemerisCorrectionAlgorithmMap
{
public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm)
{
_lowestYear = year;
_algorithm = algorithm;
}
internal int _lowestYear;
internal CorrectionAlgorithm _algorithm;
};
private static EphemerisCorrectionAlgorithmMap[] s_ephemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[]
{
// lowest year that starts algorithm, algorithm to use
new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default),
new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019),
new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987),
new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899),
new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799),
new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699),
new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last
};
private static double Reminder(double divisor, double dividend)
{
double whole = Math.Floor(divisor / dividend);
return divisor - (dividend * whole);
}
private static double NormalizeLongitude(double longitude)
{
longitude = Reminder(longitude, FullCircleOfArc);
if (longitude < 0)
{
longitude += FullCircleOfArc;
}
return longitude;
}
static public double AsDayFraction(double longitude)
{
return longitude / FullCircleOfArc;
}
private static double PolynomialSum(double[] coefficients, double indeterminate)
{
double sum = coefficients[0];
double indeterminateRaised = 1;
for (int i = 1; i < coefficients.Length; i++)
{
indeterminateRaised *= indeterminate;
sum += (coefficients[i] * indeterminateRaised);
}
return sum;
}
private static double CenturiesFrom1900(int gregorianYear)
{
long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1));
return (double)(july1stOfYear - s_startOf1900Century) / DaysInUniformLengthCentury;
}
// the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
private static double DefaultEphemerisCorrection(int gregorianYear)
{
Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
double daysSinceStartOf1810 = january1stOfYear - s_startOf1810;
double x = TwelveHours + daysSinceStartOf1810;
return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay;
}
private static double EphemerisCorrection1988to2019(int gregorianYear)
{
Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
private static double EphemerisCorrection1900to1987(int gregorianYear)
{
Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900);
}
private static double EphemerisCorrection1800to1899(int gregorianYear)
{
Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900);
}
private static double EphemerisCorrection1700to1799(int gregorianYear)
{
Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
double yearsSince1700 = gregorianYear - 1700;
return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay;
}
private static double EphemerisCorrection1620to1699(int gregorianYear)
{
Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay;
}
// ephemeris-correction: correction to account for the slowing down of the rotation of the earth
private static double EphemerisCorrection(double time)
{
int year = GetGregorianYear(time);
foreach (EphemerisCorrectionAlgorithmMap map in s_ephemerisCorrectionTable)
{
if (map._lowestYear <= year)
{
switch (map._algorithm)
{
case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(year);
case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(year);
case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(year);
case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(year);
case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(year);
case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(year);
}
break; // break the loop and assert eventually
}
}
Contract.Assert(false, "Not expected to come here");
return DefaultEphemerisCorrection(year);
}
static public double JulianCenturies(double moment)
{
double dynamicalMoment = moment + EphemerisCorrection(moment);
return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
}
private static bool IsNegative(double value)
{
return Math.Sign(value) == -1;
}
private static double CopySign(double value, double sign)
{
return (IsNegative(value) == IsNegative(sign)) ? value : -value;
}
// equation-of-time; approximate the difference between apparent solar time and mean solar time
// formal definition is EOT = GHA - GMHA
// GHA is the Greenwich Hour Angle of the apparent (actual) Sun
// GMHA is the Greenwich Mean Hour Angle of the mean (fictitious) Sun
// http://www.esrl.noaa.gov/gmd/grad/solcalc/
// http://en.wikipedia.org/wiki/Equation_of_time
private static double EquationOfTime(double time)
{
double julianCenturies = JulianCenturies(time);
double lambda = PolynomialSum(s_lambdaCoefficients, julianCenturies);
double anomaly = PolynomialSum(s_anomalyCoefficients, julianCenturies);
double eccentricity = PolynomialSum(s_eccentricityCoefficients, julianCenturies);
double epsilon = Obliquity(julianCenturies);
double tanHalfEpsilon = TanOfDegree(epsilon / 2);
double y = tanHalfEpsilon * tanHalfEpsilon;
double dividend = ((y * SinOfDegree(2 * lambda))
- (2 * eccentricity * SinOfDegree(anomaly))
+ (4 * eccentricity * y * SinOfDegree(anomaly) * CosOfDegree(2 * lambda))
- (0.5 * Math.Pow(y, 2) * SinOfDegree(4 * lambda))
- (1.25 * Math.Pow(eccentricity, 2) * SinOfDegree(2 * anomaly)));
double divisor = 2 * Math.PI;
double equation = dividend / divisor;
// approximation of equation of time is not valid for dates that are many millennia in the past or future
// thus limited to a half day
return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation);
}
private static double AsLocalTime(double apparentMidday, double longitude)
{
// slightly inaccurate since equation of time takes mean time not apparent time as its argument, but the difference is negligible
double universalTime = apparentMidday - AsDayFraction(longitude);
return apparentMidday - EquationOfTime(universalTime);
}
// midday
static public double Midday(double date, double longitude)
{
return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude);
}
private static double InitLongitude(double longitude)
{
return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc;
}
// midday-in-tehran
static public double MiddayAtPersianObservationSite(double date)
{
return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time
}
private static double PeriodicTerm(double julianCenturies, int x, double y, double z)
{
return x * SinOfDegree(y + z * julianCenturies);
}
private static double SumLongSequenceOfPeriodicTerms(double julianCenturies)
{
double sum = 0.0;
sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892);
sum += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958);
sum += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666);
sum += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385);
sum += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261);
sum += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403);
sum += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726);
sum += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812);
sum += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678);
sum += PeriodicTerm(julianCenturies, 334, 260.87, -19.441);
sum += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117);
sum += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884);
sum += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008);
sum += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434);
sum += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739);
sum += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345);
sum += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293);
sum += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684);
sum += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148);
sum += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448);
sum += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773);
sum += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992);
sum += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493);
sum += PeriodicTerm(julianCenturies, 68, 185.1, 149.588);
sum += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75);
sum += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405);
sum += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176);
sum += PeriodicTerm(julianCenturies, 37, 250.4, 151.771);
sum += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316);
sum += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08);
sum += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54);
sum += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706);
sum += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655);
sum += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167);
sum += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369);
sum += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298);
sum += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757);
sum += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243);
sum += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999);
sum += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511);
sum += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039);
sum += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909);
sum += PeriodicTerm(julianCenturies, 13, 151.8, 119.066);
sum += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071);
sum += PeriodicTerm(julianCenturies, 12, 53.3, -4.578);
sum += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292);
sum += PeriodicTerm(julianCenturies, 10, 205.7, -39.127);
sum += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536);
sum += PeriodicTerm(julianCenturies, 10, 146.1, 90073.778);
return sum;
}
private static double Aberration(double julianCenturies)
{
return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575;
}
private static double Nutation(double julianCenturies)
{
double a = PolynomialSum(s_coefficientsA, julianCenturies);
double b = PolynomialSum(s_coefficientsB, julianCenturies);
return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b));
}
static public double Compute(double time)
{
double julianCenturies = JulianCenturies(time);
double lambda = 282.7771834
+ (36000.76953744 * julianCenturies)
+ (0.000005729577951308232 * SumLongSequenceOfPeriodicTerms(julianCenturies));
double longitude = lambda + Aberration(julianCenturies) + Nutation(julianCenturies);
return InitLongitude(longitude);
}
static public double AsSeason(double longitude)
{
return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
}
private static double EstimatePrior(double longitude, double time)
{
double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude)));
double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude);
return Math.Min(time, timeSunLastAtLongitude - (MeanSpeedOfSun * longitudeErrorDelta));
}
// persian-new-year-on-or-before
// number of days is the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
internal static long PersianNewYearOnOrBefore(long numberOfDays)
{
double date = (double)numberOfDays;
double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date));
long lowerBoundNewYearDay = (long)Math.Floor(approx) - 1;
long upperBoundNewYearDay = lowerBoundNewYearDay + 3; // estimate is generally within a day of the actual occurrance (at the limits, the error expands, since the calculations rely on the mean tropical year which changes...)
long day = lowerBoundNewYearDay;
for (; day != upperBoundNewYearDay; ++day)
{
double midday = MiddayAtPersianObservationSite((double)day);
double l = Compute(midday);
if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring))
{
break;
}
}
Contract.Assert(day != upperBoundNewYearDay);
return day - 1;
}
}
}
| |
//-----------------------------------------------------------------------------
// Universal Trionic adapter library
// (C) Janis Silins, 2010
// $Id$
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using Combi;
namespace T5CANLib.CAN
{
//-----------------------------------------------------------------------------
/**
CAN library driver for LPC17xx based devices.
*/
public class LPCCANDevice_T5 : ICANDevice, IDisposable
{
// dynamic state
private Thread read_thread; ///< reader thread
private bool term_requested = false; ///< thread termination flag
private Object term_mutex = new Object(); ///< mutex for termination flag
private bool logging_enabled = false; ///< logging flag
private string startup_path =
@"C:\Program Files\Dilemma\CarPCControl"; ///< startup path
private caCombiAdapter combi; ///< adapter object
private CANMessage in_msg =
new CANMessage(); ///< incoming message
//-------------------------------------------------------------------------
/**
Default constructor.
*/
public LPCCANDevice_T5()
{
// create adapter
this.combi = new caCombiAdapter();
Debug.Assert(this.combi != null);
// create reader thread
this.read_thread = new Thread(this.read_messages);
Debug.Assert(read_thread != null);
}
//-------------------------------------------------------------------------
/**
Destructor.
*/
~LPCCANDevice_T5()
{
// release adapter
this.close();
this.combi = null;
}
//-------------------------------------------------------------------------
/**
Releases the object.
*/
public override void Delete()
{
// empty
}
//-------------------------------------------------------------------------
/**
Disposes of the object.
*/
public void Dispose()
{
// empty
}
//-----------------------------------------------------------------------------
/**
Checks if ADC low-pass filter is active.
@param channel A/D channel number [0...4]
@return active (yes / no)
*/
public override void setPortNumber(string portnumber)
{
//nothing to do
}
/*
public override bool GetADCFiltering(uint channel)
{
Debug.Assert(this.combi != null);
return this.combi.GetADCFiltering(channel);
}*/
//-----------------------------------------------------------------------------
/**
Enables / disables low-pass filtering for all ADC channels and stores
the setting in EEPROM.
@param channel A/D channel number [0...4]
@param enable filtering enabled (yes / no)
*/
/*public override void SetADCFiltering(uint channel, bool enable)
{
Debug.Assert(this.combi != null);
this.combi.SetADCFiltering(channel, enable);
}*/
//-----------------------------------------------------------------------------
/**
Returns momentary voltage from A/D converter; works in all modes.
@param channel A/D channel number [0...4]
@return analog value, V
*/
public override float GetADCValue(uint channel)
{
Debug.Assert(this.combi != null);
return this.combi.GetADCValue(channel);
}
//-----------------------------------------------------------------------------
/**
Returns current temperature from K-type thermocouple.
@param value temperature, DegC
*/
public override float GetThermoValue()
{
Debug.Assert(this.combi != null);
float value = this.combi.GetThermoValue();
//value += DateTime.Now.Millisecond;
return value;
}
//-------------------------------------------------------------------------
/**
Connects to adapter over USB.
@return succ / fail
*/
public bool connect()
{
try
{
// connect to adapter
this.combi.Open();
uint fw_ver = this.combi.GetFirmwareVersion();
return true;
}
catch
{
return false;
}
}
//-------------------------------------------------------------------------
/**
Disconnects from adapter.
@return succ / fail
*/
public void disconnect()
{
this.combi.Close();
}
//-------------------------------------------------------------------------
/**
Opens a connection to CAN interface.
@return result
*/
public override OpenResult open()
{
try
{
// connect to adapter
this.connect();
// open CAN channel
this.combi.CAN_SetBitrate(615000);
this.combi.CAN_Open(true);
// start reader thread
this.read_thread.Start();
return OpenResult.OK;
}
catch
{
// cleanup
this.close();
// adapter not present
return OpenResult.OpenError;
}
}
//-------------------------------------------------------------------------
/**
Determines if connection to CAN device is open.
return open (true/false)
*/
public override bool isOpen()
{
return this.combi.IsOpen();
}
//-------------------------------------------------------------------------
/**
Closes the connection to CAN interface.
return success (true/false)
*/
public override CloseResult close()
{
try
{
// terminate worker thread
Debug.Assert(this.term_mutex != null);
lock (this.term_mutex)
{
this.term_requested = true;
}
// close connection
this.disconnect();
return CloseResult.OK;
}
catch
{
// ignore errors
return CloseResult.OK;
}
}
//-------------------------------------------------------------------------
/**
Clears incoming data buffer.
*/
public override void clearReceiveBuffer()
{
// TODO
}
//-------------------------------------------------------------------------
/**
Clears outgoing data buffer.
*/
public override void clearTransmitBuffer()
{
// TODO
}
//-------------------------------------------------------------------------
/**
*/
//-------------------------------------------------------------------------
/**
Returns the number of connected adapters.
@return number of adapters
*/
public override int GetNumberOfAdapters()
{
return 1;
}
//-------------------------------------------------------------------------
/**
Enables logging.
@param path2log log file location
*/
public override void EnableLogging(string path2log)
{
this.logging_enabled = true;
this.startup_path = path2log;
}
//-------------------------------------------------------------------------
/**
Disables logging.
*/
public override void DisableLogging()
{
this.logging_enabled = false;
}
//-------------------------------------------------------------------------
/**
Writes a CAN message to log file.
@param r_canMsg message
@param IsTransmit ???
*/
private void DumpCanMsg(CANMessage r_canMsg, bool IsTransmit)
{
DateTime dt = DateTime.Now;
try
{
using (StreamWriter sw = new StreamWriter(Path.Combine(this.startup_path,
dt.Year.ToString("D4") + dt.Month.ToString("D2") +
dt.Day.ToString("D2") + "-CanTrace.log"), true))
{
if (IsTransmit)
{
// get the byte transmitted
int transmitvalue = (int)(r_canMsg.getData() & 0x000000000000FF00);
transmitvalue /= 256;
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") +
" TX: id=" + r_canMsg.getID().ToString("D2") +
" len= " + r_canMsg.getLength().ToString("X8") +
" data=" + r_canMsg.getData().ToString("X16") +
" " + r_canMsg.getFlags().ToString("X2") +
" character = " + GetCharString(transmitvalue) +
"\t ts: " + r_canMsg.getTimeStamp().ToString("X16") +
" flags: " + r_canMsg.getFlags().ToString("X2"));
}
else
{
// get the byte received
int receivevalue = (int)(r_canMsg.getData() & 0x0000000000FF0000);
receivevalue /= (256 * 256);
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") +
" RX: id=" + r_canMsg.getID().ToString("D2") +
" len= " + r_canMsg.getLength().ToString("X8") +
" data=" + r_canMsg.getData().ToString("X16") +
" " + r_canMsg.getFlags().ToString("X2") +
" character = " + GetCharString(receivevalue) +
"\t ts: " + r_canMsg.getTimeStamp().ToString("X16") +
" flags: " + r_canMsg.getFlags().ToString("X2"));
}
}
}
catch (Exception E)
{
Console.WriteLine("Failed to write to logfile: " + E.Message);
}
}
//-------------------------------------------------------------------------
/**
Converts a special character to string.
@param value character
@return string
*/
private string GetCharString(int value)
{
char c = Convert.ToChar(value);
string charstr = c.ToString();
if (c == 0x0d) charstr = "<CR>";
else if (c == 0x0a) charstr = "<LF>";
else if (c == 0x00) charstr = "<NULL>";
else if (c == 0x01) charstr = "<SOH>";
else if (c == 0x02) charstr = "<STX>";
else if (c == 0x03) charstr = "<ETX>";
else if (c == 0x04) charstr = "<EOT>";
else if (c == 0x05) charstr = "<ENQ>";
else if (c == 0x06) charstr = "<ACK>";
else if (c == 0x07) charstr = "<BEL>";
else if (c == 0x08) charstr = "<BS>";
else if (c == 0x09) charstr = "<TAB>";
else if (c == 0x0B) charstr = "<VT>";
else if (c == 0x0C) charstr = "<FF>";
else if (c == 0x0E) charstr = "<SO>";
else if (c == 0x0F) charstr = "<SI>";
else if (c == 0x10) charstr = "<DLE>";
else if (c == 0x11) charstr = "<DC1>";
else if (c == 0x12) charstr = "<DC2>";
else if (c == 0x13) charstr = "<DC3>";
else if (c == 0x14) charstr = "<DC4>";
else if (c == 0x15) charstr = "<NACK>";
else if (c == 0x16) charstr = "<SYN>";
else if (c == 0x17) charstr = "<ETB>";
else if (c == 0x18) charstr = "<CAN>";
else if (c == 0x19) charstr = "<EM>";
else if (c == 0x1A) charstr = "<SUB>";
else if (c == 0x1B) charstr = "<ESC>";
else if (c == 0x1C) charstr = "<FS>";
else if (c == 0x1D) charstr = "<GS>";
else if (c == 0x1E) charstr = "<RS>";
else if (c == 0x1F) charstr = "<US>";
else if (c == 0x7F) charstr = "<DEL>";
return charstr;
}
//-------------------------------------------------------------------------
/**
Sends a 11 bit CAN data frame.
@param msg CAN message
@return success (true/false)
*/
public override bool sendMessage(CANMessage msg)
{
if (this.logging_enabled)
{
this.DumpCanMsg(msg, true);
}
try
{
Combi.caCombiAdapter.caCANFrame frame;
frame.id = msg.getID();
frame.length = msg.getLength();
frame.data = msg.getData();
frame.is_extended = 0;
frame.is_remote = 0;
this.combi.CAN_SendMessage(ref frame);
return true;
}
catch (Exception e)
{
return false;
}
}
//-------------------------------------------------------------------------
/**
Handles incoming messages.
*/
private void read_messages()
{
caCombiAdapter.caCANFrame frame = new caCombiAdapter.caCANFrame();
// main loop
while (true)
{
// check tor thread termination request
Debug.Assert(this.term_mutex != null);
lock (this.term_mutex)
{
if (this.term_requested)
{
// exit
return;
}
}
// receive messages
if (this.combi.CAN_GetMessage(ref frame, 1000))
{
// convert message
this.in_msg.setID(frame.id);
this.in_msg.setLength(frame.length);
this.in_msg.setData(frame.data);
// pass message to listeners
lock (this.m_listeners)
{
foreach (ICANListener listener in this.m_listeners)
{
listener.handleMessage(this.in_msg);
}
}
}
}
}
};
} // end namespace
//-----------------------------------------------------------------------------
// EOF
//-----------------------------------------------------------------------------
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
namespace Microsoft.DotNet.Cli.Publish.Tests
{
public class GivenDotnetPublishPublishesProjects : TestBase
{
[Fact]
public void ItPublishesARunnablePortableApp()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("--framework netcoreapp2.0")
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputDll = Path.Combine(testProjectDirectory, "bin", configuration, "netcoreapp2.0", "publish", $"{testAppName}.dll");
new DotnetCommand()
.ExecuteWithCapturedOutput(outputDll)
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItImplicitlyRestoresAProjectWhenPublishing()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("--framework netcoreapp2.0")
.Should().Pass();
}
[Fact]
public void ItCanPublishAMultiTFMProjectWithImplicitRestore()
{
var testInstance = TestAssets.Get(
TestAssetKinds.DesktopTestProjects,
"NETFrameworkReferenceNETStandard20")
.CreateInstance()
.WithSourceFiles();
string projectDirectory = Path.Combine(testInstance.Root.FullName, "MultiTFMTestApp");
new PublishCommand()
.WithWorkingDirectory(projectDirectory)
.Execute("--framework netcoreapp2.0")
.Should().Pass();
}
[Fact]
public void ItDoesNotImplicitlyRestoreAProjectWhenPublishingWithTheNoRestoreOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new PublishCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp2.0 --no-restore")
.Should().Fail()
.And.HaveStdOutContaining("project.assets.json");
}
[Fact]
public void ItPublishesARunnableSelfContainedApp()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root;
var rid = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
new PublishCommand()
.WithFramework("netcoreapp2.0")
.WithRuntime(rid)
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputProgram = testProjectDirectory
.GetDirectory("bin", configuration, "netcoreapp2.0", rid, "publish", $"{testAppName}{Constants.ExeSuffix}")
.FullName;
EnsureProgramIsRunnable(outputProgram);
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItPublishesARidSpecificAppSettingSelfContainedToTrue()
{
var testAppName = "MSBuildTestApp";
var outputDirectory = PublishAppWithSelfContained(testAppName, true);
var outputProgram = Path.Combine(outputDirectory.FullName, $"{testAppName}{Constants.ExeSuffix}");
EnsureProgramIsRunnable(outputProgram);
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItPublishesARidSpecificAppSettingSelfContainedToFalse()
{
var testAppName = "MSBuildTestApp";
var outputDirectory = PublishAppWithSelfContained(testAppName, false);
outputDirectory.Should().OnlyHaveFiles(new[] {
$"{testAppName}.dll",
$"{testAppName}.pdb",
$"{testAppName}.deps.json",
$"{testAppName}.runtimeconfig.json",
});
new DotnetCommand()
.ExecuteWithCapturedOutput(Path.Combine(outputDirectory.FullName, $"{testAppName}.dll"))
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
private DirectoryInfo PublishAppWithSelfContained(string testAppName, bool selfContained)
{
var testInstance = TestAssets.Get(testAppName)
.CreateInstance($"PublishesSelfContained{selfContained}")
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root;
var rid = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
new PublishCommand()
.WithRuntime(rid)
.WithSelfContained(selfContained)
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
return testProjectDirectory
.GetDirectory("bin", configuration, "netcoreapp2.0", rid, "publish");
}
private static void EnsureProgramIsRunnable(string path)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
//Workaround for https://github.com/dotnet/corefx/issues/15516
Process.Start("chmod", $"u+x {path}").WaitForExit();
}
}
[Fact]
public void ItPublishesAppWhenRestoringToSpecificPackageDirectory()
{
var rootPath = TestAssets.CreateTestDirectory().FullName;
var rootDir = new DirectoryInfo(rootPath);
string dir = "pkgs";
string args = $"--packages {dir}";
string newArgs = $"console -o \"{rootPath}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(rootPath)
.Execute(newArgs)
.Should()
.Pass();
new RestoreCommand()
.WithWorkingDirectory(rootPath)
.Execute(args)
.Should()
.Pass();
new PublishCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Pass();
var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
var outputProgram = rootDir
.GetDirectory("bin", configuration, "netcoreapp2.0", "publish", $"{rootDir.Name}.dll")
.FullName;
new TestCommand(outputProgram)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
}
}
| |
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting.Channels.Ipc;
using System.Configuration;
using System.Security.Permissions;
using System.Globalization;
using Microsoft.Win32;
using System.Security.AccessControl;
using System.Security.Principal;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
internal static class RegistryKeys
{
internal static readonly string ProductRootRegKey = @"SOFTWARE\Microsoft\Net Framework Setup\NDP\v3.0\Setup\Windows Workflow Foundation";
internal static readonly string DebuggerSubKey = ProductRootRegKey + @"\Debugger";
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class DebugController : MarshalByRefObject
{
#region Data members
private Guid programId;
private string hostName;
private int attachTimeout;
private ProgramPublisher programPublisher;
private DebugControllerThread debugControllerThread;
private Timer attachTimer;
private WorkflowRuntime serviceContainer;
private IpcChannel channel;
private IWorkflowDebugger controllerConduit;
private bool isZombie;
private bool isAttached;
private ManualResetEvent eventConduitAttached;
private InstanceTable instanceTable;
private Dictionary<Type, Guid> typeToGuid;
private Dictionary<byte[], Guid> xomlHashToGuid;
bool isServiceContainerStarting;
private const string rootExecutorGuid = "98fcdc7a-8ab4-4fb7-92d4-20f437285729";
private object eventLock;
private object syncRoot = new object();
private static readonly string ControllerConduitTypeName = "ControllerConduitTypeName";
#endregion
#region Security related methods
private delegate void ExceptionNotification(Exception e);
internal static void InitializeProcessSecurity()
{
// Spawn off a separate thread to that does RevertToSelf and adjusts DACLs.
// This is because RevertToSelf terminates client impersonation on the thread
// that calls it. We do not want to change that on the current thread when
// the runtime is hosted inside ASP.net for example.
Exception workerThreadException = null;
ProcessSecurity processSecurity = new ProcessSecurity();
Thread workerThread = new Thread(new ThreadStart(processSecurity.Initialize));
processSecurity.exceptionNotification += delegate(Exception e)
{
workerThreadException = e;
};
workerThread.Start(); workerThread.Join();
if (workerThreadException != null)
throw workerThreadException;
}
private class ProcessSecurity
{
internal ExceptionNotification exceptionNotification;
internal void Initialize()
{
try
{
// This is needed if the thread calling the method is impersonating
// a client call (ASP.net hosting scenarios).
if (!NativeMethods.RevertToSelf())
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
// Get the DACL for process token. Add TOKEN_QUERY permissions for the Administrators group.
// Set the updated DACL for process token.
RawAcl tokenDacl = GetCurrentProcessTokenDacl();
CommonAce adminsGroupAceForToken = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, NativeMethods.TOKEN_QUERY, new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), false, null);
int i = FindIndexInDacl(adminsGroupAceForToken, tokenDacl);
if (i != -1)
tokenDacl.InsertAce(i, adminsGroupAceForToken);
SetCurrentProcessTokenDacl(tokenDacl);
}
catch (Exception e)
{
// Communicate any exceptions from this thread back to the thread
// that spawned it.
if (exceptionNotification != null)
exceptionNotification(e);
}
}
private RawAcl GetCurrentProcessTokenDacl()
{
IntPtr hProcess = IntPtr.Zero;
IntPtr hProcessToken = IntPtr.Zero;
IntPtr securityDescriptorPtr = IntPtr.Zero;
try
{
hProcess = NativeMethods.GetCurrentProcess();
if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ALL_ACCESS, out hProcessToken))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
// Get security descriptor associated with the kernel object, read the DACL and return
// that to the caller.
uint returnLength;
NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, 0, out returnLength);
int lasterror = Marshal.GetLastWin32Error(); //#pragma warning disable 56523 doesnt recognize 56523
securityDescriptorPtr = Marshal.AllocCoTaskMem((int)returnLength);
if (!NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, securityDescriptorPtr, returnLength, out returnLength))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
byte[] sdBytes = new byte[returnLength];
Marshal.Copy(securityDescriptorPtr, sdBytes, 0, (int)returnLength);
RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(sdBytes, 0);
return rawSecurityDescriptor.DiscretionaryAcl;
}
finally
{
if (hProcess != IntPtr.Zero && hProcess != (IntPtr)(-1))
if (!NativeMethods.CloseHandle(hProcess))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (hProcessToken != IntPtr.Zero)
if (!NativeMethods.CloseHandle(hProcessToken))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (securityDescriptorPtr != IntPtr.Zero)
Marshal.FreeCoTaskMem(securityDescriptorPtr);
}
}
private void SetCurrentProcessTokenDacl(RawAcl dacl)
{
IntPtr hProcess = IntPtr.Zero;
IntPtr hProcessToken = IntPtr.Zero;
IntPtr securityDescriptorPtr = IntPtr.Zero;
try
{
hProcess = NativeMethods.GetCurrentProcess();
if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ALL_ACCESS, out hProcessToken))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
// Get security descriptor associated with the kernel object and modify it.
uint returnLength;
NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, 0, out returnLength);
int lasterror = Marshal.GetLastWin32Error(); //#pragma warning disable 56523 doesnt recognize 56523
securityDescriptorPtr = Marshal.AllocCoTaskMem((int)returnLength);
if (!NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, securityDescriptorPtr, returnLength, out returnLength))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
byte[] sdBytes = new byte[returnLength];
Marshal.Copy(securityDescriptorPtr, sdBytes, 0, (int)returnLength);
RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(sdBytes, 0);
rawSecurityDescriptor.DiscretionaryAcl = dacl;
sdBytes = new byte[rawSecurityDescriptor.BinaryLength];
rawSecurityDescriptor.GetBinaryForm(sdBytes, 0);
Marshal.FreeCoTaskMem(securityDescriptorPtr);
securityDescriptorPtr = Marshal.AllocCoTaskMem(rawSecurityDescriptor.BinaryLength);
Marshal.Copy(sdBytes, 0, securityDescriptorPtr, rawSecurityDescriptor.BinaryLength);
if (!NativeMethods.SetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, securityDescriptorPtr))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
finally
{
if (hProcess != IntPtr.Zero && hProcess != (IntPtr)(-1))
if (!NativeMethods.CloseHandle(hProcess))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (hProcessToken != IntPtr.Zero)
if (!NativeMethods.CloseHandle(hProcessToken))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
if (securityDescriptorPtr != IntPtr.Zero)
Marshal.FreeCoTaskMem(securityDescriptorPtr);
}
}
// The preferred order in which ACEs are added to DACLs is
// documented here: http://search.msdn.microsoft.com/search/results.aspx?qu=Order+of+ACEs+in+a+DACL&View=msdn&st=b.
// This routine follows that logic to determine the position of an ACE in the DACL.
private int FindIndexInDacl(CommonAce newAce, RawAcl dacl)
{
int i = 0;
for (i = 0; i < dacl.Count; i++)
{
if (dacl[i] is CommonAce && ((CommonAce)dacl[i]).SecurityIdentifier.Value == newAce.SecurityIdentifier.Value && dacl[i].AceType == newAce.AceType)
{
i = -1;
break;
}
if (newAce.AceType == AceType.AccessDenied && dacl[i].AceType == AceType.AccessDenied && !newAce.IsInherited && !dacl[i].IsInherited)
continue;
if (newAce.AceType == AceType.AccessDenied && !newAce.IsInherited)
break;
if (newAce.AceType == AceType.AccessAllowed && dacl[i].AceType == AceType.AccessAllowed && !newAce.IsInherited && !dacl[i].IsInherited)
continue;
if (newAce.AceType == AceType.AccessAllowed && !newAce.IsInherited)
break;
}
return i;
}
}
#endregion
#region Constructor and Lifetime methods
internal DebugController(WorkflowRuntime serviceContainer, string hostName)
{
if (serviceContainer == null)
throw new ArgumentNullException("serviceContainer");
try
{
this.programPublisher = new ProgramPublisher();
}
catch
{
// If we are unable to create the ProgramPublisher, this means that VS does not exist on this machine, so we can't debug.
return;
}
this.serviceContainer = serviceContainer;
this.programId = Guid.Empty;
this.controllerConduit = null;
this.channel = null;
this.isZombie = false;
this.hostName = hostName;
AppDomain.CurrentDomain.ProcessExit += OnDomainUnload;
AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
this.serviceContainer.Started += this.Start;
this.serviceContainer.Stopped += this.Stop;
}
public override object InitializeLifetimeService()
{
// We can't use a sponser because VS doesn't like to be attached when the lease renews itself - the
// debugee gets an Access Violation and VS freezes. Returning null implies that the proxy shim will be
// deleted only when the App Domain unloads. However, we will have disconnected the shim so no
// one will be able to attach to it and the same proxy is used everytime a debugger attaches.
return null;
}
#endregion
#region Attach and Detach methods
internal void Attach(Guid programId, int attachTimeout, int detachPingInterval, out string hostName, out string uri, out int controllerThreadId, out bool isSynchronousAttach)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.Attach(): programId = {0}", programId));
lock (this.syncRoot)
{
hostName = String.Empty;
uri = String.Empty;
controllerThreadId = 0;
isSynchronousAttach = false;
// Race condition:
// During the call to Attach() if Uninitialize() is also called, we should ignore the call to Attach() and
// just return. The Zombie flag and lock(this) help us recognize the ----.
if (this.isZombie)
return;
// Race condition:
// The isAttached flat along with lock(this) catch the ---- where a debugger may have detached which
// we haven't detected yet and another debugger may have attached, so we force detach from the first
// debugger.
if (this.isAttached)
Detach();
this.isAttached = true;
this.programId = programId;
this.debugControllerThread = new DebugControllerThread();
this.instanceTable = new InstanceTable(this.debugControllerThread.ManagedThreadId);
this.typeToGuid = new Dictionary<Type, Guid>();
this.xomlHashToGuid = new Dictionary<byte[], Guid>((IEqualityComparer<byte[]>)new DigestComparer());
this.debugControllerThread.RunThread(this.instanceTable);
// Publish our MBR object.
IDictionary providerProperties = new Hashtable();
providerProperties["typeFilterLevel"] = "Full";
BinaryServerFormatterSinkProvider sinkProvider = new BinaryServerFormatterSinkProvider(providerProperties, null);
Hashtable channelProperties = new Hashtable();
channelProperties["name"] = string.Empty;
channelProperties["portName"] = this.programId.ToString();
SecurityIdentifier si = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
IdentityReference idRef = si.Translate(typeof(NTAccount));
channelProperties["authorizedGroup"] = idRef.ToString();
this.channel = new IpcChannel(channelProperties, null, sinkProvider);
ChannelServices.RegisterChannel(this.channel, true);
ObjRef o = RemotingServices.Marshal(this, this.programId.ToString());
hostName = this.hostName;
uri = this.channel.GetUrlsForUri(this.programId.ToString())[0];
controllerThreadId = this.debugControllerThread.ThreadId;
isSynchronousAttach = !this.isServiceContainerStarting;
this.attachTimeout = attachTimeout;
this.attachTimer = new Timer(AttachTimerCallback, null, attachTimeout, detachPingInterval);
}
}
private void Detach()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.Detach():"));
using (new DebuggerThreadMarker())
{
lock (this.syncRoot)
{
AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoad;
// See comments in Attach().
if (this.isZombie || !this.isAttached)
return;
this.isAttached = false;
// Undone: AkashS - At this point wait for all event handling to complete to avoid exceptions.
this.programId = Guid.Empty;
if (this.debugControllerThread != null)
{
this.debugControllerThread.StopThread();
this.debugControllerThread = null;
}
if (this.attachTimer != null)
{
this.attachTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.attachTimer = null;
}
RemotingServices.Disconnect(this);
if (this.channel != null)
{
ChannelServices.UnregisterChannel(this.channel);
this.channel = null;
}
this.controllerConduit = null;
this.eventConduitAttached.Reset();
this.instanceTable = null;
this.typeToGuid = null;
this.xomlHashToGuid = null;
// Do this only after we perform the previous cleanup! Otherwise
// we may get exceptions from the runtime that may cause the cleanup
// to not happen.
if (!this.serviceContainer.IsZombie)
{
foreach (WorkflowInstance instance in this.serviceContainer.GetLoadedWorkflows())
{
WorkflowExecutor executor = instance.GetWorkflowResourceUNSAFE();
using (executor.ExecutorLock.Enter())
{
if (executor.IsInstanceValid)
executor.WorkflowExecutionEvent -= OnInstanceEvent;
}
}
this.serviceContainer.WorkflowExecutorInitializing -= InstanceInitializing;
this.serviceContainer.DefinitionDispenser.WorkflowDefinitionLoaded -= ScheduleTypeLoaded;
}
}
}
}
private void AttachTimerCallback(object state)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.AttachTimerCallback():"));
try
{
lock (this.syncRoot)
{
// See comments in Attach().
if (this.isZombie || !this.isAttached)
return;
if (!Debugger.IsAttached)
{
// The debugger had attached and has now detached, so cleanup, or Attach() was called on the
// Program Node, but the process of attach failed thereafter and so we were never actually
// debugged.
this.attachTimer.Change(Timeout.Infinite, Timeout.Infinite);
Detach();
}
}
}
catch
{
// Avoid throwing unhandled exceptions!
}
}
private void OnDomainUnload(object sender, System.EventArgs e)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.OnDomainUnload():"));
Stop(null, default(WorkflowRuntimeEventArgs));
}
#endregion
#region Methods for the DE
public void AttachToConduit(Uri url)
{
if (url == null)
throw new ArgumentNullException("url");
try
{
using (new DebuggerThreadMarker())
{
try
{
RegistryKey debugEngineSubKey = Registry.LocalMachine.OpenSubKey(RegistryKeys.DebuggerSubKey);
if (debugEngineSubKey != null)
{
string controllerConduitTypeName = debugEngineSubKey.GetValue(ControllerConduitTypeName, String.Empty) as string;
if (!String.IsNullOrEmpty(controllerConduitTypeName) && Type.GetType(controllerConduitTypeName) != null)
this.controllerConduit = Activator.GetObject(Type.GetType(controllerConduitTypeName), url.AbsolutePath) as IWorkflowDebugger;
}
}
catch { }
if (this.controllerConduit == null)
{
const string controllerConduitTypeFormat = "Microsoft.Workflow.DebugEngine.ControllerConduit, Microsoft.Workflow.DebugController, Version={0}.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
// Try versions 12.0.0.0, 11.0.0.0, 10.0.0.0
Type controllerConduitType = null;
for (int version = 12; controllerConduitType == null && version >= 10; --version)
{
try
{
controllerConduitType = Type.GetType(string.Format(CultureInfo.InvariantCulture, controllerConduitTypeFormat, version));
}
catch (TypeLoadException)
{
// Fall back to next-lower version
}
}
if (controllerConduitType != null)
{
this.controllerConduit = Activator.GetObject(controllerConduitType, url.AbsolutePath) as IWorkflowDebugger;
}
}
Debug.Assert(this.controllerConduit != null, "Failed to create Controller Conduit");
if (this.controllerConduit == null)
return;
this.eventLock = new object();
// Race Condition:
// We hook up to the AssemblyLoad event, the Schedule events and Instance events handler
// before we iterate over all loaded assemblies. This means that we need to deal with duplicates in the
// debugee.
// Race Condition:
// Further the order in which we hook up handlers/iterate is important to avoid ----s if the events fire
// before the iterations complete. We need to hook and iterate over the assemblies, then the schedule
// types and finally the instances. This guarantees that we always have all the assemblies when we load
// schedules types and we always have all the schedule types when we load instances.
AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!assembly.IsDynamic
&& !(assembly is System.Reflection.Emit.AssemblyBuilder)
&& !(string.IsNullOrEmpty(assembly.Location)))
{
this.controllerConduit.AssemblyLoaded(this.programId, assembly.Location, assembly.GlobalAssemblyCache);
}
}
this.serviceContainer.DefinitionDispenser.WorkflowDefinitionLoaded += ScheduleTypeLoaded;
// In here we load all schedule types defined as they are - with no dynamic updates
ReadOnlyCollection<Type> types;
ReadOnlyCollection<Activity> values;
this.serviceContainer.DefinitionDispenser.GetWorkflowTypes(out types, out values);
for (int i = 0; i < types.Count; i++)
{
Type scheduleType = types[i];
Activity rootActivity = values[i];
LoadExistingScheduleType(GetScheduleTypeId(scheduleType), scheduleType, false, rootActivity);
}
ReadOnlyCollection<byte[]> keys;
this.serviceContainer.DefinitionDispenser.GetWorkflowDefinitions(out keys, out values);
for (int i = 0; i < keys.Count; i++)
{
byte[] scheduleDefHash = keys[i];
Activity rootActivity = values[i];
Activity workflowDefinition = (Activity)rootActivity.GetValue(Activity.WorkflowDefinitionProperty);
ArrayList changeActions = null;
if (workflowDefinition != null)
changeActions = (ArrayList)workflowDefinition.GetValue(WorkflowChanges.WorkflowChangeActionsProperty);
LoadExistingScheduleType(GetScheduleTypeId(scheduleDefHash), rootActivity.GetType(), (changeActions != null && changeActions.Count != 0), rootActivity);
}
this.serviceContainer.WorkflowExecutorInitializing += InstanceInitializing;
foreach (WorkflowInstance instance in this.serviceContainer.GetLoadedWorkflows())
{
WorkflowExecutor executor = instance.GetWorkflowResourceUNSAFE();
using (executor.ExecutorLock.Enter())
{
LoadExistingInstance(instance, true);
}
}
this.eventConduitAttached.Set();
}
}
catch (Exception e)
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: Failure in DebugController.AttachToConduit: {0}, Call stack:{1}", e.Message, e.StackTrace));
}
}
#endregion
#region Methods for the Runtime
private void Start(object source, WorkflowRuntimeEventArgs e)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.ServiceContainerStarted():"));
this.isZombie = false;
this.isAttached = false;
this.eventConduitAttached = new ManualResetEvent(false);
this.isServiceContainerStarting = true;
bool published = this.programPublisher.Publish(this);
// If the debugger is already attached, then the DE will invoke AttachToConduit() on a separate thread.
// We need to wait for that to happen to prevent new instances being created and causing a ----. See
// comments in ControllerConduit.ProgramCreated(). However, if the DE never calls AttachToConduit(),
// and the detaches instead, we set a wait timeout to that of our Attach Timer.
// Note that when we publish the program node, if the debugger is attached, isAttached will be set to true
// when the debugger calls Attach() on the Program Node!
while (published && this.isAttached && !this.eventConduitAttached.WaitOne(attachTimeout, false));
this.isServiceContainerStarting = false;
}
private void Stop(object source, WorkflowRuntimeEventArgs e)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.ServiceContainerStopped():"));
try
{
lock (this.syncRoot)
{
Detach();
this.programPublisher.Unpublish();
// See comments in Attach().
this.isZombie = true;
}
}
catch
{
// Do not throw exceptions back!
}
}
internal void Close()
{
//Unregister from Appdomain event to remove ourselves from GCRoot.
AppDomain.CurrentDomain.ProcessExit -= OnDomainUnload;
AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;
if (!this.isZombie)
{
Stop(null, new WorkflowRuntimeEventArgs(false));
}
}
private void OnInstanceEvent(object sender, WorkflowExecutor.WorkflowExecutionEventArgs e)
{
switch (e.EventType)
{
case WorkflowEventInternal.Completed:
InstanceCompleted(sender, new WorkflowEventArgs(((WorkflowExecutor)sender).WorkflowInstance));
break;
case WorkflowEventInternal.Terminated:
InstanceTerminated(sender, new WorkflowEventArgs(((WorkflowExecutor)sender).WorkflowInstance));
break;
case WorkflowEventInternal.Unloaded:
InstanceUnloaded(sender, new WorkflowEventArgs(((WorkflowExecutor)sender).WorkflowInstance));
break;
case WorkflowEventInternal.Changed:
OnWorkflowChanged(sender, e);
break;
case WorkflowEventInternal.HandlerInvoking:
OnHandlerInvoking(sender, e);
break;
case WorkflowEventInternal.HandlerInvoked:
OnHandlerInvoked(sender, e);
break;
case WorkflowEventInternal.ActivityStatusChange:
OnActivityStatusChanged(sender, (WorkflowExecutor.ActivityStatusChangeEventArgs)e);
break;
case WorkflowEventInternal.ActivityExecuting:
OnActivityExecuting(sender, (WorkflowExecutor.ActivityExecutingEventArgs)e);
break;
default:
return;
}
}
private void InstanceInitializing(object sender, WorkflowRuntime.WorkflowExecutorInitializingEventArgs e)
{
try
{
if (e.Loading)
LoadExistingInstance(((WorkflowExecutor)sender).WorkflowInstance, true);
else
LoadExistingInstance(((WorkflowExecutor)sender).WorkflowInstance, false);
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void InstanceCompleted(object sender, WorkflowEventArgs args)
{
try
{
UnloadExistingInstance(args.WorkflowInstance);
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void InstanceTerminated(object sender, WorkflowEventArgs args)
{
try
{
UnloadExistingInstance(args.WorkflowInstance);
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void InstanceUnloaded(object sender, WorkflowEventArgs args)
{
// Treat this as if the instance completed so that it won't show up in the UI anymore.
try
{
UnloadExistingInstance(args.WorkflowInstance);
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void ScheduleTypeLoaded(object sender, WorkflowDefinitionEventArgs args)
{
try
{
if (args.WorkflowType != null)
{
Activity rootActivity = ((WorkflowRuntime)sender).DefinitionDispenser.GetWorkflowDefinition(args.WorkflowType);
LoadExistingScheduleType(GetScheduleTypeId(args.WorkflowType), args.WorkflowType, false, rootActivity);
}
else
{
Activity rootActivity = ((WorkflowRuntime)sender).DefinitionDispenser.GetWorkflowDefinition(args.WorkflowDefinitionHashCode);
LoadExistingScheduleType(GetScheduleTypeId(args.WorkflowDefinitionHashCode), rootActivity.GetType(), false, rootActivity);
}
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void OnActivityExecuting(object sender, WorkflowExecutor.ActivityExecutingEventArgs eventArgs)
{
if (this.isZombie || !this.isAttached)
return;
try
{
lock (this.eventLock)
{
IWorkflowCoreRuntime workflowCoreRuntime = (IWorkflowCoreRuntime)sender;
Guid scheduleTypeId = GetScheduleTypeId(workflowCoreRuntime);
// When the activity starts executing, update its handler list for stepping.
EnumerateEventHandlersForActivity(scheduleTypeId, eventArgs.Activity);
this.controllerConduit.BeforeActivityStatusChanged(this.programId, scheduleTypeId, workflowCoreRuntime.InstanceID, eventArgs.Activity.QualifiedName, GetHierarchicalId(eventArgs.Activity), eventArgs.Activity.ExecutionStatus, GetContextId(eventArgs.Activity));
this.controllerConduit.ActivityStatusChanged(this.programId, scheduleTypeId, workflowCoreRuntime.InstanceID, eventArgs.Activity.QualifiedName, GetHierarchicalId(eventArgs.Activity), eventArgs.Activity.ExecutionStatus, GetContextId(eventArgs.Activity));
}
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void OnActivityStatusChanged(object sender, WorkflowExecutor.ActivityStatusChangeEventArgs eventArgs)
{
if (this.isZombie || !this.isAttached)
return;
try
{
lock (this.eventLock)
{
// We will receive an event when Activity.Execute() is about to be called.
if (eventArgs.Activity.ExecutionStatus == ActivityExecutionStatus.Executing)
return;
IWorkflowCoreRuntime workflowCoreRuntime = (IWorkflowCoreRuntime)sender;
Guid scheduleTypeId = GetScheduleTypeId(workflowCoreRuntime);
// When the activity starts executing, update its handler list for stepping.
if (eventArgs.Activity.ExecutionStatus == ActivityExecutionStatus.Executing)
EnumerateEventHandlersForActivity(scheduleTypeId, eventArgs.Activity);
this.controllerConduit.BeforeActivityStatusChanged(this.programId, scheduleTypeId, workflowCoreRuntime.InstanceID, eventArgs.Activity.QualifiedName, GetHierarchicalId(eventArgs.Activity), eventArgs.Activity.ExecutionStatus, GetContextId(eventArgs.Activity));
this.controllerConduit.ActivityStatusChanged(this.programId, scheduleTypeId, workflowCoreRuntime.InstanceID, eventArgs.Activity.QualifiedName, GetHierarchicalId(eventArgs.Activity), eventArgs.Activity.ExecutionStatus, GetContextId(eventArgs.Activity));
}
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void OnHandlerInvoking(object sender, EventArgs eventArgs)
{
// Undone: AkashS - We need to remove EnumerateHandlersForActivity() and set the CPDE
// breakpoints from here. This is handle the cases where event handlers are modified
// at runtime.
}
private void OnHandlerInvoked(object sender, EventArgs eventArgs)
{
if (this.isZombie || !this.isAttached)
return;
try
{
lock (this.eventLock)
{
IWorkflowCoreRuntime workflowCoreRuntime = sender as IWorkflowCoreRuntime;
this.controllerConduit.HandlerInvoked(this.programId, workflowCoreRuntime.InstanceID, NativeMethods.GetCurrentThreadId(), GetHierarchicalId(workflowCoreRuntime.CurrentActivity));
}
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
private void OnWorkflowChanged(object sender, EventArgs eventArgs)
{
if (this.isZombie || !this.isAttached)
return;
try
{
lock (this.eventLock)
{
IWorkflowCoreRuntime workflowCoreRuntime = (IWorkflowCoreRuntime)sender;
// Get cached old root activity.
Activity oldRootActivity = this.instanceTable.GetRootActivity(workflowCoreRuntime.InstanceID);
Guid scheduleTypeId = workflowCoreRuntime.InstanceID; // From now on we will treat the instance id as a dynamic schedule type id.
LoadExistingScheduleType(scheduleTypeId, oldRootActivity.GetType(), true, oldRootActivity);
// And now reload the instance.
this.instanceTable.UpdateRootActivity(workflowCoreRuntime.InstanceID, oldRootActivity);
// The DE will update the schedule type on the thread that is running the instance.
// DE should be called after the instance table entry is replaced.
this.controllerConduit.InstanceDynamicallyUpdated(this.programId, workflowCoreRuntime.InstanceID, scheduleTypeId);
}
}
catch
{
// Don't throw exceptions to the Runtime. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
#endregion
#region Helper methods and properties
// Callers of this method should acquire the executor lock only if they
// are not being called in the runtime thread.(bug 17231).
private void LoadExistingInstance(WorkflowInstance instance, bool attaching)
{
WorkflowExecutor executor = instance.GetWorkflowResourceUNSAFE();
if (!executor.IsInstanceValid)
return;
IWorkflowCoreRuntime runtimeService = (IWorkflowCoreRuntime)executor;
Activity rootActivity = runtimeService.RootActivity;
Guid scheduleTypeId = GetScheduleTypeId(runtimeService);
// If we are just attaching, need to LoadExistingScheduleType with the dynamic definition and type
// since the OnDynamicUpdateEvent has never been executed.
if (attaching && runtimeService.IsDynamicallyUpdated)
LoadExistingScheduleType(scheduleTypeId, rootActivity.GetType(), true, rootActivity);
// Add to the InstanceTable before firing the DE event !
this.instanceTable.AddInstance(instance.InstanceId, rootActivity);
this.controllerConduit.InstanceCreated(this.programId, instance.InstanceId, scheduleTypeId);
// Take a lock so that SetInitialActivityStatus is always called before next status events.
lock (this.eventLock)
{
executor.WorkflowExecutionEvent += OnInstanceEvent;
foreach (Activity activity in DebugController.WalkActivityTree(rootActivity))
{
#if false
//
ReplicatorActivity replicator = activity as ReplicatorActivity;
if (replicator != null)
{
foreach (Activity queuedChildActivity in replicator.DynamicActivities)
activityQueue.Enqueue(queuedChildActivity);
}
else
#endif
UpdateActivityStatus(scheduleTypeId, instance.InstanceId, activity);
}
ActivityExecutionContext rootExecutionContext = new ActivityExecutionContext(rootActivity);
foreach (ActivityExecutionContext executionContext in DebugController.WalkExecutionContextTree(rootExecutionContext))
{
Activity instanceActivity = executionContext.Activity;
foreach (Activity childInstance in DebugController.WalkActivityTree(instanceActivity))
{
UpdateActivityStatus(scheduleTypeId, instance.InstanceId, childInstance);
}
}
}
}
private void UpdateActivityStatus(Guid scheduleTypeId, Guid instanceId, Activity activity)
{
if (activity == null)
throw new ArgumentNullException("activity");
// first update its handler list
if (activity.ExecutionStatus == ActivityExecutionStatus.Executing)
EnumerateEventHandlersForActivity(scheduleTypeId, activity);
//report only states different from the initialized
if (activity.ExecutionStatus != ActivityExecutionStatus.Initialized)
{
Activity contextActivity = ContextActivityUtils.ContextActivity(activity);
int context = ContextActivityUtils.ContextId(contextActivity);
this.controllerConduit.SetInitialActivityStatus(this.programId, scheduleTypeId, instanceId, activity.QualifiedName, GetHierarchicalId(activity), activity.ExecutionStatus, context);
}
}
private static IEnumerable WalkActivityTree(Activity rootActivity)
{
if (rootActivity == null || !rootActivity.Enabled)
yield break;
// Return self
yield return rootActivity;
// Go through the children as well
if (rootActivity is CompositeActivity)
{
foreach (Activity childActivity in ((CompositeActivity)rootActivity).Activities)
{
foreach (Activity nestedChild in WalkActivityTree(childActivity))
yield return nestedChild;
}
}
}
private static IEnumerable WalkExecutionContextTree(ActivityExecutionContext rootContext)
{
if (rootContext == null)
yield break;
yield return rootContext;
foreach (ActivityExecutionContext executionContext in rootContext.ExecutionContextManager.ExecutionContexts)
{
foreach (ActivityExecutionContext nestedContext in WalkExecutionContextTree(executionContext))
yield return nestedContext;
}
yield break;
}
private void UnloadExistingInstance(WorkflowInstance instance)
{
// Fire DE event before removing from the InstanceTable!
this.controllerConduit.InstanceCompleted(this.programId, instance.InstanceId);
this.instanceTable.RemoveInstance(instance.InstanceId);
}
private void LoadExistingScheduleType(Guid scheduleTypeId, Type scheduleType, bool isDynamic, Activity rootActivity)
{
if (rootActivity == null)
throw new InvalidOperationException();
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(stringWriter))
{
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
serializer.Serialize(xmlWriter, rootActivity);
string fileName = null;
string md5Digest = null;
Attribute[] attributes = scheduleType.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false) as Attribute[];
if (attributes != null && attributes.Length == 1)
{
fileName = ((WorkflowMarkupSourceAttribute)attributes[0]).FileName;
md5Digest = ((WorkflowMarkupSourceAttribute)attributes[0]).MD5Digest;
}
this.controllerConduit.ScheduleTypeLoaded(this.programId, scheduleTypeId, scheduleType.Assembly.FullName, fileName, md5Digest, isDynamic, scheduleType.FullName, scheduleType.Name, stringWriter.ToString());
}
}
}
private string GetHierarchicalId(Activity activity)
{
string id = string.Empty;
while (activity != null)
{
string iterationId = string.Empty;
Activity contextActivity = ContextActivityUtils.ContextActivity(activity);
int context = ContextActivityUtils.ContextId(contextActivity);
iterationId = activity.Name + ((context > 1 && activity == contextActivity) ? "(" + context + ")" : string.Empty);
id = (id.Length > 0) ? iterationId + "." + id : iterationId;
activity = activity.Parent;
}
return id;
}
private int GetContextId(Activity activity)
{
Activity contextActivity = ContextActivityUtils.ContextActivity(activity);
return ContextActivityUtils.ContextId(contextActivity);
}
private Guid GetScheduleTypeId(IWorkflowCoreRuntime workflowCoreRuntime)
{
Activity rootActivity = workflowCoreRuntime.RootActivity;
if (workflowCoreRuntime.IsDynamicallyUpdated)
return workflowCoreRuntime.InstanceID;
else if (string.IsNullOrEmpty(rootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string))
return GetScheduleTypeId(rootActivity.GetType());
else
return GetScheduleTypeId(rootActivity.GetValue(WorkflowDefinitionDispenser.WorkflowDefinitionHashCodeProperty) as byte[]);
}
private Guid GetScheduleTypeId(Type scheduleType)
{
// We cannot use the GUID from the type because that is not guaranteed to be unique, especially when
// multiple versions are loaded and the stamps a GuidAttribute.
lock (this.typeToGuid)
{
if (!this.typeToGuid.ContainsKey(scheduleType))
this.typeToGuid[scheduleType] = Guid.NewGuid();
return (Guid)this.typeToGuid[scheduleType];
}
}
private Guid GetScheduleTypeId(byte[] scheduleDefHashCode)
{
// We use the same hashtable to store schedule definition to Guid mapping.
lock (this.xomlHashToGuid)
{
if (!this.xomlHashToGuid.ContainsKey(scheduleDefHashCode))
this.xomlHashToGuid[scheduleDefHashCode] = Guid.NewGuid();
return (Guid)this.xomlHashToGuid[scheduleDefHashCode];
}
}
private void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
// Call assembly load on the conduit for assemblies loaded from disk.
if (args.LoadedAssembly.Location != String.Empty)
{
try
{
this.controllerConduit.AssemblyLoaded(this.programId, args.LoadedAssembly.Location, args.LoadedAssembly.GlobalAssemblyCache);
}
catch
{
// Don't throw exceptions to the CLR. Ignore exceptions that may occur if the debugger detaches
// and closes the remoting channel.
}
}
}
private void EnumerateEventHandlersForActivity(Guid scheduleTypeId, Activity activity)
{
List<ActivityHandlerDescriptor> handlerMethods = new List<ActivityHandlerDescriptor>();
MethodInfo getInvocationListMethod = activity.GetType().GetMethod("System.Workflow.ComponentModel.IDependencyObjectAccessor.GetInvocationList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
foreach (EventInfo eventInfo in activity.GetType().GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
{
DependencyProperty dependencyEvent = DependencyProperty.FromName(eventInfo.Name, activity.GetType());
if (dependencyEvent != null)
{
try
{
MethodInfo boundGetInvocationListMethod = getInvocationListMethod.MakeGenericMethod(new Type[] { dependencyEvent.PropertyType });
foreach (Delegate handler in (boundGetInvocationListMethod.Invoke(activity, new object[] { dependencyEvent }) as Delegate[]))
{
MethodInfo handlerMethodInfo = handler.Method;
ActivityHandlerDescriptor handlerMethod;
handlerMethod.Name = handlerMethodInfo.DeclaringType.FullName + "." + handlerMethodInfo.Name;
handlerMethod.Token = handlerMethodInfo.MetadataToken;
handlerMethods.Add(handlerMethod);
}
}
catch
{
}
}
}
this.controllerConduit.UpdateHandlerMethodsForActivity(this.programId, scheduleTypeId, activity.QualifiedName, handlerMethods);
}
#endregion
}
}
| |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;
using FluentAssertions.Collections;
using FluentAssertions.Common;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace Tests.Core.Extensions
{
public static class ReadOnlyDictionaryShouldExtensions
{
public static ReadOnlyDictionaryAssertions<TKey, TValue> Should<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> actualValue) =>
new ReadOnlyDictionaryAssertions<TKey, TValue>(actualValue);
public static GenericDictionaryAssertions<TKey, TValue> Should<TKey, TValue>(this Dictionary<TKey, TValue> actualValue) =>
new GenericDictionaryAssertions<TKey, TValue>(actualValue);
}
public class WhichValueConstraint<TKey, TValue> : AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>
{
public WhichValueConstraint(ReadOnlyDictionaryAssertions<TKey, TValue> parentConstraint, TValue value)
: base(parentConstraint) => WhichValue = value;
/// <summary>Gets the value of the object referred to by the key.</summary>
public TValue WhichValue { get; private set; }
}
/// <summary>
/// Contains a number of methods to assert that an <see cref="IDictionary{TKey,TValue}" /> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class ReadOnlyDictionaryAssertions<TKey, TValue>
: ReferenceTypeAssertions<IReadOnlyDictionary<TKey, TValue>, ReadOnlyDictionaryAssertions<TKey, TValue>>
{
public ReadOnlyDictionaryAssertions(IReadOnlyDictionary<TKey, TValue> dictionary)
{
if (dictionary != null) Subject = dictionary;
}
protected override string Identifier => "dictionary";
/// <summary>
/// Asserts that the number of items in the dictionary matches the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The expected number of items.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> HaveCount(int expected,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {0} item(s){reason}, but found {1}.", expected, Subject);
var actualCount = Subject.Count;
Execute.Assertion
.ForCondition(actualCount == expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to have {1} item(s){reason}, but found {2}.", Subject, expected, actualCount);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the number of items in the dictionary matches a condition stated by a predicate.
/// </summary>
/// <param name="countPredicate">The predicate which must be satisfied by the amount of items.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> HaveCount(Expression<Func<int, bool>> countPredicate,
string because = "", params object[] becauseArgs
)
{
if (countPredicate == null) throw new NullReferenceException("Cannot compare dictionary count against a <null> predicate.");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to have {0} items{reason}, but found {1}.", countPredicate.Body, Subject);
var compiledPredicate = countPredicate.Compile();
var actualCount = Subject.Count;
if (!compiledPredicate(actualCount))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to have a count {1}{reason}, but count is {2}.",
Subject, countPredicate.Body, actualCount);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary does not contain any items.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> BeEmpty(string because = "", params object[] becauseArgs)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to be empty{reason}, but found {0}.", Subject);
Execute.Assertion
.ForCondition(!Subject.Any())
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to not have any items{reason}, but found {0}.", Subject.Count);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary contains at least 1 item.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotBeEmpty(string because = "",
params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} not to be empty{reason}, but found {0}.", Subject);
Execute.Assertion
.ForCondition(Subject.Any())
.BecauseOf(because, becauseArgs)
.FailWith("Expected one or more items{reason}, but found none.");
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary contains all the same key-value pairs as the
/// specified <paramref name="expected" /> dictionary. Keys and values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected dictionary</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> Equal(IReadOnlyDictionary<TKey, TValue> expected,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but found {1}.", expected, Subject);
if (expected == null) throw new ArgumentNullException("expected", "Cannot compare dictionary with <null>.");
var missingKeys = expected.Keys.Except(Subject.Keys);
var additionalKeys = Subject.Keys.Except(expected.Keys);
if (missingKeys.Any())
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but could not find keys {1}.", expected,
missingKeys);
if (additionalKeys.Any())
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but found additional keys {1}.", expected,
additionalKeys);
foreach (var key in expected.Keys)
Execute.Assertion
.ForCondition(Subject[key].IsSameOrEqualTo(expected[key]))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to be equal to {0}{reason}, but {1} differs at key {2}.",
expected, Subject, key);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts the current dictionary not to contain all the same key-value pairs as the
/// specified <paramref name="unexpected" /> dictionary. Keys and values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected dictionary</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotEqual(IReadOnlyDictionary<TKey, TValue> unexpected,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected dictionaries not to be equal{reason}, but found {0}.", Subject);
if (unexpected == null) throw new ArgumentNullException("unexpected", "Cannot compare dictionary with <null>.");
var missingKeys = unexpected.Keys.Except(Subject.Keys);
var additionalKeys = Subject.Keys.Except(unexpected.Keys);
var foundDifference = missingKeys.Any()
|| additionalKeys.Any()
|| Subject.Keys.Any(key => !Subject[key].IsSameOrEqualTo(unexpected[key]));
if (!foundDifference)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect dictionaries {0} and {1} to be equal{reason}.", unexpected, Subject);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary contains the specified key. Keys are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected key</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public WhichValueConstraint<TKey, TValue> ContainKey(TKey expected,
string because = "", params object[] becauseArgs
)
{
var andConstraint = ContainKeys(new[] { expected }, because, becauseArgs);
return new WhichValueConstraint<TKey, TValue>(andConstraint.And, Subject[expected]);
}
/// <summary>
/// Asserts that the dictionary contains all of the specified keys. Keys are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected keys</param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> ContainKeys(params TKey[] expected) => ContainKeys(expected, string.Empty);
/// <summary>
/// Asserts that the dictionary contains all of the specified keys. Keys are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected keys</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> ContainKeys(IEnumerable<TKey> expected,
string because = "", params object[] becauseArgs
)
{
if (expected == null) throw new NullReferenceException("Cannot verify key containment against a <null> collection of keys");
var enumerable = expected as TKey[] ?? expected.ToArray();
var expectedKeys = enumerable.ToArray();
if (!expectedKeys.Any()) throw new ArgumentException("Cannot verify key containment against an empty sequence");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain keys {0}{reason}, but found {1}.", expected, Subject);
var missingKeys = expectedKeys.Where(key => !Subject.ContainsKey(key));
if (missingKeys.Any())
{
if (expectedKeys.Count() > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain key {1}{reason}, but could not find {2}.", Subject,
expected, missingKeys);
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain key {1}{reason}.", Subject,
enumerable.Cast<object>().First());
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary does not contain the specified <paramref name="unexpected" /> key.
/// Keys are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected key</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainKey(TKey unexpected,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} not to contain key {0}{reason}, but found {1}.", unexpected, Subject);
if (Subject.ContainsKey(unexpected))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("{context:Dictionary} {0} should not contain key {1}{reason}, but found it anyhow.", Subject, unexpected);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary does not contain any of the specified keys. Keys are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected keys</param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainKeys(params TKey[] unexpected) =>
NotContainKeys(unexpected, string.Empty);
/// <summary>
/// Asserts that the dictionary does not contain any of the specified keys. Keys are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected keys</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainKeys(IEnumerable<TKey> unexpected,
string because = "", params object[] becauseArgs
)
{
if (unexpected == null) throw new NullReferenceException("Cannot verify key containment against a <null> collection of keys");
var enumerable = unexpected as TKey[] ?? unexpected.ToArray();
var unexpectedKeys = enumerable.ToArray();
if (!unexpectedKeys.Any()) throw new ArgumentException("Cannot verify key containment against an empty sequence");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain keys {0}{reason}, but found {1}.", unexpected, Subject);
var foundKeys = unexpectedKeys.Intersect(Subject.Keys);
if (foundKeys.Any())
{
if (unexpectedKeys.Count() > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to not contain key {1}{reason}, but found {2}.", Subject,
unexpected, foundKeys);
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to not contain key {1}{reason}.", Subject,
enumerable.Cast<object>().First());
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary contains the specified value. Values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>, TValue> ContainValue(TValue expected,
string because = "", params object[] becauseArgs
)
{
var innerConstraint =
ContainValuesAndWhich(new[] { expected }, because, becauseArgs);
return
new AndWhichConstraint
<ReadOnlyDictionaryAssertions<TKey, TValue>, TValue>(
innerConstraint.And, innerConstraint.Which);
}
/// <summary>
/// Asserts that the dictionary contains all of the specified values. Values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected values</param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> ContainValues(params TValue[] expected) =>
ContainValues(expected, string.Empty);
/// <summary>
/// Asserts that the dictionary contains all of the specified values. Values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected values</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> ContainValues(IEnumerable<TValue> expected,
string because = "", params object[] becauseArgs
) => ContainValuesAndWhich(expected, because, becauseArgs);
private AndWhichConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>, IEnumerable<TValue>> ContainValuesAndWhich(
IEnumerable<TValue> expected, string because = "",
params object[] becauseArgs
)
{
if (expected == null) throw new NullReferenceException("Cannot verify value containment against a <null> collection of values");
var enumerable = expected as TValue[] ?? expected.ToArray();
var expectedValues = enumerable.ToArray();
if (!expectedValues.Any()) throw new ArgumentException("Cannot verify value containment with an empty sequence");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain value {0}{reason}, but found {1}.", expected, Subject);
var missingValues = expectedValues.Except(Subject.Values);
if (missingValues.Any())
{
if (expectedValues.Length > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain value {1}{reason}, but could not find {2}.", Subject,
expected, missingValues);
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain value {1}{reason}.", Subject,
enumerable.Cast<object>().First());
}
return
new AndWhichConstraint
<ReadOnlyDictionaryAssertions<TKey, TValue>,
IEnumerable<TValue>>(this,
RepetitionPreservingIntersect(Subject.Values, expectedValues));
}
/// <summary>
/// Returns an enumerable consisting of all items in the first collection also appearing in the second.
/// </summary>
/// <remarks>Enumerable.Intersect is not suitable because it drops any repeated elements.</remarks>
private IEnumerable<TValue> RepetitionPreservingIntersect(
IEnumerable<TValue> first, IEnumerable<TValue> second
)
{
var secondSet = new HashSet<TValue>(second);
return first.Where(secondSet.Contains);
}
/// <summary>
/// Asserts that the current dictionary does not contain the specified <paramref name="unexpected" /> value.
/// Values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected value</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainValue(TValue unexpected,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} not to contain value {0}{reason}, but found {1}.", unexpected, Subject);
if (Subject.Values.Contains(unexpected))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("{context:Dictionary} {0} should not contain value {1}{reason}, but found it anyhow.", Subject, unexpected);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the dictionary does not contain any of the specified values. Values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected values</param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainValues(params TValue[] unexpected) =>
NotContainValues(unexpected, string.Empty);
/// <summary>
/// Asserts that the dictionary does not contain any of the specified values. Values are compared using
/// their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected values</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContainValues(IEnumerable<TValue> unexpected,
string because = "", params object[] becauseArgs
)
{
if (unexpected == null) throw new NullReferenceException("Cannot verify value containment against a <null> collection of values");
var enumerable = unexpected as TValue[] ?? unexpected.ToArray();
var unexpectedValues = enumerable.ToArray();
if (!unexpectedValues.Any()) throw new ArgumentException("Cannot verify value containment with an empty sequence");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to not contain value {0}{reason}, but found {1}.", unexpected, Subject);
var foundValues = unexpectedValues.Intersect(Subject!.Values);
if (foundValues.Any())
{
if (unexpectedValues.Length > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to not contain value {1}{reason}, but found {2}.", Subject,
unexpected, foundValues);
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to not contain value {1}{reason}.", Subject,
enumerable.Cast<object>().First());
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary contains the specified <paramref name="expected" />.
/// Keys and values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected key/value pairs.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> Contain(IEnumerable<KeyValuePair<TKey, TValue>> expected,
string because = "", params object[] becauseArgs
)
{
if (expected == null) throw new ArgumentNullException("expected", "Cannot compare dictionary with <null>.");
var expectedKeyValuePairs = expected.ToArray();
if (!expectedKeyValuePairs.Any())
throw new ArgumentException("Cannot verify key containment against an empty collection of key/value pairs");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain key/value pairs {0}{reason}, but dictionary is {1}.", expected, Subject);
var expectedKeys = expectedKeyValuePairs.Select(keyValuePair => keyValuePair.Key).ToArray();
var missingKeys = expectedKeys.Where(key => !Subject.ContainsKey(key));
if (missingKeys.Any())
{
if (expectedKeyValuePairs.Count() > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain key(s) {1}{reason}, but could not find keys {2}.", Subject,
expectedKeys, missingKeys);
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} {0} to contain key {1}{reason}.", Subject,
expectedKeys.Cast<object>().First());
}
var keyValuePairsNotSameOrEqualInSubject = expectedKeyValuePairs
.Where(keyValuePair => !Subject[keyValuePair.Key].IsSameOrEqualTo(keyValuePair.Value))
.ToArray();
if (keyValuePairsNotSameOrEqualInSubject.Any())
{
if (keyValuePairsNotSameOrEqualInSubject.Count() > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain {0}{reason}, but {context:dictionary} differs at keys {1}.",
expectedKeyValuePairs, keyValuePairsNotSameOrEqualInSubject.Select(keyValuePair => keyValuePair.Key));
else
{
var expectedKeyValuePair = keyValuePairsNotSameOrEqualInSubject.First();
var actual = Subject![expectedKeyValuePair.Key];
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but found {2}.", expectedKeyValuePair.Value,
expectedKeyValuePair.Key, actual);
}
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary contains the specified <paramref name="expected" />.
/// Keys and values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected <see cref="KeyValuePair{TKey,TValue}" /></param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> Contain(KeyValuePair<TKey, TValue> expected,
string because = "", params object[] becauseArgs
) => Contain(expected.Key, expected.Value, because, becauseArgs);
/// <summary>
/// Asserts that the current dictionary contains the specified <paramref name="value" /> for the supplied
/// <paramref
/// name="key" />
/// . Values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="key">The key for which to validate the value</param>
/// <param name="value">The value to validate</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> Contain(TKey key, TValue value,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but dictionary is {2}.", value, key,
Subject);
if (Subject.ContainsKey(key))
{
var actual = Subject[key];
Execute.Assertion
.ForCondition(actual.IsSameOrEqualTo(value))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but found {2}.", value, key, actual);
}
else
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to contain value {0} at key {1}{reason}, but the key was not found.", value,
key);
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary does not contain the specified <paramref name="items" />.
/// Keys and values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="items">The unexpected key/value pairs</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContain(IEnumerable<KeyValuePair<TKey, TValue>> items,
string because = "", params object[] becauseArgs
)
{
if (items == null) throw new ArgumentNullException("items", "Cannot compare dictionary with <null>.");
var keyValuePairs = items.ToArray();
if (!keyValuePairs.Any()) throw new ArgumentException("Cannot verify key containment against an empty collection of key/value pairs");
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to not contain key/value pairs {0}{reason}, but dictionary is {1}.", items, Subject);
var keyValuePairsFound = keyValuePairs.Where(keyValuePair => Subject.ContainsKey(keyValuePair.Key)).ToArray();
if (keyValuePairsFound.Any())
{
var keyValuePairsSameOrEqualInSubject =
keyValuePairsFound.Where(keyValuePair => Subject[keyValuePair.Key].IsSameOrEqualTo(keyValuePair.Value)).ToArray();
if (keyValuePairsSameOrEqualInSubject.Any())
{
if (keyValuePairsSameOrEqualInSubject.Count() > 1)
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to not contain key/value pairs {0}{reason}, but found them anyhow.",
keyValuePairs);
else
{
var keyValuePair = keyValuePairsSameOrEqualInSubject.First();
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} to not contain value {0} at key {1}{reason}, but found it anyhow.",
keyValuePair.Value, keyValuePair.Key);
}
}
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
/// <summary>
/// Asserts that the current dictionary does not contain the specified <paramref name="item" />.
/// Keys and values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="item">The unexpected <see cref="KeyValuePair{TKey,TValue}" /></param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContain(KeyValuePair<TKey, TValue> item,
string because = "", params object[] becauseArgs
) => NotContain(item.Key, item.Value, because, becauseArgs);
/// <summary>
/// Asserts that the current dictionary does not contain the specified <paramref name="value" /> for the
/// supplied <paramref name="key" />. Values are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="key">The key for which to validate the value</param>
/// <param name="value">The value to validate</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>> NotContain(TKey key, TValue value,
string because = "", params object[] becauseArgs
)
{
if (ReferenceEquals(Subject, null))
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} not to contain value {0} at key {1}{reason}, but dictionary is {2}.", value,
key, Subject);
if (Subject!.ContainsKey(key))
{
var actual = Subject[key];
Execute.Assertion
.ForCondition(!actual.IsSameOrEqualTo(value))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:dictionary} not to contain value {0} at key {1}{reason}, but found it anyhow.", value, key);
}
return new AndConstraint<ReadOnlyDictionaryAssertions<TKey, TValue>>(this);
}
}
}
| |
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 RabbitFarm.WebAPI.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.IO;
using Xunit;
namespace SemanticReleaseNotesParser.Core.Tests
{
public class SemanticReleaseNotesParserTest
{
[Fact]
public void Parse_Null_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => Parser.SemanticReleaseNotesParser.Parse((string)null));
Assert.Equal("rawReleaseNotes", exception.ParamName);
}
[Fact]
public void Parse_StringEmpty_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => Parser.SemanticReleaseNotesParser.Parse(string.Empty));
Assert.Equal("rawReleaseNotes", exception.ParamName);
}
[Fact]
public void Parse_WhiteSpace_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => Parser.SemanticReleaseNotesParser.Parse(" "));
Assert.Equal("rawReleaseNotes", exception.ParamName);
}
[Fact]
public void Parse_TextReader_Null_Exception()
{
// act & assert
var exception = Assert.Throws<ArgumentNullException>(() => Parser.SemanticReleaseNotesParser.Parse((TextReader)null));
Assert.Equal("reader", exception.ParamName);
}
[Fact]
public void Parse_Syntax_Summaries()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Summaries);
// assert
Assert.Equal(@"This is a _project_ summary with two paragraphs.Lorem ipsum dolor sit amet consectetuer **adipiscing** elit.Aliquam hendreritmi posuere lectus.
Vestibulum `enim wisi` viverra nec fringilla in laoreetvitae risus. Donec sit amet nisl. Aliquam [semper](?) ipsumsit amet velit.", releaseNote.Summary);
}
[Fact]
public void Parse_TextReader_Syntax_Summaries()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(GetTextReader(Syntax_Summaries));
// assert
Assert.Equal(@"This is a _project_ summary with two paragraphs.Lorem ipsum dolor sit amet consectetuer **adipiscing** elit.Aliquam hendreritmi posuere lectus.
Vestibulum `enim wisi` viverra nec fringilla in laoreetvitae risus. Donec sit amet nisl. Aliquam [semper](?) ipsumsit amet velit.", releaseNote.Summary);
}
[Fact]
public void Parse_Syntax_Items()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Items);
// assert
Assert.Equal(4, releaseNote.Items.Count);
Assert.Equal("This is the _first_ *list* item.", releaseNote.Items[0].Summary);
Assert.Equal("This is the **second** __list__ item.", releaseNote.Items[1].Summary);
Assert.Equal("This is the `third` list item.", releaseNote.Items[2].Summary);
Assert.Equal("This is the [forth](?) list item.", releaseNote.Items[3].Summary);
}
[Fact]
public void Parse_Syntax_Sections()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Sections);
// assert
Assert.Equal(2, releaseNote.Sections.Count);
Assert.Equal("Section", releaseNote.Sections[0].Name);
Assert.Equal("This is the summary for Section.", releaseNote.Sections[0].Summary);
Assert.Equal(2, releaseNote.Sections[0].Items.Count);
Assert.Equal("This is a Section scoped first list item.", releaseNote.Sections[0].Items[0].Summary);
Assert.Equal("This is a Section scoped second list item.", releaseNote.Sections[0].Items[1].Summary);
Assert.Equal("Other Section", releaseNote.Sections[1].Name);
Assert.Equal("This is the summary for Other Section.", releaseNote.Sections[1].Summary);
Assert.Equal(2, releaseNote.Sections[1].Items.Count);
Assert.Equal("This is a Other Section scoped first list item.", releaseNote.Sections[1].Items[0].Summary);
Assert.Equal("This is a Other Section scoped second list item.", releaseNote.Sections[1].Items[1].Summary);
}
[Fact]
public void Parse_Syntax_Priority()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Priority);
// assert
Assert.Equal(string.Empty, releaseNote.Summary);
Assert.Equal(7, releaseNote.Items.Count);
Assert.Equal(1, releaseNote.Items[0].Priority);
Assert.Equal("This is a High priority list item.", releaseNote.Items[0].Summary);
Assert.Equal(1, releaseNote.Items[1].Priority);
Assert.Equal("This is a High priority list item.", releaseNote.Items[1].Summary);
Assert.Equal(2, releaseNote.Items[2].Priority);
Assert.Equal("This is a Normal priority list item.", releaseNote.Items[2].Summary);
Assert.Equal(1, releaseNote.Items[3].Priority);
Assert.Equal("This is a High priority list item.", releaseNote.Items[3].Summary);
Assert.Equal(2, releaseNote.Items[4].Priority);
Assert.Equal("This is a Normal priority list item.", releaseNote.Items[4].Summary);
Assert.Equal(3, releaseNote.Items[5].Priority);
Assert.Equal("This is a Minor priority list item.", releaseNote.Items[5].Summary);
Assert.Equal(3, releaseNote.Items[6].Priority);
Assert.Equal("This is a Minor priority list item.", releaseNote.Items[6].Summary);
}
[Fact]
public void Parse_Syntax_Category()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Category);
// assert
Assert.Equal(string.Empty, releaseNote.Summary);
Assert.Equal(10, releaseNote.Items.Count);
Assert.Equal("New", releaseNote.Items[0].Categories[0]);
Assert.Equal("This is a New list item.", releaseNote.Items[0].Summary);
Assert.Equal("Fix", releaseNote.Items[1].Categories[0]);
Assert.Equal("This is a Fix list item.", releaseNote.Items[1].Summary);
Assert.Equal("Change", releaseNote.Items[2].Categories[0]);
Assert.Equal("This is a Change list item.", releaseNote.Items[2].Summary);
Assert.Equal("New", releaseNote.Items[3].Categories[0]);
Assert.Equal("New features are everyone's favorites.", releaseNote.Items[3].Summary);
Assert.Equal("Developer", releaseNote.Items[4].Categories[0]);
Assert.Equal("This is a list item for a Developer.", releaseNote.Items[4].Summary);
Assert.Equal("Super Special", releaseNote.Items[5].Categories[0]);
Assert.Equal("This is a super-special custom list item.", releaseNote.Items[5].Summary);
Assert.Equal("O", releaseNote.Items[6].Categories[0]);
Assert.Equal("This is a o ne letter category.", releaseNote.Items[6].Summary);
Assert.Equal("Developer", releaseNote.Items[7].Categories[0]);
Assert.Equal("New", releaseNote.Items[7].Categories[1]);
Assert.Equal("This is my last DEVELOPER list item.", releaseNote.Items[7].Summary);
Assert.Empty(releaseNote.Items[8].Categories);
Assert.Equal("This is something without category.", releaseNote.Items[8].Summary);
Assert.Equal("New", releaseNote.Items[9].Categories[0]);
Assert.Equal("And this new with two same categories.", releaseNote.Items[9].Summary);
}
[Fact]
public void Parse_Example_A()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(ExampleA);
// assert
Assert.Equal("Incremental release designed to provide an update to some of the core plugins.", releaseNote.Summary);
Assert.Equal(4, releaseNote.Items.Count);
Assert.Equal("Release Checker: Now gives you a breakdown of exactly what you are missing.", releaseNote.Items[0].Summary);
Assert.Equal("New", releaseNote.Items[0].Categories[0]);
Assert.Equal("Structured Layout: An alternative layout engine that allows developers to control layout.", releaseNote.Items[1].Summary);
Assert.Equal("New", releaseNote.Items[1].Categories[0]);
Assert.Equal("Timeline: Comes with an additional grid view to show the same data.", releaseNote.Items[2].Summary);
Assert.Equal("Changed", releaseNote.Items[2].Categories[0]);
Assert.Equal("Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.", releaseNote.Items[3].Summary);
Assert.Equal("Fix", releaseNote.Items[3].Categories[0]);
}
[Fact]
public void Parse_Example_B()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(ExampleB);
// assert
Assert.Equal("Incremental release designed to provide an update to some of the core plugins.", releaseNote.Summary);
Assert.Empty(releaseNote.Items);
Assert.Equal(2, releaseNote.Sections.Count);
Assert.Equal("System", releaseNote.Sections[0].Name);
Assert.Equal(2, releaseNote.Sections[0].Items.Count);
Assert.Equal("*Release Checker*: Now gives you a breakdown of exactly what you are missing.", releaseNote.Sections[0].Items[0].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[0].Categories[0]);
Assert.Equal("*Structured Layout*: An alternative layout engine that allows developers to control layout.", releaseNote.Sections[0].Items[1].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[1].Categories[0]);
Assert.Equal("Plugin", releaseNote.Sections[1].Name);
Assert.Equal(2, releaseNote.Sections[1].Items.Count);
Assert.Equal("*Timeline*: Comes with an additional grid view to show the same data.", releaseNote.Sections[1].Items[0].Summary);
Assert.Equal("Changed", releaseNote.Sections[1].Items[0].Categories[0]);
Assert.Equal("*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.", releaseNote.Sections[1].Items[1].Summary);
Assert.Equal("Fix", releaseNote.Sections[1].Items[1].Categories[0]);
}
[Fact]
public void Parse_Example_C()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(ExampleC);
// assert
Assert.Equal("Incremental release designed to provide an update to some of the core plugins.", releaseNote.Summary);
Assert.Single(releaseNote.Items);
Assert.Equal("*Example*: You can have global issues that aren't grouped to a section", releaseNote.Items[0].Summary);
Assert.Equal(2, releaseNote.Sections.Count);
Assert.Equal("System", releaseNote.Sections[0].Name);
Assert.Equal("This description is specific to system section.", releaseNote.Sections[0].Summary);
Assert.Equal(2, releaseNote.Sections[0].Items.Count);
Assert.Equal("*Release Checker*: Now gives you a new breakdown of exactly what you are missing.", releaseNote.Sections[0].Items[0].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[0].Categories[0]);
Assert.Equal("*Structured Layout*: A new alternative layout engine that allows developers to control layout.", releaseNote.Sections[0].Items[1].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[1].Categories[0]);
Assert.Equal("Plugin", releaseNote.Sections[1].Name);
Assert.Equal("This description is specific to plugin section.", releaseNote.Sections[1].Summary);
Assert.Equal(2, releaseNote.Sections[1].Items.Count);
Assert.Equal("*Timeline*: Comes with an additional grid view to show the same data.", releaseNote.Sections[1].Items[0].Summary);
Assert.Equal("Changed", releaseNote.Sections[1].Items[0].Categories[0]);
Assert.Equal("*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.", releaseNote.Sections[1].Items[1].Summary);
Assert.Equal("Fix", releaseNote.Sections[1].Items[1].Categories[0]);
Assert.Equal("i1234", releaseNote.Sections[1].Items[1].TaskId);
Assert.Equal("http://getglimpse.com", releaseNote.Sections[1].Items[1].TaskLink);
}
[Fact]
public void Parse_Example_D()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(ExampleD);
// assert
Assert.Equal("Incremental release designed to provide an update to some of the core plugins.", releaseNote.Summary);
Assert.Single(releaseNote.Items);
Assert.Equal(1, releaseNote.Items[0].Priority);
Assert.Equal("*Example*: You can have global issues that aren't grouped to a section", releaseNote.Items[0].Summary);
Assert.Equal(2, releaseNote.Sections.Count);
Assert.Equal("System ", releaseNote.Sections[0].Name);
Assert.Equal("This description is specific to system section.", releaseNote.Sections[0].Summary);
Assert.Equal("http://getglimpse.com/release/icon/core.png", releaseNote.Sections[0].Icon);
Assert.Equal(2, releaseNote.Sections[0].Items.Count);
Assert.Equal("*Release Checker*: Now gives you a breakdown of exactly what you are missing.", releaseNote.Sections[0].Items[0].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[0].Categories[0]);
Assert.Equal(3, releaseNote.Sections[0].Items[0].Priority);
Assert.Equal("*Structured Layout*: An alternative layout engine that allows developers to control layout.", releaseNote.Sections[0].Items[1].Summary);
Assert.Equal("New", releaseNote.Sections[0].Items[1].Categories[0]);
Assert.Equal(2, releaseNote.Sections[0].Items[1].Priority);
Assert.Equal("Plugin ", releaseNote.Sections[1].Name);
Assert.Equal("This description is specific to plugin section.", releaseNote.Sections[1].Summary);
Assert.Equal("http://getglimpse.com/release/icon/mvc.png", releaseNote.Sections[1].Icon);
Assert.Equal(2, releaseNote.Sections[1].Items.Count);
Assert.Equal("*Timeline*: Comes with an additional grid view to show the same data.", releaseNote.Sections[1].Items[0].Summary);
Assert.Equal("Changed", releaseNote.Sections[1].Items[0].Categories[0]);
Assert.Equal(1, releaseNote.Sections[1].Items[1].Priority);
Assert.Equal("*Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement.", releaseNote.Sections[1].Items[1].Summary);
Assert.Equal("Fix", releaseNote.Sections[1].Items[1].Categories[0]);
Assert.Equal(1, releaseNote.Sections[1].Items[1].Priority);
Assert.Equal("i1234", releaseNote.Sections[1].Items[1].TaskId);
Assert.Equal("http://getglimpse.com", releaseNote.Sections[1].Items[1].TaskLink);
}
[Fact]
public void Parse_Real_NVika()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(NVikaReleaseNotes);
// assert
Assert.Single(releaseNote.Metadata);
Assert.Equal("Commits", releaseNote.Metadata[0].Name);
Assert.Equal("[19556f025b...0203ea9a43](https://github.com/laedit/vika/compare/19556f025b...0203ea9a43)", releaseNote.Metadata[0].Value);
Assert.Equal(3, releaseNote.Items.Count);
Assert.Equal("Enhancement", releaseNote.Items[0].Categories[0]);
Assert.Equal("[#9](https://github.com/laedit/vika/issues/9) - Handle multiple report files", releaseNote.Items[0].Summary);
Assert.Equal("Enhancement", releaseNote.Items[1].Categories[0]);
Assert.Equal("[#2](https://github.com/laedit/vika/issues/2) - Support AppVeyor", releaseNote.Items[1].Summary);
Assert.Equal("Enhancement", releaseNote.Items[2].Categories[0]);
Assert.Equal("[#1](https://github.com/laedit/vika/issues/1) - Support InspectCode", releaseNote.Items[2].Summary);
}
[Fact]
public void Parse_Example_A_WithOnlyLF()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(ExampleAWithOnlyLF);
// assert
Assert.Equal("Incremental release designed to provide an update to some of the core plugins.", releaseNote.Summary);
Assert.Equal(4, releaseNote.Items.Count);
Assert.Equal("Release Checker: Now gives you a breakdown of exactly what you are missing.", releaseNote.Items[0].Summary);
Assert.Equal("New", releaseNote.Items[0].Categories[0]);
Assert.Equal("Structured Layout: An alternative layout engine that allows developers to control layout.", releaseNote.Items[1].Summary);
Assert.Equal("New", releaseNote.Items[1].Categories[0]);
Assert.Equal("Timeline: Comes with an additional grid view to show the same data.", releaseNote.Items[2].Summary);
Assert.Equal("Changed", releaseNote.Items[2].Categories[0]);
Assert.Equal("Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement.", releaseNote.Items[3].Summary);
Assert.Equal("Fix", releaseNote.Items[3].Categories[0]);
}
[Fact]
public void Parse_Syntax_Metadata_Commits()
{
// act
var releaseNote = Parser.SemanticReleaseNotesParser.Parse(Syntax_Metadata_Commits);
// assert
Assert.Equal(2, releaseNote.Metadata.Count);
Assert.Equal("Commits", releaseNote.Metadata[0].Name);
Assert.Equal("56af25a...d3fead4", releaseNote.Metadata[0].Value);
Assert.Equal("Commits", releaseNote.Metadata[1].Name);
Assert.Equal("[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)", releaseNote.Metadata[1].Value);
}
private TextReader GetTextReader(string input)
{
return new StringReader(input);
}
private const string Syntax_Summaries = @"This is a _project_ summary with two paragraphs.
Lorem ipsum dolor sit amet consectetuer **adipiscing** elit.
Aliquam hendreritmi posuere lectus.
Vestibulum `enim wisi` viverra nec fringilla in laoreet
vitae risus. Donec sit amet nisl. Aliquam [semper](?) ipsum
sit amet velit.";
private const string Syntax_Items = @" - This is the _first_ *list* item.
- This is the **second** __list__ item.
- This is the `third` list item.
- This is the [forth](?) list item.";
private const string Syntax_Sections = @"# Section
This is the summary for Section.
- This is a Section scoped first list item.
- This is a Section scoped second list item.
# Other Section
This is the summary for Other Section.
- This is a Other Section scoped first list item.
- This is a Other Section scoped second list item.
";
private const string Syntax_Priority = @" 1. This is a High priority list item.
1. This is a High priority list item.
2. This is a Normal priority list item.
1. This is a High priority list item.
2. This is a Normal priority list item.
3. This is a Minor priority list item.
3. This is a Minor priority list item.
";
private const string Syntax_Category = @" - This is a +New list item.
- This is a +Fix list item.
- This is a +Change list item.
- +New features are everyone's favorites.
- This is a list item for a +Developer.
- This is a +super-special custom list item.
- This is a +o ne letter category.
- This is my last +DEVELOPER list item. +New
- This is something without category.
- And this +new with two same categories. +New
";
private const string ExampleA = @"Incremental release designed to provide an update to some of the core plugins.
- Release Checker: Now gives you a breakdown of exactly what you are missing. +New
- Structured Layout: An alternative layout engine that allows developers to control layout. +New
- Timeline: Comes with an additional grid view to show the same data. +Changed
- Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement. +Fix";
private const string ExampleAWithOnlyLF = "Incremental release designed to provide an update to some of the core plugins.\n\n - Release Checker: Now gives you a breakdown of exactly what you are missing. +New\n - Structured Layout: An alternative layout engine that allows developers to control layout. +New\n - Timeline: Comes with an additional grid view to show the same data. +Changed\n - Ajax: Fix that crashed poll in Chrome and IE due to log/trace statement. +Fix";
private const string ExampleB = @"Incremental release designed to provide an update to some of the core plugins.
# System
- *Release Checker*: Now gives you a breakdown of exactly what you are missing. +New
- *Structured Layout*: An alternative layout engine that allows developers to control layout. +New
# Plugin
- *Timeline*: Comes with an additional grid view to show the same data. +Changed
- *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement. +Fix";
private const string ExampleC = @"Incremental release designed to provide an update to some of the core plugins.
- *Example*: You can have global issues that aren't grouped to a section
# System
This description is specific to system section.
- *Release Checker*: Now gives you a +new breakdown of exactly what you are missing.
- *Structured Layout*: A +new alternative layout engine that allows developers to control layout.
# Plugin
This description is specific to plugin section.
- *Timeline*: Comes with an additional grid view to show the same data. +Changed
- *Ajax*: +Fix that crashed poll in Chrome and IE due to log/trace statement. [[i1234][http://getglimpse.com]]";
private const string ExampleD = @"Incremental release designed to provide an update to some of the core plugins.
1. *Example*: You can have global issues that aren't grouped to a section
# System [[icon][http://getglimpse.com/release/icon/core.png]]
This description is specific to system section.
3. *Release Checker*: Now gives you a breakdown of exactly what you are missing. +New
2. *Structured Layout*: An alternative layout engine that allows developers to control layout. +New
# Plugin [[icon][http://getglimpse.com/release/icon/mvc.png]]
This description is specific to plugin section.
1. *Timeline*: Comes with an additional grid view to show the same data. +Changed
1. *Ajax*: Fix that crashed poll in Chrome and IE due to log/trace statement. +Fix [[i1234][http://getglimpse.com]]";
private const string NVikaReleaseNotes = @" - [#9](https://github.com/laedit/vika/issues/9) - Handle multiple report files +enhancement
- [#2](https://github.com/laedit/vika/issues/2) - Support AppVeyor +enhancement
- [#1](https://github.com/laedit/vika/issues/1) - Support InspectCode +enhancement
Commits: [19556f025b...0203ea9a43](https://github.com/laedit/vika/compare/19556f025b...0203ea9a43)
";
private const string Syntax_Metadata_Commits = @"56af25a...d3fead4
Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)";
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
[ToolboxItem(false)]
public partial class DockPane : UserControl, IDockDragSource
{
public enum AppearanceStyle
{
ToolWindow,
Document
}
private enum HitTestArea
{
Caption,
TabStrip,
Content,
None
}
private struct HitTestResult
{
public HitTestArea HitArea;
public int Index;
public HitTestResult(HitTestArea hitTestArea, int index)
{
HitArea = hitTestArea;
Index = index;
}
}
private DockPaneCaptionBase m_captionControl;
private DockPaneCaptionBase CaptionControl
{
get { return m_captionControl; }
}
private DockPaneStripBase m_tabStripControl;
public DockPaneStripBase TabStripControl
{
get { return m_tabStripControl; }
}
internal protected DockPane(IDockContent content, DockState visibleState, bool show)
{
InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show)
{
if (floatWindow == null)
throw new ArgumentNullException("floatWindow");
InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show);
}
internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show)
{
if (previousPane == null)
throw (new ArgumentNullException("previousPane"));
InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show)
{
InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show);
}
private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show)
{
if (dockState == DockState.Hidden || dockState == DockState.Unknown)
throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState);
if (content == null)
throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent);
if (content.DockHandler.DockPanel == null)
throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel);
SuspendLayout();
SetStyle(ControlStyles.Selectable, false);
m_isFloat = (dockState == DockState.Float);
m_contents = new DockContentCollection();
m_displayingContents = new DockContentCollection(this);
m_dockPanel = content.DockHandler.DockPanel;
m_dockPanel.AddPane(this);
m_splitter = new SplitterControl(this);
m_nestedDockingStatus = new NestedDockingStatus(this);
m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this);
m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this);
Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl });
DockPanel.SuspendLayout(true);
if (flagBounds)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else if (prevPane != null)
DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion);
SetDockState(dockState);
if (show)
content.DockHandler.Pane = this;
else if (this.IsFloat)
content.DockHandler.FloatPane = this;
else
content.DockHandler.PanelPane = this;
ResumeLayout();
DockPanel.ResumeLayout(true, true);
}
private bool m_isDisposing;
protected override void Dispose(bool disposing)
{
if (disposing)
{
// IMPORTANT: avoid nested call into this method on Mono.
// https://github.com/dockpanelsuite/dockpanelsuite/issues/16
if (Win32Helper.IsRunningOnMono)
{
if (m_isDisposing)
return;
m_isDisposing = true;
}
m_dockState = DockState.Unknown;
if (NestedPanesContainer != null)
NestedPanesContainer.NestedPanes.Remove(this);
if (DockPanel != null)
{
DockPanel.RemovePane(this);
m_dockPanel = null;
}
Splitter.Dispose();
if (m_autoHidePane != null)
m_autoHidePane.Dispose();
}
base.Dispose(disposing);
}
private IDockContent m_activeContent = null;
public virtual IDockContent ActiveContent
{
get { return m_activeContent; }
set
{
if (ActiveContent == value)
return;
if (value != null)
{
if (!DisplayingContents.Contains(value))
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
else
{
if (DisplayingContents.Count != 0)
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
IDockContent oldValue = m_activeContent;
if (DockPanel.ActiveAutoHideContent == oldValue)
DockPanel.ActiveAutoHideContent = null;
m_activeContent = value;
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document)
{
if (m_activeContent != null)
m_activeContent.DockHandler.Form.BringToFront();
}
else
{
if (m_activeContent != null)
m_activeContent.DockHandler.SetVisible();
if (oldValue != null && DisplayingContents.Contains(oldValue))
oldValue.DockHandler.SetVisible();
if (IsActivated && m_activeContent != null)
m_activeContent.DockHandler.Activate();
}
if (FloatWindow != null)
FloatWindow.SetText();
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi &&
DockState == DockState.Document)
RefreshChanges(false); // delayed layout to reduce screen flicker
else
RefreshChanges();
if (m_activeContent != null)
TabStripControl.EnsureTabVisible(m_activeContent);
}
}
private bool m_allowDockDragAndDrop = true;
public virtual bool AllowDockDragAndDrop
{
get { return m_allowDockDragAndDrop; }
set { m_allowDockDragAndDrop = value; }
}
private IDisposable m_autoHidePane = null;
internal IDisposable AutoHidePane
{
get { return m_autoHidePane; }
set { m_autoHidePane = value; }
}
private object m_autoHideTabs = null;
internal object AutoHideTabs
{
get { return m_autoHideTabs; }
set { m_autoHideTabs = value; }
}
private object TabPageContextMenu
{
get
{
IDockContent content = ActiveContent;
if (content == null)
return null;
if (content.DockHandler.TabPageContextMenuStrip != null)
return content.DockHandler.TabPageContextMenuStrip;
else if (content.DockHandler.TabPageContextMenu != null)
return content.DockHandler.TabPageContextMenu;
else
return null;
}
}
internal bool HasTabPageContextMenu
{
get { return TabPageContextMenu != null; }
}
internal void ShowTabPageContextMenu(Control control, Point position)
{
object menu = TabPageContextMenu;
if (menu == null)
return;
ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip;
if (contextMenuStrip != null)
{
contextMenuStrip.Show(control, position);
return;
}
ContextMenu contextMenu = menu as ContextMenu;
if (contextMenu != null)
contextMenu.Show(this, position);
}
private Rectangle CaptionRectangle
{
get
{
if (!HasCaption)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x, y, width;
x = rectWindow.X;
y = rectWindow.Y;
width = rectWindow.Width;
int height = CaptionControl.MeasureHeight();
return new Rectangle(x, y, width, height);
}
}
internal Rectangle ContentRectangle
{
get
{
Rectangle rectWindow = DisplayingRectangle;
Rectangle rectCaption = CaptionRectangle;
Rectangle rectTabStrip = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height);
if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top)
y += rectTabStrip.Height;
int width = rectWindow.Width;
int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height;
return new Rectangle(x, y, width, height);
}
}
internal Rectangle TabStripRectangle
{
get
{
if (Appearance == AppearanceStyle.ToolWindow)
return TabStripRectangle_ToolWindow;
else
return TabStripRectangle_Document;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
if (DisplayingContents.Count <= 1 || IsAutoHide)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int x = rectWindow.X;
int y = rectWindow.Bottom - height;
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(x, y))
y = rectCaption.Y + rectCaption.Height;
return new Rectangle(x, y, width, height);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
if (DisplayingContents.Count == 0)
return Rectangle.Empty;
if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x = rectWindow.X;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int y = 0;
if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
y = rectWindow.Height - height;
else
y = rectWindow.Y;
return new Rectangle(x, y, width, height);
}
}
public virtual string CaptionText
{
get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; }
}
private DockContentCollection m_contents;
public DockContentCollection Contents
{
get { return m_contents; }
}
private DockContentCollection m_displayingContents;
public DockContentCollection DisplayingContents
{
get { return m_displayingContents; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool HasCaption
{
get
{
if (DockState == DockState.Document ||
DockState == DockState.Hidden ||
DockState == DockState.Unknown ||
(DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1))
return false;
else
return true;
}
}
private bool m_isActivated = false;
public bool IsActivated
{
get { return m_isActivated; }
}
internal void SetIsActivated(bool value)
{
if (m_isActivated == value)
return;
m_isActivated = value;
if (DockState != DockState.Document)
RefreshChanges(false);
OnIsActivatedChanged(EventArgs.Empty);
}
private bool m_isActiveDocumentPane = false;
public bool IsActiveDocumentPane
{
get { return m_isActiveDocumentPane; }
}
internal void SetIsActiveDocumentPane(bool value)
{
if (m_isActiveDocumentPane == value)
return;
m_isActiveDocumentPane = value;
if (DockState == DockState.Document)
RefreshChanges();
OnIsActiveDocumentPaneChanged(EventArgs.Empty);
}
public bool IsDockStateValid(DockState dockState)
{
foreach (IDockContent content in Contents)
if (!content.DockHandler.IsDockStateValid(dockState))
return false;
return true;
}
public bool IsAutoHide
{
get { return DockHelper.IsDockStateAutoHide(DockState); }
}
public AppearanceStyle Appearance
{
get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; }
}
internal Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
public void Activate()
{
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent)
DockPanel.ActiveAutoHideContent = ActiveContent;
else if (!IsActivated && ActiveContent != null)
ActiveContent.DockHandler.Activate();
}
internal void AddContent(IDockContent content)
{
if (Contents.Contains(content))
return;
Contents.Add(content);
}
internal void Close()
{
Dispose();
}
public void CloseActiveContent()
{
CloseContent(ActiveContent);
}
internal void CloseContent(IDockContent content)
{
if (content == null)
return;
if (!content.DockHandler.CloseButton)
return;
DockPanel dockPanel = DockPanel;
dockPanel.SuspendLayout(true);
try
{
if (content.DockHandler.HideOnClose)
{
content.DockHandler.Hide();
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
else
content.DockHandler.Close();
}
finally
{
dockPanel.ResumeLayout(true, true);
}
}
private HitTestResult GetHitTest(Point ptMouse)
{
Point ptMouseClient = PointToClient(ptMouse);
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Caption, -1);
Rectangle rectContent = ContentRectangle;
if (rectContent.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Content, -1);
Rectangle rectTabStrip = TabStripRectangle;
if (rectTabStrip.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse)));
return new HitTestResult(HitTestArea.None, -1);
}
private bool m_isHidden = true;
public bool IsHidden
{
get { return m_isHidden; }
}
private void SetIsHidden(bool value)
{
if (m_isHidden == value)
return;
m_isHidden = value;
if (DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
else if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
protected override void OnLayout(LayoutEventArgs levent)
{
SetIsHidden(DisplayingContents.Count == 0);
if (!IsHidden)
{
CaptionControl.Bounds = CaptionRectangle;
TabStripControl.Bounds = TabStripRectangle;
SetContentBounds();
foreach (IDockContent content in Contents)
{
if (DisplayingContents.Contains(content))
if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible)
content.DockHandler.FlagClipWindow = false;
}
}
base.OnLayout(levent);
}
internal void SetContentBounds()
{
Rectangle rectContent = ContentRectangle;
if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi)
rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent));
Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height);
foreach (IDockContent content in Contents)
if (content.DockHandler.Pane == this)
{
if (content == ActiveContent)
content.DockHandler.Form.Bounds = rectContent;
else
content.DockHandler.Form.Bounds = rectInactive;
}
}
internal void RefreshChanges()
{
RefreshChanges(true);
}
private void RefreshChanges(bool performLayout)
{
if (IsDisposed)
return;
CaptionControl.RefreshChanges();
TabStripControl.RefreshChanges();
if (DockState == DockState.Float && FloatWindow != null)
FloatWindow.RefreshChanges();
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null)
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
if (performLayout)
PerformLayout();
}
internal void RemoveContent(IDockContent content)
{
if (!Contents.Contains(content))
return;
Contents.Remove(content);
}
public void SetContentIndex(IDockContent content, int index)
{
int oldIndex = Contents.IndexOf(content);
if (oldIndex == -1)
throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent));
if (index < 0 || index > Contents.Count - 1)
if (index != -1)
throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Contents.Count - 1 && index == -1)
return;
Contents.Remove(content);
if (index == -1)
Contents.Add(content);
else if (oldIndex < index)
Contents.AddAt(content, index - 1);
else
Contents.AddAt(content, index);
RefreshChanges();
}
private void SetParent()
{
if (DockState == DockState.Unknown || DockState == DockState.Hidden)
{
SetParent(null);
Splitter.Parent = null;
}
else if (DockState == DockState.Float)
{
SetParent(FloatWindow);
Splitter.Parent = FloatWindow;
}
else if (DockHelper.IsDockStateAutoHide(DockState))
{
SetParent(DockPanel.AutoHideControl);
Splitter.Parent = null;
}
else
{
SetParent(DockPanel.DockWindows[DockState]);
Splitter.Parent = Parent;
}
}
private void SetParent(Control value)
{
if (Parent == value)
return;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Parent = value;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (contentFocused != null)
contentFocused.DockHandler.Activate();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
public new void Show()
{
Activate();
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (!dragSource.CanDockTo(this))
return;
Point ptMouse = Control.MousePosition;
HitTestResult hitTestResult = GetHitTest(ptMouse);
if (hitTestResult.HitArea == HitTestArea.Caption)
dockOutline.Show(this, -1);
else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1)
dockOutline.Show(this, hitTestResult.Index);
}
internal void ValidateActiveContent()
{
if (ActiveContent == null)
{
if (DisplayingContents.Count != 0)
ActiveContent = DisplayingContents[0];
return;
}
if (DisplayingContents.IndexOf(ActiveContent) >= 0)
return;
IDockContent prevVisible = null;
for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--)
if (Contents[i].DockHandler.DockState == DockState)
{
prevVisible = Contents[i];
break;
}
IDockContent nextVisible = null;
for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++)
if (Contents[i].DockHandler.DockState == DockState)
{
nextVisible = Contents[i];
break;
}
if (prevVisible != null)
ActiveContent = prevVisible;
else if (nextVisible != null)
ActiveContent = nextVisible;
else
ActiveContent = null;
}
private static readonly object DockStateChangedEvent = new object();
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActivatedChangedEvent = new object();
public event EventHandler IsActivatedChanged
{
add { Events.AddHandler(IsActivatedChangedEvent, value); }
remove { Events.RemoveHandler(IsActivatedChangedEvent, value); }
}
protected virtual void OnIsActivatedChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActiveDocumentPaneChangedEvent = new object();
public event EventHandler IsActiveDocumentPaneChanged
{
add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); }
remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); }
}
protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent];
if (handler != null)
handler(this, e);
}
public DockWindow DockWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; }
set
{
DockWindow oldValue = DockWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
public FloatWindow FloatWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; }
set
{
FloatWindow oldValue = FloatWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
private NestedDockingStatus m_nestedDockingStatus;
public NestedDockingStatus NestedDockingStatus
{
get { return m_nestedDockingStatus; }
}
private bool m_isFloat;
public bool IsFloat
{
get { return m_isFloat; }
}
public INestedPanesContainer NestedPanesContainer
{
get
{
if (NestedDockingStatus.NestedPanes == null)
return null;
else
return NestedDockingStatus.NestedPanes.Container;
}
}
private DockState m_dockState = DockState.Unknown;
public DockState DockState
{
get { return m_dockState; }
set
{
SetDockState(value);
}
}
public DockPane SetDockState(DockState value)
{
if (value == DockState.Unknown || value == DockState.Hidden)
throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState);
if ((value == DockState.Float) == this.IsFloat)
{
InternalSetDockState(value);
return this;
}
if (DisplayingContents.Count == 0)
return null;
IDockContent firstContent = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
{
firstContent = content;
break;
}
}
if (firstContent == null)
return null;
firstContent.DockHandler.DockState = value;
DockPane pane = firstContent.DockHandler.Pane;
DockPanel.SuspendLayout(true);
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
content.DockHandler.Pane = pane;
}
DockPanel.ResumeLayout(true, true);
return pane;
}
private void InternalSetDockState(DockState value)
{
if (m_dockState == value)
return;
DockState oldDockState = m_dockState;
INestedPanesContainer oldContainer = NestedPanesContainer;
m_dockState = value;
SuspendRefreshStateChange();
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
if (!IsFloat)
DockWindow = DockPanel.DockWindows[DockState];
else if (FloatWindow == null)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this);
if (contentFocused != null)
{
if (!Win32Helper.IsRunningOnMono)
{
DockPanel.ContentFocusManager.Activate(contentFocused);
}
}
ResumeRefreshStateChange(oldContainer, oldDockState);
}
private int m_countRefreshStateChange = 0;
private void SuspendRefreshStateChange()
{
m_countRefreshStateChange++;
DockPanel.SuspendLayout(true);
}
private void ResumeRefreshStateChange()
{
m_countRefreshStateChange--;
System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0);
DockPanel.ResumeLayout(true, true);
}
private bool IsRefreshStateChangeSuspended
{
get { return m_countRefreshStateChange != 0; }
}
private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
ResumeRefreshStateChange();
RefreshStateChange(oldContainer, oldDockState);
}
private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
if (IsRefreshStateChangeSuspended)
return;
SuspendRefreshStateChange();
DockPanel.SuspendLayout(true);
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
SetParent();
if (ActiveContent != null)
ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane);
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Pane == this)
content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane);
}
if (oldContainer != null)
{
Control oldContainerControl = (Control)oldContainer;
if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed)
oldContainerControl.PerformLayout();
}
if (DockHelper.IsDockStateAutoHide(oldDockState))
DockPanel.RefreshActiveAutoHideContent();
if (NestedPanesContainer.DockState == DockState)
((Control)NestedPanesContainer).PerformLayout();
if (DockHelper.IsDockStateAutoHide(DockState))
DockPanel.RefreshActiveAutoHideContent();
if (DockHelper.IsDockStateAutoHide(oldDockState) ||
DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
ResumeRefreshStateChange();
if (contentFocused != null)
contentFocused.DockHandler.Activate();
DockPanel.ResumeLayout(true, true);
if (oldDockState != DockState)
OnDockStateChanged(EventArgs.Empty);
}
private IDockContent GetFocusedContent()
{
IDockContent contentFocused = null;
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Form.ContainsFocus)
{
contentFocused = content;
break;
}
}
return contentFocused;
}
public DockPane DockTo(INestedPanesContainer container)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
DockAlignment alignment;
if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight)
alignment = DockAlignment.Bottom;
else
alignment = DockAlignment.Right;
return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5);
}
public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
if (container.IsFloat == this.IsFloat)
{
InternalAddToDockList(container, previousPane, alignment, proportion);
return this;
}
IDockContent firstContent = GetFirstContent(container.DockState);
if (firstContent == null)
return null;
DockPane pane;
DockPanel.DummyContent.DockPanel = DockPanel;
if (container.IsFloat)
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true);
else
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true);
pane.DockTo(container, previousPane, alignment, proportion);
SetVisibleContentsToPane(pane);
DockPanel.DummyContent.DockPanel = null;
return pane;
}
private void SetVisibleContentsToPane(DockPane pane)
{
SetVisibleContentsToPane(pane, ActiveContent);
}
private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(pane.DockState))
{
content.DockHandler.Pane = pane;
i--;
}
}
if (activeContent.DockHandler.Pane == pane)
pane.ActiveContent = activeContent;
}
private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion)
{
if ((container.DockState == DockState.Float) != IsFloat)
throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer);
int count = container.NestedPanes.Count;
if (container.NestedPanes.Contains(this))
count--;
if (prevPane == null && count > 0)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane);
if (prevPane != null && !container.NestedPanes.Contains(prevPane))
throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane);
if (prevPane == this)
throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane);
INestedPanesContainer oldContainer = NestedPanesContainer;
DockState oldDockState = DockState;
container.NestedPanes.Add(this);
NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion);
if (DockHelper.IsDockWindowState(DockState))
m_dockState = container.DockState;
RefreshStateChange(oldContainer, oldDockState);
}
public void SetNestedDockingProportion(double proportion)
{
NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion);
if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
public DockPane Float()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = ActiveContent;
DockPane floatPane = GetFloatPaneFromContents();
if (floatPane == null)
{
IDockContent firstContent = GetFirstContent(DockState.Float);
if (firstContent == null)
{
DockPanel.ResumeLayout(true, true);
return null;
}
floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true);
}
SetVisibleContentsToPane(floatPane, activeContent);
DockPanel.ResumeLayout(true, true);
return floatPane;
}
private DockPane GetFloatPaneFromContents()
{
DockPane floatPane = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (!content.DockHandler.IsDockStateValid(DockState.Float))
continue;
if (floatPane != null && content.DockHandler.FloatPane != floatPane)
return null;
else
floatPane = content.DockHandler.FloatPane;
}
return floatPane;
}
private IDockContent GetFirstContent(DockState dockState)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(dockState))
return content;
}
return null;
}
public void RestoreToPanel()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = DockPanel.ActiveContent;
for (int i = DisplayingContents.Count - 1; i >= 0; i--)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.CheckDockState(false) != DockState.Unknown)
content.DockHandler.IsFloat = false;
}
DockPanel.ResumeLayout(true, true);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE)
Activate();
base.WndProc(ref m);
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
Point location = PointToScreen(new Point(0, 0));
Size size;
DockPane floatPane = ActiveContent.DockHandler.FloatPane;
if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1)
size = DockPanel.DefaultFloatWindowSize;
else
size = floatPane.FloatWindow.Size;
if (ptMouse.X > location.X + size.Width)
location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize;
return new Rectangle(location, size);
}
void IDockDragSource.EndDrag()
{
}
public void FloatAt(Rectangle floatWindowBounds)
{
if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else
FloatWindow.Bounds = floatWindowBounds;
DockState = DockState.Float;
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
IDockContent activeContent = ActiveContent;
for (int i = Contents.Count - 1; i >= 0; i--)
{
IDockContent c = Contents[i];
if (c.DockHandler.DockState == DockState)
{
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
}
}
pane.ActiveContent = activeContent;
}
else
{
if (dockStyle == DockStyle.Left)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5);
else if (dockStyle == DockStyle.Right)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5);
else if (dockStyle == DockStyle.Top)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5);
else if (dockStyle == DockStyle.Bottom)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5);
DockState = pane.DockState;
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
if (dockStyle == DockStyle.Top)
DockState = DockState.DockTop;
else if (dockStyle == DockStyle.Bottom)
DockState = DockState.DockBottom;
else if (dockStyle == DockStyle.Left)
DockState = DockState.DockLeft;
else if (dockStyle == DockStyle.Right)
DockState = DockState.DockRight;
else if (dockStyle == DockStyle.Fill)
DockState = DockState.Document;
}
#endregion
}
}
| |
/********************************************************************
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.ComponentModel;
using Microsoft.MultiverseInterfaceStudio.FrameXml.Controls;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Drawing.Design;
namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization
{
/// Generated from Ui.xsd into two pieces and merged here.
/// Manually modified later - DO NOT REGENERATE
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "3.5.20706.1")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.multiverse.net/ui")]
[System.Xml.Serialization.XmlRootAttribute("Slider", Namespace = "http://www.multiverse.net/ui", IsNullable = false)]
public partial class SliderType : FrameType
{
public SliderType()
{
this.drawLayer = DRAWLAYER.OVERLAY;
this.orientation = ORIENTATION.VERTICAL;
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(DRAWLAYER.OVERLAY)]
[Category("Appearance")]
public DRAWLAYER drawLayer
{
get
{
return this.Properties.GetValue<DRAWLAYER>("drawLayer");
}
set
{
this.Properties["drawLayer"] = value;
}
}
/// <remarks/>
[XmlAttribute]
[Browsable(false)]
public float minValue
{
get
{
return this.MinValue.Value;
}
set
{
this.MinValue = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
[Browsable(false)]
public bool minValueSpecified
{
get
{
return this.MinValue.HasValue;
}
set
{
if (value)
this.MinValue = this.MinValue.Value;
else
this.MinValue = null;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[Browsable(false)]
public float maxValue
{
get
{
return this.MaxValue.Value;
}
set
{
this.MaxValue = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
[Browsable(false)]
public bool maxValueSpecified
{
get
{
return this.MaxValue.HasValue;
}
set
{
if (value)
this.MaxValue = this.MaxValue.Value;
else
this.MaxValue = null;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[Browsable(false)]
public float defaultValue
{
get
{
return this.DefaultValue.Value;
}
set
{
this.DefaultValue = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
[Browsable(false)]
public bool defaultValueSpecified
{
get
{
return this.DefaultValue.HasValue;
}
set
{
if (value)
this.DefaultValue = this.DefaultValue.Value;
else
this.DefaultValue = null;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[Browsable(false)]
public float valueStep
{
get
{
return this.ValueStep.Value;
}
set
{
this.ValueStep = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
[Browsable(false)]
public bool valueStepSpecified
{
get
{
return this.ValueStep.HasValue;
}
set
{
if (value)
this.ValueStep = this.ValueStep.Value;
else
this.ValueStep = null;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute(ORIENTATION.VERTICAL)]
[Category("Appearance")]
public ORIENTATION orientation
{
get
{
return this.Properties.GetValue<ORIENTATION>("orientation");
}
set
{
this.Properties["orientation"] = value;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
internal enum SingleCtlTypeEnum
{
InteractivityCtl, VisibilityCtl, BorderCtl, FontCtl, BackgroundCtl, BackgroundImage,
ReportParameterCtl, ReportCodeCtl, ReportModulesClassesCtl, ImageCtl, SubreportCtl,
FiltersCtl, SortingCtl, GroupingCtl
}
/// <summary>
/// Summary description for PropertyDialog.
/// </summary>
internal class SingleCtlDialog : System.Windows.Forms.Form
{
private DesignCtl _DesignCtl;
private DesignXmlDraw _Draw; // design draw
private List<XmlNode> _Nodes; // selected nodes
private SingleCtlTypeEnum _Type;
IProperty _Ctl;
private Button bOK;
private Button bCancel;
private Panel pMain;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal SingleCtlDialog(DesignCtl dc, DesignXmlDraw dxDraw, List<XmlNode> sNodes,
SingleCtlTypeEnum type, string[] names)
{
this._Type = type;
this._DesignCtl = dc;
this._Draw = dxDraw;
this._Nodes = sNodes;
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Add the control for the selected ReportItems
// We could have forced the user to create this (and maybe should have)
// instead of using an enum.
UserControl uc = null;
string title = null;
switch (type)
{
case SingleCtlTypeEnum.InteractivityCtl:
title = " - Interactivty";
uc = new InteractivityCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.VisibilityCtl:
title = " - Visibility";
uc = new VisibilityCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.BorderCtl:
title = " - Borders";
uc = new StyleBorderCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.FontCtl:
title = " - Font";
uc = new FontCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.BackgroundCtl:
title = " - Background";
uc = new BackgroundCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.ImageCtl:
title = " - Image";
uc = new ImageCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.SubreportCtl:
title = " - Subreport";
uc = new SubreportCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.FiltersCtl:
title = " - Filter";
uc = new FiltersCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.SortingCtl:
title = " - Sorting";
uc = new SortingCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.GroupingCtl:
title = " - Grouping";
uc = new GroupingCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.ReportParameterCtl:
title = " - Report Parameters";
uc = new ReportParameterCtl(dxDraw);
break;
case SingleCtlTypeEnum.ReportCodeCtl:
title = " - Code";
uc = new CodeCtl(dxDraw);
break;
case SingleCtlTypeEnum.ReportModulesClassesCtl:
title = " - Modules and Classes";
uc = new ModulesClassesCtl(dxDraw);
break;
}
_Ctl = uc as IProperty;
if (title != null)
this.Text = this.Text + title;
if (uc == null)
return;
int h = uc.Height;
int w = uc.Width;
uc.Top = 0;
uc.Left = 0;
uc.Dock = DockStyle.Fill;
uc.Parent = this.pMain;
this.Height = h + (this.Height - pMain.Height);
this.Width = w + (this.Width - pMain.Width);
this.ResumeLayout(true);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.pMain = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.Location = new System.Drawing.Point(452, 410);
this.bOK.Name = "bOK";
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 0;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(542, 410);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 1;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
this.bCancel.Click += new System.EventHandler(this.bCancel_Click);
//
// pMain
//
this.pMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pMain.Location = new System.Drawing.Point(3, 3);
this.pMain.Name = "pMain";
this.pMain.Size = new System.Drawing.Size(614, 401);
this.pMain.TabIndex = 2;
//
// SingleCtlDialog
//
this.AcceptButton = this.bOK;
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(620, 436);
this.Controls.Add(this.pMain);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SingleCtlDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Properties";
this.ResumeLayout(false);
}
#endregion
private void bOK_Click(object sender, System.EventArgs e)
{
string c = "";
switch (_Type)
{
case SingleCtlTypeEnum.InteractivityCtl:
c = "Interactivity change";
break;
case SingleCtlTypeEnum.VisibilityCtl:
c = "Visibility change";
break;
case SingleCtlTypeEnum.BorderCtl:
c = "Border change";
break;
case SingleCtlTypeEnum.FontCtl:
c = "Appearance change";
break;
case SingleCtlTypeEnum.BackgroundCtl:
case SingleCtlTypeEnum.BackgroundImage:
c = "Background change";
break;
case SingleCtlTypeEnum.FiltersCtl:
c = "Filters change";
break;
case SingleCtlTypeEnum.SortingCtl:
c = "Sort change";
break;
case SingleCtlTypeEnum.GroupingCtl:
c = "Grouping change";
break;
case SingleCtlTypeEnum.ReportCodeCtl:
c = "Report code change";
break;
case SingleCtlTypeEnum.ImageCtl:
c = "Image change";
break;
case SingleCtlTypeEnum.SubreportCtl:
c = "Subreport change";
break;
case SingleCtlTypeEnum.ReportModulesClassesCtl:
c = "Report Modules/Classes change";
break;
}
this._DesignCtl.StartUndoGroup(c);
this._Ctl.Apply();
this._DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
this.DialogResult = DialogResult.OK;
}
private void bCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using DocIdBitSet = Lucene.Net.Util.DocIdBitSet;
using Occur = Lucene.Net.Search.BooleanClause.Occur;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary> FilteredQuery JUnit tests.
///
/// <p/>Created: Apr 21, 2004 1:21:46 PM
///
///
/// </summary>
/// <version> $Id: TestFilteredQuery.java 807821 2009-08-25 21:55:49Z mikemccand $
/// </version>
/// <since> 1.4
/// </since>
[TestFixture]
public class TestFilteredQuery:LuceneTestCase
{
[Serializable]
private class AnonymousClassFilter:Filter
{
public override DocIdSet GetDocIdSet(IndexReader reader)
{
System.Collections.BitArray bitset = new System.Collections.BitArray((5 % 64 == 0?5 / 64:5 / 64 + 1) * 64);
bitset.Set(1, true);
bitset.Set(3, true);
return new DocIdBitSet(bitset);
}
}
[Serializable]
private class AnonymousClassFilter1:Filter
{
public override DocIdSet GetDocIdSet(IndexReader reader)
{
System.Collections.BitArray bitset = new System.Collections.BitArray((5 % 64 == 0?5 / 64:5 / 64 + 1) * 64);
for (int i = 0; i < 5; i++) bitset.Set(i, true);
return new DocIdBitSet(bitset);
}
}
private IndexSearcher searcher;
private RAMDirectory directory;
private Query query;
private Filter filter;
[SetUp]
public override void SetUp()
{
base.SetUp();
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.Add(new Field("field", "one two three four five", Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("sorter", "b", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new Field("field", "one two three four", Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("sorter", "d", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new Field("field", "one two three y", Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("sorter", "a", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new Field("field", "one two x", Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("sorter", "c", Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
writer.Optimize();
writer.Close();
searcher = new IndexSearcher(directory);
query = new TermQuery(new Term("field", "three"));
filter = NewStaticFilterB();
}
// must be static for serialization tests
private static Filter NewStaticFilterB()
{
return new AnonymousClassFilter();
}
[TearDown]
public override void TearDown()
{
searcher.Close();
directory.Close();
base.TearDown();
}
[Test]
public virtual void TestFilteredQuery_Renamed()
{
Query filteredquery = new FilteredQuery(query, filter);
ScoreDoc[] hits = searcher.Search(filteredquery, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.AreEqual(1, hits[0].doc);
QueryUtils.Check(filteredquery, searcher);
hits = searcher.Search(filteredquery, null, 1000, new Sort("sorter")).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.AreEqual(1, hits[0].doc);
filteredquery = new FilteredQuery(new TermQuery(new Term("field", "one")), filter);
hits = searcher.Search(filteredquery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
QueryUtils.Check(filteredquery, searcher);
filteredquery = new FilteredQuery(new TermQuery(new Term("field", "x")), filter);
hits = searcher.Search(filteredquery, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.AreEqual(3, hits[0].doc);
QueryUtils.Check(filteredquery, searcher);
filteredquery = new FilteredQuery(new TermQuery(new Term("field", "y")), filter);
hits = searcher.Search(filteredquery, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length);
QueryUtils.Check(filteredquery, searcher);
// test boost
Filter f = NewStaticFilterA();
float boost = 2.5f;
BooleanQuery bq1 = new BooleanQuery();
TermQuery tq = new TermQuery(new Term("field", "one"));
tq.SetBoost(boost);
bq1.Add(tq, Occur.MUST);
bq1.Add(new TermQuery(new Term("field", "five")), Occur.MUST);
BooleanQuery bq2 = new BooleanQuery();
tq = new TermQuery(new Term("field", "one"));
filteredquery = new FilteredQuery(tq, f);
filteredquery.SetBoost(boost);
bq2.Add(filteredquery, Occur.MUST);
bq2.Add(new TermQuery(new Term("field", "five")), Occur.MUST);
AssertScoreEquals(bq1, bq2);
Assert.AreEqual(boost, filteredquery.GetBoost(), 0);
Assert.AreEqual(1.0f, tq.GetBoost(), 0); // the boost value of the underlying query shouldn't have changed
}
// must be static for serialization tests
private static Filter NewStaticFilterA()
{
return new AnonymousClassFilter1();
}
/// <summary> Tests whether the scores of the two queries are the same.</summary>
public virtual void AssertScoreEquals(Query q1, Query q2)
{
ScoreDoc[] hits1 = searcher.Search(q1, null, 1000).ScoreDocs;
ScoreDoc[] hits2 = searcher.Search(q2, null, 1000).ScoreDocs;
Assert.AreEqual(hits1.Length, hits2.Length);
for (int i = 0; i < hits1.Length; i++)
{
Assert.AreEqual(hits1[i].score, hits2[i].score, 0.0000001f);
}
}
/// <summary> This tests FilteredQuery's rewrite correctness</summary>
[Test]
public virtual void TestRangeQuery()
{
TermRangeQuery rq = new TermRangeQuery("sorter", "b", "d", true, true);
Query filteredquery = new FilteredQuery(rq, filter);
ScoreDoc[] hits = searcher.Search(filteredquery, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length);
QueryUtils.Check(filteredquery, searcher);
}
[Test]
public virtual void TestBoolean()
{
BooleanQuery bq = new BooleanQuery();
Query query = new FilteredQuery(new MatchAllDocsQuery(), new SingleDocTestFilter(0));
bq.Add(query, BooleanClause.Occur.MUST);
query = new FilteredQuery(new MatchAllDocsQuery(), new SingleDocTestFilter(1));
bq.Add(query, BooleanClause.Occur.MUST);
ScoreDoc[] hits = searcher.Search(bq, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length);
QueryUtils.Check(query, searcher);
}
// Make sure BooleanQuery, which does out-of-order
// scoring, inside FilteredQuery, works
[Test]
public virtual void TestBoolean2()
{
BooleanQuery bq = new BooleanQuery();
Query query = new FilteredQuery(bq, new SingleDocTestFilter(0));
bq.Add(new TermQuery(new Term("field", "one")), BooleanClause.Occur.SHOULD);
bq.Add(new TermQuery(new Term("field", "two")), BooleanClause.Occur.SHOULD);
ScoreDoc[] hits = searcher.Search(query, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
QueryUtils.Check(query, searcher);
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Drawing;
namespace Reporting.Rdl
{
///<summary>
/// Bar chart definition and processing.
///</summary>
internal class ChartBar: ChartBase
{
int _GapSize = 6; // TODO: hard code for now
internal ChartBar(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat)
: base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat,_ToolTipXFormat)
{
}
override internal void Draw(Report rpt)
{
CreateSizedBitmap();
//AJM GJL 14082008 Using Vector Graphics
using (Graphics g1 = Graphics.FromImage(_bm))
{
_aStream = new System.IO.MemoryStream();
IntPtr HDC = g1.GetHdc();
_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel);
g1.ReleaseHdc(HDC);
}
using (Graphics g = Graphics.FromImage(_mf))
{
// 06122007AJM Used to Force Higher Quality
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// Adjust the top margin to depend on the title height
Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title);
Layout.TopMargin = titleSize.Height;
double max=0,min=0; // Get the max and min values
// 20022008 AJM GJL - Now requires Y axis identifier
GetValueMaxMin(rpt, ref max, ref min, 0,1);
DrawChartStyle(rpt, g);
// Draw title; routine determines if necessary
DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin));
// Adjust the left margin to depend on the Category Axis
Size caSize = CategoryAxisSize(rpt, g);
Layout.LeftMargin = caSize.Width;
// Adjust the bottom margin to depend on the Value Axis
Size vaSize = ValueAxisSize(rpt, g, min, max);
Layout.BottomMargin = vaSize.Height;
// Draw legend
System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true);
// 20022008 AJM GJL - Requires Rpt and Graphics
AdjustMargins(lRect,rpt,g ); // Adjust margins based on legend.
// Draw Plot area
DrawPlotAreaStyle(rpt, g, lRect);
// Draw Value Axis
if (vaSize.Width > 0) // If we made room for the axis - we need to draw it
DrawValueAxis(rpt, g, min, max,
new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin);
// Draw Category Axis
if (caSize.Height > 0)
DrawCategoryAxis(rpt, g,
new System.Drawing.Rectangle(Layout.LeftMargin - caSize.Width, Layout.TopMargin, caSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin));
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked)
DrawPlotAreaStacked(rpt, g, min, max);
else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
DrawPlotAreaPercentStacked(rpt, g);
else
DrawPlotAreaPlain(rpt, g, min, max);
DrawLegend(rpt, g, false, false); // after the plot is drawn
}
}
void DrawPlotAreaPercentStacked(Report rpt, Graphics g)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
double max = 1;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double sum=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
sum += GetDataValue(rpt, iRow, iCol);
}
double v=0;
int saveX=0;
double t=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) ((Math.Min(v/sum,max) / max) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g,
GetSeriesBrush(rpt, iRow, iCol),
rect, iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + t.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
void DrawPlotAreaPlain(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = SeriesCount * CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
//int barLoc=Layout.LeftMargin;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
double v = this.GetDataValue(rpt, iRow, iCol);
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol),
new System.Drawing.Rectangle(Layout.PlotArea.Left, barLoc, x, heightBar), iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)Layout.PlotArea.Left + "|Y:" + (int)(barLoc) + "|W:" + x + "|H:" + heightBar;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
barLoc += heightBar;
}
}
return;
}
void DrawPlotAreaStacked(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double v=0;
double t = 0;
int saveX=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), rect, iRow, iCol);
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
// Calculate the size of the category axis
Size CategoryAxisSize(Report rpt, Graphics g)
{
_LastCategoryWidth = 0;
Size size=Size.Empty;
if (this.ChartDefn.CategoryAxis == null)
return size;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return size;
Style s = a.Style;
// Measure the title
size = DrawTitleMeasure(rpt, g, a.Title);
if (!a.Visible) // don't need to calculate the height
return size;
// Calculate the tallest category name
TypeCode tc;
int maxWidth=0;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
Size tSize;
if (s == null)
tSize = Style.MeasureStringDefaults(rpt, g, v, tc, null, int.MaxValue);
else
tSize =s.MeasureString(rpt, g, v, tc, null, int.MaxValue);
if (tSize.Width > maxWidth)
maxWidth = tSize.Width;
if (iRow == CategoryCount)
_LastCategoryWidth = tSize.Width;
}
// Add on the widest category name
size.Width += maxWidth;
return size;
}
// DrawCategoryAxis
void DrawCategoryAxis(Report rpt, Graphics g, System.Drawing.Rectangle rect)
{
if (this.ChartDefn.CategoryAxis == null)
return;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return;
Style s = a.Style;
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height));
int drawHeight = rect.Height / CategoryCount;
TypeCode tc;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
int drawLoc=(int) (rect.Top + (iRow-1) * ((double) rect.Height / CategoryCount));
// Draw the category text
if (a.Visible)
{
System.Drawing.Rectangle drawRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, drawLoc, rect.Width-tSize.Width, drawHeight);
if (s == null)
Style.DrawStringDefaults(g, v, drawRect);
else
s.DrawString(rpt, g, v, tc, null, drawRect);
}
// Draw the Major Tick Marks (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, drawLoc));
}
// Draw the end on (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, rect.Bottom));
return;
}
protected void DrawCategoryAxisTick(Graphics g, bool bMajor, AxisTickMarksEnum tickType, Point p)
{
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
switch (tickType)
{
case AxisTickMarksEnum.Outside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X-len, p.Y));
break;
case AxisTickMarksEnum.Inside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.Cross:
g.DrawLine(Pens.Black, new Point(p.X-len, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.None:
default:
break;
}
return;
}
void DrawColumnBar(Report rpt, Graphics g, Brush brush, System.Drawing.Rectangle rect, int iRow, int iCol)
{
g.FillRectangle(brush, rect);
g.DrawRectangle(Pens.Black, rect);
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked ||
(ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
{
DrawDataPoint(rpt, g, rect, iRow, iCol);
}
else
{
Point p;
p = new Point(rect.Right, rect.Top);
DrawDataPoint(rpt, g, p, iRow, iCol);
}
return;
}
protected void DrawValueAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom)
{
if (this.ChartDefn.ValueAxis == null)
return;
Axis a = this.ChartDefn.ValueAxis.Axis;
if (a == null)
return;
Style s = a.Style;
// Account for tick marks
int tickSize=0;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
tickSize = this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
tickSize += this.AxisTickMarkMinorLen;
int intervalCount;
double incr;
SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count
int maxValueHeight = 0;
double v = min;
Size size= Size.Empty;
for (int i = 0; i < intervalCount+1; i++)
{
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * rect.Width);
if (!a.Visible)
{
// nothing to do
}
else if (s != null)
{
size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
s.DrawString(rpt, g, v, TypeCode.Double, null, vRect);
}
else
{
size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
Style.DrawStringDefaults(g, v, vRect);
}
if (size.Height > maxValueHeight) // Need to keep track of the maximum height
maxValueHeight = size.Height; // this is probably overkill since it should always be the same??
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom ));
v += incr;
}
// Draw the end points of the major grid lines
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom));
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom));
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top+maxValueHeight+tickSize, rect.Width, tSize.Height));
return;
}
protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e)
{
if (gl == null || !gl.ShowGridLines)
return;
if (gl.Style != null)
gl.Style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p)
{
if (tickType == AxisTickMarksEnum.None)
return;
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
Point s, e;
switch (tickType)
{
case AxisTickMarksEnum.Inside:
s = new Point(p.X, p.Y);
e = new Point(p.X, p.Y-len);
break;
case AxisTickMarksEnum.Cross:
s = new Point(p.X, p.Y-len);
e = new Point(p.X, p.Y+len);
break;
case AxisTickMarksEnum.Outside:
default:
s = new Point(p.X, p.Y+len);
e = new Point(p.X, p.Y);
break;
}
Style style = gl.Style;
if (style != null)
style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
// Calculate the size of the value axis; width is max value width + title width
// height is max value height
protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max)
{
Size size=Size.Empty;
if (ChartDefn.ValueAxis == null)
return size;
Axis a = ChartDefn.ValueAxis.Axis;
if (a == null)
return size;
Size minSize;
Size maxSize;
if (!a.Visible)
{
minSize = maxSize = Size.Empty;
}
else if (a.Style != null)
{
minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
else
{
minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
// Choose the largest
size.Width = Math.Max(minSize.Width, maxSize.Width);
size.Height = Math.Max(minSize.Height, maxSize.Height);
// Now we need to add in the height of the title (if any)
Size titleSize = DrawTitleMeasure(rpt, g, a.Title);
size.Height += titleSize.Height;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMinorLen;
return size;
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancersOperations operations.
/// </summary>
internal partial class LoadBalancersOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancersOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancersOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LoadBalancer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LoadBalancer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
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 = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using bv.common.Core;
using bv.common.Enums;
using bv.common.Resources;
using bv.winclient.BasePanel;
namespace bv.winclient.Core
{
public partial class ErrorForm : BvForm
{
private bool m_ShowDetail;
private static Exception m_CurrentException;
public ErrorForm()
{
InitializeComponent();
HelpTopicId = Help2.HomePage;
Splash.HideSplash();
if (!WinUtils.IsComponentInDesignMode(this))
{
cmdDetail.Click += cmdDetail_Click;
if (BaseFormManager.MainForm != null)
{
Icon = BaseFormManager.MainForm.Icon;
}
}
}
public enum FormType
{
Error,
Message,
Warning,
Confirmation
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ErrorText
{
get { return lbErrorText.Text; }
set
{
lbErrorText.Text = value;
SizeF size = lbErrorText.CreateGraphics().MeasureString(value, lbErrorText.Font, lbErrorText.Width);
float delta = size.Height - lbErrorText.Height+1;
if (delta > 1)
{
Height += (int) delta;
Panel3.Height += (int) delta;
}
}
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string FullErrorText
{
get { return txtFullErrorText.Text; }
set
{
txtFullErrorText.Text = value;
if (value != null)
{
DefineButtonsVisibility();
//cmdDetail_Click(null, EventArgs.Empty);
//cmdSend.Visible = value.IsCriticalError;
}
}
}
private FormType m_FormType;
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public FormType Type
{
get { return m_FormType; }
set
{
m_FormType = value;
Text = GetMessage(m_FormType.ToString());
DefineButtonsVisibility();
}
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static BaseStringsStorage Messages { get; set; }
static ErrorForm()
{
UnitTestMode = false;
}
public static bool UnitTestMode { get; set; }
private void DefineButtonsVisibility()
{
//if (m_FormType != FormType.Error)
//{
cmdDetail.Visible = txtFullErrorText.Text != "";
cmdDetail_Click(null, EventArgs.Empty);
cmdSend.Visible = false;
cmdOk.Visible = m_FormType != FormType.Confirmation;
btnNo.Visible = m_FormType == FormType.Confirmation;
btnYes.Visible = m_FormType == FormType.Confirmation;
//}
//else
//{
//cmdDetail.Visible = txtFullErrorText.Text != "";
//cmdDetail_Click(null, EventArgs.Empty);
//cmdSend.Visible = false;
//if (m_Error != null)
//{
// cmdSend.Visible = m_Error.IsCriticalError;
//}
//else
//{
// cmdSend.Visible = false;
//}
//}
}
#region "Shared methods"
private static Exception GetInnerException(Exception ex)
{
while (ex != null && ex.InnerException != null)
{
return GetInnerException(ex.InnerException);
}
return ex;
}
private static bool HandleException(Exception ex)
{
if (ex == null)
{
return false;
}
ex = GetInnerException(ex);
if (ex is SqlException)
{
string msgId = SqlExceptionMessage.Get(ex as SqlException);
if (msgId != null)
{
ShowError(msgId);
return true;
}
}
return false;
}
public static string GetMessage(string resourceKey, string resourceValue = null)
{
if (resourceKey == null)
{
return String.Empty;
}
string s = BvMessages.Get(resourceKey, resourceValue);
if (BvMessages.Instance.IsValueExists)
{
return s;
}
if (Messages != null)
{
s = Messages.GetString(resourceKey, resourceValue);
return s;
}
return String.Empty;
}
private static DialogResult ShowForm(ErrorForm f, Form owner)
{
if (owner == null)
{
owner = ActiveForm;
}
try
{
WaitDialog.Hide();
f.TopMost = true;
if (UnitTestMode)
{
f.Show(owner);
Thread.Sleep(2000);
return DialogResult.OK;
}
return f.ShowDialog(owner);
}
finally
{
WaitDialog.Restore();
}
}
private static ErrorForm Create(Form owner, string msg, FormType fType, string detailError = null)
{
if (owner == null)
{
owner = ActiveForm;
}
var f = new ErrorForm
{
ErrorText = msg,
Type = fType
};
//f.cmdDetail.Visible = !string.IsNullOrEmpty(detailError);
if (!string.IsNullOrEmpty(detailError))
{
f.FullErrorText = detailError;
}
//f.cmdDetail_Click(null, EventArgs.Empty);
f.StartPosition = owner != null ? FormStartPosition.CenterParent : FormStartPosition.CenterScreen;
RtlHelper.SetRTL(f);
return f;
}
public static void ShowMessageDirect(Form owner, string msg, FormType fType, string detailError = null)
{
if (BaseFormManager.IsReportsServiceRunning || BaseFormManager.IsAvrServiceRunning)
{
string error =
string.Format("Could not show message form from the service.{0}Error message:{0}'{1}'{0} Error details:{0}'{2}'",
Environment.NewLine, msg, detailError);
throw new ApplicationException(error);
}
using (ErrorForm f = Create(owner, msg, fType, detailError))
{
ShowForm(f, owner);
}
}
public static void ShowMessageDirect(string msg, FormType fType, string detailError = null)
{
ShowMessageDirect(null, msg, fType, detailError);
}
public static void ShowMessageDirect(string msg)
{
ShowMessageDirect(msg, FormType.Message);
}
public static void ShowMessage(string str, string defaultStr)
{
ShowMessageDirect(GetMessage(str, defaultStr));
}
public static void ShowWarning(string str, string defaultStr = null)
{
ShowWarningDirect(GetMessage(str, defaultStr));
}
public static void ShowWarningFormat(string str, string defaultStr, params object[] args)
{
ShowWarningFormatWithPrefix(str, defaultStr, "", args);
}
public static void ShowWarningFormatWithPrefix(string str, string defaultStr, string prefix, params object[] args)
{
ShowMessageDirect(prefix +
(args == null
? GetMessage(str, defaultStr)
: String.Format(GetMessage(str, defaultStr), args))
, FormType.Warning);
}
public static void ShowWarningDirect(string str)
{
ShowMessageDirect(str, FormType.Warning);
}
public static void ShowError(StandardError errType, Exception ex)
{
if (HandleException(ex))
{
return;
}
string error = StandardErrorHelper.Error(errType);
string detailError = ex.ToString();
ShowMessageDirect(error, FormType.Error, detailError);
}
public static void ShowError(Exception ex)
{
ShowError(StandardError.UnprocessedError, ex);
}
public static void ShowError(string errResourceName)
{
ShowMessageDirect(GetMessage(errResourceName), FormType.Error);
}
public static void ShowError(string errResourceName, string errMsg)
{
ShowMessageDirect(GetMessage(errResourceName, errMsg), FormType.Error);
}
public static void ShowError(string errResourceName, string errMsg, Exception ex)
{
if (m_CurrentException != null)
{
return;
}
if (HandleException(ex))
{
return;
}
m_CurrentException = ex;
string detailError = null;
if (ex != null)
{
detailError = ex.ToString();
}
ShowMessageDirect(GetMessage(errResourceName, errMsg), FormType.Error, detailError);
m_CurrentException = null;
}
public static void ShowError(string errResourceName, string errMsg, params object[] args)
{
ShowMessageDirect(
args == null
? GetMessage(errResourceName, errMsg)
: String.Format(GetMessage(errResourceName, errMsg), args)
, FormType.Error);
}
public static void ShowErrorDirect(string errMessage, Exception ex = null)
{
string detailError = null;
if (ex != null)
{
detailError = ex.ToString();
}
ShowMessageDirect(errMessage, FormType.Error, detailError);
}
public static void ShowErrorDirect(Form owner, string errMessage, Exception ex = null)
{
string detailError = null;
if (ex != null)
{
detailError = ex.ToString();
}
ShowMessageDirect(owner, errMessage, FormType.Error, detailError);
}
public static void ShowErrorDirect(string errMessage, params object[] args)
{
ShowMessageDirect(String.Format(errMessage, args), FormType.Error);
}
public static void ShowErrorDirect(Form owner, string errMessage, params object[] args)
{
ShowMessageDirect(owner, String.Format(errMessage, args), FormType.Error);
}
public static void ShowError(string errMsg, Exception ex)
{
if (HandleException(ex))
{
return;
}
ShowMessageDirect(errMsg, FormType.Error, ex.ToString());
}
public static DialogResult ShowConfirmationDialog(Form owner, string msg, string detailError)
{
using (ErrorForm f = Create(owner, msg, FormType.Confirmation, detailError))
{
return ShowForm(f, owner);
}
}
private delegate void ExceptionDelegate(Exception ex);
public static void ShowErrorThreadSafe(Exception ex)
{
ExceptionDelegate o = ShowError;
if (BaseFormManager.MainForm == null)
{
throw (ex);
}
BaseFormManager.MainForm.BeginInvoke(o, ex);
}
#endregion
#region "Private methods"
private void cmdDetail_Click(object sender, EventArgs e)
{
SuspendLayout();
if (string.IsNullOrEmpty(txtFullErrorText.Text))
{
m_ShowDetail = false;
cmdDetail.Visible = false;
pnDetails.Visible = false;
if (Height - pnDetails.Height > 100)
{
Height -= pnDetails.Height;
}
ResumeLayout();
return;
}
if (m_ShowDetail)
{
cmdDetail.Text = GetMessage("btnShowErrDetail", "Show Details");
Height -= pnDetails.Height;
}
else
{
cmdDetail.Text = GetMessage("btnHideErrDetail", "Hide Details");
Height += pnDetails.Height;
}
m_ShowDetail = !m_ShowDetail;
pnDetails.Visible = m_ShowDetail;
ResumeLayout();
}
#endregion
protected override void OnResize(EventArgs e)
{
PerformLayout();
}
}
}
| |
using System;
// Author:
// Anton Kasyanov <[email protected]>
//
// Copyright (C) 2014 Anton Kasyanov <[email protected]>
//
//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.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
namespace FluentSQLite
{
public enum FieldType
{
AutoInc,
Integer,
Float,
Decimal,
DateTime,
String,
Blob
}
/// <summary>
/// Field context
/// </summary>
public interface IFieldContext
{
/// <summary>
/// Fuield Name
/// </summary>
string FieldName { get; }
/// <summary>
/// Filed type
/// </summary>
FieldType FieldType { get; }
/// <summary>
/// Flag indicating whether the current field belongs to the table Primary Key
/// </summary>
bool IsInPrimaryKey { get; }
/// <summary>
/// Flag indicating whether the field should be always assigned (ie that it cannot be left NULL in the database)
/// </summary>
bool IsRequired { get; }
}
/// <summary>
/// Data table context
/// </summary>
public interface ITableContext
{
/// <summary>
/// Database table name
/// </summary>
string TableName { get; }
/// <summary>
/// Collection of table fields
/// </summary>
IEnumerable<IFieldContext> Fields { get; }
/// <summary>
/// Adds a field to the table structure
/// </summary>
/// <param name="fieldName">Field name</param>
/// <param name="fieldType">Field type</param>
/// <param name="required">Flag indicating whether the field should be always assigned (ie that it cannot be left NULL in the database)</param>
/// <param name="primaryKey">Flag indicating whether the current field belongs to the table Primary Key</param>
/// <returns>Table context used by the FluentSQLite interface</returns>
ITableContext AddField(string fieldName, FieldType fieldType, bool required = false, bool primaryKey = false);
/// <summary>
/// Commit structure changes
/// </summary>
/// <returns>Database context used by the FluentSQLite interface</returns>
IDatabaseContext CommitStructure();
/// <summary>
/// Adds a data row to the database
/// </summary>
/// <param name="data">Field values</param>
/// <returns>Table context used by the fluent interface</returns>
ITableContext InsertRow(params object[] data);
/// <summary>
/// Commits queued data rows added via the InsertRow method
/// </summary>
/// <returns>Database context used by the FluentSQLite interface</returns>
IDatabaseContext CommitData();
}
/// <summary>
/// SQLite database context
/// </summary>
public interface IDatabaseContext
{
/// <summary>
/// Database connection
/// </summary>
IDbConnection Connection { get; }
/// <summary>
/// Collection of data tables defined via the FluentSQLite interface earlier
/// </summary>
IEnumerable<ITableContext> DataTables { get; }
/// <summary>
/// Adds a data table to the database
/// </summary>
/// <param name="tableName">Data table name</param>
/// <returns>Table context used by the FluentSQLite interface</returns>
ITableContext AddTable(string tableName);
/// <summary>
/// Selects one of the data tables. Can be used to add data to
/// data tables that already exist in the database, but weren't
/// described via the FluentSQLite interface
/// </summary>
/// <returns>Table context used by the FluentSQLite interface</returns>
ITableContext SelectTable(string tableName);
/// <summary>
/// Closes the database connection.
/// For In-Memory databases this operation drops the database.
/// </summary>
void DetachDatabase();
}
/// <summary>
/// Entry point
/// </summary>
public static class Database
{
private const string DefaultConnectionString = @"Data Source=:memory:;Version=3;New=True;Synchronous=Off;";
/// <summary>
/// Creates a new or creates to an existing SQLite database
/// using the provided database connection string
/// </summary>
/// <param name="connectionString">Database connection string</param>
/// <returns>Database context</returns>
public static IDatabaseContext CreateDatabase(string connectionString = Database.DefaultConnectionString)
{
return Database.CreateDatabase(new SQLiteConnection(connectionString));
}
/// <summary>
/// Creates a new or creates to an existing SQLite database
/// using the provided database connection instance
/// </summary>
/// <param name="connection"></param>
/// <returns>Database context</returns>
public static IDatabaseContext CreateDatabase(IDbConnection connection)
{
return new DatabaseContext(connection);
}
}
/// <summary>
/// Internal alias for a data row context
/// </summary>
sealed class DataRowContext : List<object>
{
public DataRowContext(IEnumerable<object> data)
: base(data)
{
}
}
sealed class FieldContext : IFieldContext
{
public FieldContext(string fieldName, FieldType fieldType, bool required, bool primaryKey)
{
this.FieldName = fieldName;
this.FieldType = fieldType;
this.IsRequired = required;
this.IsInPrimaryKey = primaryKey;
}
public string FieldName { get; private set; }
public FieldType FieldType { get; private set; }
public bool IsInPrimaryKey { get; private set; }
public bool IsRequired { get; private set; }
}
sealed class TableContext : ITableContext
{
#region Private field(s)
private readonly IDatabaseContext _ownerContext;
private readonly IList<IFieldContext> _fields;
private readonly IList<DataRowContext> _rows;
private bool _isAutoIncPresent;
#endregion
public TableContext(string tableName, IDatabaseContext ownerContext)
{
this._ownerContext = ownerContext;
this.TableName = tableName;
this._fields = new List<IFieldContext>(16);
this._rows = new List<DataRowContext>(16);
this._isAutoIncPresent = false;
}
public string TableName { get; private set; }
public IEnumerable<IFieldContext> Fields
{
get
{
return new List<IFieldContext>(this._fields);
}
}
public ITableContext AddField(string fieldName, FieldType fieldType, bool required = false, bool primaryKey = false)
{
// Additional checks to ensure that requested option set is consentient
if (primaryKey)
required = true;
this.CheckPrimaryKeyRestrictions(fieldType, primaryKey);
this._fields.Add(new FieldContext(fieldName, fieldType, required, primaryKey));
return this;
}
private void CheckPrimaryKeyRestrictions(FieldType fieldType, bool primaryKey)
{
if (this._isAutoIncPresent && primaryKey)
throw new FluentSQLiteException("AutoInc field should be the only Primary Key field");
// Nothing more to check
if (fieldType != FluentSQLite.FieldType.AutoInc)
return;
// Non-PK cannot be AutoInc
if (!primaryKey)
throw new FluentSQLiteException("AutoInc field should be Primary Key field");
this._isAutoIncPresent = true;
if (this._fields.Any(field => field.IsInPrimaryKey))
throw new FluentSQLiteException("AutoInc field should be the only Primary Key field");
}
public IDatabaseContext CommitStructure()
{
var commandText = this.GenerateCreateTableSqlExpression();
this.ExecuteCreateTableCommand(commandText);
return this._ownerContext;
}
private string GenerateCreateTableSqlExpression()
{
StringBuilder commandTextBuilder = new StringBuilder(256);
commandTextBuilder.AppendFormat(@"CREATE TABLE ""{0}"" (", this.TableName);
// First pass - table structure
bool fieldAdded = false;
foreach (var field in this._fields)
{
if (fieldAdded)
commandTextBuilder.Append(@", ");
else
fieldAdded = true;
commandTextBuilder.AppendFormat(@"""{0}"" {1}", field.FieldName, TableContext.ConvertEnumToSqlType(field.FieldType));
if (field.IsRequired && field.FieldType != FieldType.AutoInc)
commandTextBuilder.Append(@" NOT NULL");
}
// Second pass - Primary key
bool primaryKeyDefined = false;
foreach (var field in this._fields)
{
if (!field.IsInPrimaryKey)
continue;
if (field.FieldType == FieldType.AutoInc)
continue;
if (!primaryKeyDefined)
{
commandTextBuilder.Append(@", PRIMARY KEY(");
primaryKeyDefined = true;
}
else
{
commandTextBuilder.Append(@", ");
}
commandTextBuilder.Append(field.FieldName);
}
if (primaryKeyDefined)
commandTextBuilder.Append(@")"); // Close the PK definition clause
commandTextBuilder.Append(@")"); // Close the structure definition clause
return commandTextBuilder.ToString();
}
private void ExecuteCreateTableCommand(string commandText)
{
using (var command = this._ownerContext.Connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
public ITableContext InsertRow(params object[] data)
{
this._rows.Add(new DataRowContext(data));
return this;
}
public IDatabaseContext CommitData()
{
if (this._rows.Count == 0)
return this._ownerContext;
List<string> parameterNames = new List<String>(this._fields.Count);
var commandText = this.GenerateDataInsertSqlExpression(parameterNames);
this.ExecuteInsertDataCommand(commandText, parameterNames);
this._rows.Clear();
return this._ownerContext;
}
private string GenerateDataInsertSqlExpression(List<string> parameterNames)
{
var commandTextBuilder = new StringBuilder(256);
var valuesListBuilder = new StringBuilder(256);
// Seed values
commandTextBuilder.AppendFormat(@"INSERT INTO ""{0}"" (", this.TableName);
valuesListBuilder.Append(@" VALUES (");
bool fieldAdded = false;
foreach (var field in this._fields)
{
if (field.FieldType == FieldType.AutoInc)
continue;
string parameterName = "@" + field.FieldName.Replace(' ', '_');
if (fieldAdded)
{
commandTextBuilder.Append(@", ");
valuesListBuilder.Append(@", ");
}
else
{
fieldAdded = true;
}
commandTextBuilder.AppendFormat(@"""{0}""", field.FieldName);
valuesListBuilder.Append(parameterName);
parameterNames.Add(parameterName);
}
commandTextBuilder.Append(@")");
valuesListBuilder.Append(@")");
commandTextBuilder.Append(valuesListBuilder);
return commandTextBuilder.ToString();
}
private void ExecuteInsertDataCommand(string commandText, List<string> parameterNames)
{
using (var command = this._ownerContext.Connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
var parameters = new IDbDataParameter[parameterNames.Count];
for (int i = 0; i < parameterNames.Count; i++)
{
var parameter = command.CreateParameter();
parameter.ParameterName = parameterNames[i];
parameters[i] = parameter;
command.Parameters.Add(parameter);
}
foreach (var row in this._rows)
{
for (int j = 0; j < row.Count; j++)
{
parameters[j].Value = row[j];
}
command.ExecuteNonQuery();
}
}
}
private static string ConvertEnumToSqlType(FieldType value)
{
switch (value)
{
case FieldType.AutoInc:
return "INTEGER PRIMARY KEY AUTOINCREMENT";
case FieldType.Integer:
return "INTEGER";
case FieldType.Float:
return "REAL";
case FieldType.Decimal:
return "NUMERIC";
case FieldType.DateTime:
return "DATETIME";
case FieldType.String:
return "CHAR";
case FieldType.Blob:
return "BLOB";
default:
return "CHAR";
}
}
}
/// <summary>
/// Database context implementation
/// </summary>
sealed class DatabaseContext : IDatabaseContext
{
#region Private field(s)
private readonly IDictionary<string, ITableContext> _tableContexts;
#endregion
public DatabaseContext(IDbConnection connection)
{
this._tableContexts = new Dictionary<string, ITableContext>(StringComparer.OrdinalIgnoreCase);
this.Connection = connection;
if (connection.State != ConnectionState.Open)
connection.Open();
}
public IDbConnection Connection { get; private set; }
public IEnumerable<ITableContext> DataTables
{
get
{
return this._tableContexts.Values;
}
}
public ITableContext AddTable(string tableName)
{
if (this._tableContexts.ContainsKey(tableName))
throw new FluentSQLiteException("Table already present in the database: " + tableName);
ITableContext context = new TableContext(tableName, this);
this._tableContexts[tableName] = context;
return context;
}
public ITableContext SelectTable(string tableName)
{
ITableContext context;
if (this._tableContexts.TryGetValue(tableName, out context))
return context;
return this.AddTable(tableName);
}
public void DetachDatabase()
{
this.Connection.Close();
this.Connection.Dispose();
this.Connection = null;
}
}
[Serializable]
public class FluentSQLiteException : Exception
{
public FluentSQLiteException(string message)
: base(message)
{
}
}
}
| |
using Csla;
using System.ComponentModel.DataAnnotations;
using System;
using Csla.Serialization;
using System.ComponentModel;
namespace ProjectTracker.Library
{
[Serializable]
public class ProjectResourceEdit : BusinessBase<ProjectResourceEdit>
{
public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public byte[] TimeStamp
{
get { return GetProperty(TimeStampProperty); }
set { SetProperty(TimeStampProperty, value); }
}
public static readonly PropertyInfo<int> ResourceIdProperty =
RegisterProperty<int>(c => c.ResourceId);
[Display(Name = "Resource id")]
public int ResourceId
{
get { return GetProperty(ResourceIdProperty); }
private set { LoadProperty(ResourceIdProperty, value); }
}
public static readonly PropertyInfo<string> FirstNameProperty =
RegisterProperty<string>(c => c.FirstName);
[Display(Name = "First name")]
public string FirstName
{
get { return GetProperty(FirstNameProperty); }
private set { LoadProperty(FirstNameProperty, value); }
}
public static readonly PropertyInfo<string> LastNameProperty =
RegisterProperty<string>(c => c.LastName);
[Display(Name = "Last name")]
public string LastName
{
get { return GetProperty(LastNameProperty); }
private set { LoadProperty(LastNameProperty, value); }
}
[Display(Name = "Full name")]
public string FullName
{
get { return string.Format("{0}, {1}", LastName, FirstName); }
}
public static readonly PropertyInfo<DateTime> AssignedProperty =
RegisterProperty<DateTime>(c => c.Assigned);
[Display(Name = "Date assigned")]
public DateTime Assigned
{
get { return GetProperty(AssignedProperty); }
private set { LoadProperty(AssignedProperty, value); }
}
public static readonly PropertyInfo<int> RoleProperty =
RegisterProperty<int>(c => c.Role);
[Display(Name = "Role assigned")]
public int Role
{
get { return GetProperty(RoleProperty); }
set
{
SetProperty(RoleProperty, value);
OnPropertyChanged("RoleName");
}
}
[Display(Name = "Role")]
public string RoleName
{
get
{
var result = "none";
if (RoleList.GetList().ContainsKey(Role))
result = RoleList.GetList().GetItemByKey(Role).Value;
return result;
}
}
public override string ToString()
{
return ResourceId.ToString();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new ValidRole(RoleProperty));
BusinessRules.AddRule(
new Csla.Rules.CommonRules.IsInRole(
Csla.Rules.AuthorizationActions.WriteProperty, RoleProperty, "ProjectManager"));
}
#if !SILVERLIGHT && !NETFX_CORE
private void Child_Create(int resourceId)
{
using (BypassPropertyChecks)
{
ResourceId = resourceId;
Role = RoleList.DefaultRole();
LoadProperty(AssignedProperty, DateTime.Today);
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
var person = dal.Fetch(resourceId);
FirstName = person.FirstName;
LastName = person.LastName;
}
}
base.Child_Create();
}
private void Child_Fetch(int projectId, int resourceId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
var data = dal.Fetch(projectId, resourceId);
Child_Fetch(data);
}
}
private void Child_Fetch(ProjectTracker.Dal.AssignmentDto data)
{
using (BypassPropertyChecks)
{
ResourceId = data.ResourceId;
Role = data.RoleId;
LoadProperty(AssignedProperty, data.Assigned);
TimeStamp = data.LastChanged;
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
var person = dal.Fetch(data.ResourceId);
FirstName = person.FirstName;
LastName = person.LastName;
}
}
}
private void Child_Insert(ProjectEdit project)
{
Child_Insert(project.Id);
}
private void Child_Insert(int projectId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.AssignmentDto
{
ProjectId = projectId,
ResourceId = this.ResourceId,
Assigned = ReadProperty(AssignedProperty),
RoleId = this.Role
};
dal.Insert(item);
TimeStamp = item.LastChanged;
}
}
}
private void Child_Update(ProjectEdit project)
{
Child_Update(project.Id);
}
private void Child_Update(int projectId)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
var item = dal.Fetch(projectId, ResourceId);
item.Assigned = ReadProperty(AssignedProperty);
item.RoleId = Role;
item.LastChanged = TimeStamp;
dal.Update(item);
TimeStamp = item.LastChanged;
}
}
}
private void Child_DeleteSelf(ProjectEdit project)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>();
using (BypassPropertyChecks)
{
dal.Delete(project.Id, ResourceId);
}
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Net.Http.Headers
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "This is not a collection")]
public sealed class HttpResponseHeaders : HttpHeaders
{
private static readonly Dictionary<string, HttpHeaderParser> s_parserStore = CreateParserStore();
private static readonly HashSet<string> s_invalidHeaders = CreateInvalidHeaders();
private HttpGeneralHeaders _generalHeaders;
private HttpHeaderValueCollection<string> _acceptRanges;
private HttpHeaderValueCollection<AuthenticationHeaderValue> _wwwAuthenticate;
private HttpHeaderValueCollection<AuthenticationHeaderValue> _proxyAuthenticate;
private HttpHeaderValueCollection<ProductInfoHeaderValue> _server;
private HttpHeaderValueCollection<string> _vary;
#region Response Headers
public HttpHeaderValueCollection<string> AcceptRanges
{
get
{
if (_acceptRanges == null)
{
_acceptRanges = new HttpHeaderValueCollection<string>(KnownHeaderNames.AcceptRanges,
this, HeaderUtilities.TokenValidator);
}
return _acceptRanges;
}
}
public TimeSpan? Age
{
get { return HeaderUtilities.GetTimeSpanValue(KnownHeaderNames.Age, this); }
set { SetOrRemoveParsedValue(KnownHeaderNames.Age, value); }
}
public EntityTagHeaderValue ETag
{
get { return (EntityTagHeaderValue)GetParsedValues(KnownHeaderNames.ETag); }
set { SetOrRemoveParsedValue(KnownHeaderNames.ETag, value); }
}
public Uri Location
{
get { return (Uri)GetParsedValues(KnownHeaderNames.Location); }
set { SetOrRemoveParsedValue(KnownHeaderNames.Location, value); }
}
public HttpHeaderValueCollection<AuthenticationHeaderValue> ProxyAuthenticate
{
get
{
if (_proxyAuthenticate == null)
{
_proxyAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>(
KnownHeaderNames.ProxyAuthenticate, this);
}
return _proxyAuthenticate;
}
}
public RetryConditionHeaderValue RetryAfter
{
get { return (RetryConditionHeaderValue)GetParsedValues(KnownHeaderNames.RetryAfter); }
set { SetOrRemoveParsedValue(KnownHeaderNames.RetryAfter, value); }
}
public HttpHeaderValueCollection<ProductInfoHeaderValue> Server
{
get
{
if (_server == null)
{
_server = new HttpHeaderValueCollection<ProductInfoHeaderValue>(KnownHeaderNames.Server, this);
}
return _server;
}
}
public HttpHeaderValueCollection<string> Vary
{
get
{
if (_vary == null)
{
_vary = new HttpHeaderValueCollection<string>(KnownHeaderNames.Vary,
this, HeaderUtilities.TokenValidator);
}
return _vary;
}
}
public HttpHeaderValueCollection<AuthenticationHeaderValue> WwwAuthenticate
{
get
{
if (_wwwAuthenticate == null)
{
_wwwAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>(
KnownHeaderNames.WWWAuthenticate, this);
}
return _wwwAuthenticate;
}
}
#endregion
#region General Headers
public CacheControlHeaderValue CacheControl
{
get { return _generalHeaders.CacheControl; }
set { _generalHeaders.CacheControl = value; }
}
public HttpHeaderValueCollection<string> Connection
{
get { return _generalHeaders.Connection; }
}
public bool? ConnectionClose
{
get { return _generalHeaders.ConnectionClose; }
set { _generalHeaders.ConnectionClose = value; }
}
public DateTimeOffset? Date
{
get { return _generalHeaders.Date; }
set { _generalHeaders.Date = value; }
}
public HttpHeaderValueCollection<NameValueHeaderValue> Pragma
{
get { return _generalHeaders.Pragma; }
}
public HttpHeaderValueCollection<string> Trailer
{
get { return _generalHeaders.Trailer; }
}
public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding
{
get { return _generalHeaders.TransferEncoding; }
}
public bool? TransferEncodingChunked
{
get { return _generalHeaders.TransferEncodingChunked; }
set { _generalHeaders.TransferEncodingChunked = value; }
}
public HttpHeaderValueCollection<ProductHeaderValue> Upgrade
{
get { return _generalHeaders.Upgrade; }
}
public HttpHeaderValueCollection<ViaHeaderValue> Via
{
get { return _generalHeaders.Via; }
}
public HttpHeaderValueCollection<WarningHeaderValue> Warning
{
get { return _generalHeaders.Warning; }
}
#endregion
internal HttpResponseHeaders()
{
_generalHeaders = new HttpGeneralHeaders(this);
base.SetConfiguration(s_parserStore, s_invalidHeaders);
}
private static Dictionary<string, HttpHeaderParser> CreateParserStore()
{
var parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase);
parserStore.Add(KnownHeaderNames.AcceptRanges, GenericHeaderParser.TokenListParser);
parserStore.Add(KnownHeaderNames.Age, TimeSpanHeaderParser.Parser);
parserStore.Add(KnownHeaderNames.ETag, GenericHeaderParser.SingleValueEntityTagParser);
parserStore.Add(KnownHeaderNames.Location, UriHeaderParser.RelativeOrAbsoluteUriParser);
parserStore.Add(KnownHeaderNames.ProxyAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser);
parserStore.Add(KnownHeaderNames.RetryAfter, GenericHeaderParser.RetryConditionParser);
parserStore.Add(KnownHeaderNames.Server, ProductInfoHeaderParser.MultipleValueParser);
parserStore.Add(KnownHeaderNames.Vary, GenericHeaderParser.TokenListParser);
parserStore.Add(KnownHeaderNames.WWWAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser);
HttpGeneralHeaders.AddParsers(parserStore);
return parserStore;
}
private static HashSet<string> CreateInvalidHeaders()
{
var invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
HttpContentHeaders.AddKnownHeaders(invalidHeaders);
return invalidHeaders;
// Note: Reserved request header names are allowed as custom response header names. Reserved request
// headers have no defined meaning or format when used on a response. This enables a client to accept
// any headers sent from the server as either content headers or response headers.
}
internal static void AddKnownHeaders(HashSet<string> headerSet)
{
Debug.Assert(headerSet != null);
headerSet.Add(KnownHeaderNames.AcceptRanges);
headerSet.Add(KnownHeaderNames.Age);
headerSet.Add(KnownHeaderNames.ETag);
headerSet.Add(KnownHeaderNames.Location);
headerSet.Add(KnownHeaderNames.ProxyAuthenticate);
headerSet.Add(KnownHeaderNames.RetryAfter);
headerSet.Add(KnownHeaderNames.Server);
headerSet.Add(KnownHeaderNames.Vary);
headerSet.Add(KnownHeaderNames.WWWAuthenticate);
}
internal override void AddHeaders(HttpHeaders sourceHeaders)
{
base.AddHeaders(sourceHeaders);
HttpResponseHeaders sourceResponseHeaders = sourceHeaders as HttpResponseHeaders;
Debug.Assert(sourceResponseHeaders != null);
// Copy special values, but do not overwrite
_generalHeaders.AddSpecialsFrom(sourceResponseHeaders._generalHeaders);
}
}
}
| |
using System;
using System.Text;
namespace YAF.Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = YAF.Lucene.Net.Util.AttributeSource;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using Term = YAF.Lucene.Net.Index.Term;
using Terms = YAF.Lucene.Net.Index.Terms;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
using ToStringUtils = YAF.Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A <see cref="Query"/> that matches documents within an range of terms.
///
/// <para/>This query matches the documents looking for terms that fall into the
/// supplied range according to
/// <see cref="byte.CompareTo(byte)"/>. It is not intended
/// for numerical ranges; use <see cref="NumericRangeQuery"/> instead.
///
/// <para/>This query uses the
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>
/// rewrite method.
/// <para/>
/// @since 2.9
/// </summary>
public class TermRangeQuery : MultiTermQuery
{
private BytesRef lowerTerm;
private BytesRef upperTerm;
private bool includeLower;
private bool includeUpper;
/// <summary>
/// Constructs a query selecting all terms greater/equal than <paramref name="lowerTerm"/>
/// but less/equal than <paramref name="upperTerm"/>.
///
/// <para/>
/// If an endpoint is <c>null</c>, it is said
/// to be "open". Either or both endpoints may be open. Open endpoints may not
/// be exclusive (you can't select all but the first or last term without
/// explicitly specifying the term to exclude.)
/// </summary>
/// <param name="field"> The field that holds both lower and upper terms. </param>
/// <param name="lowerTerm">
/// The term text at the lower end of the range. </param>
/// <param name="upperTerm">
/// The term text at the upper end of the range. </param>
/// <param name="includeLower">
/// If true, the <paramref name="lowerTerm"/> is
/// included in the range. </param>
/// <param name="includeUpper">
/// If true, the <paramref name="upperTerm"/> is
/// included in the range. </param>
public TermRangeQuery(string field, BytesRef lowerTerm, BytesRef upperTerm, bool includeLower, bool includeUpper)
: base(field)
{
this.lowerTerm = lowerTerm;
this.upperTerm = upperTerm;
this.includeLower = includeLower;
this.includeUpper = includeUpper;
}
/// <summary>
/// Factory that creates a new <see cref="TermRangeQuery"/> using <see cref="string"/>s for term text.
/// </summary>
public static TermRangeQuery NewStringRange(string field, string lowerTerm, string upperTerm, bool includeLower, bool includeUpper)
{
BytesRef lower = lowerTerm == null ? null : new BytesRef(lowerTerm);
BytesRef upper = upperTerm == null ? null : new BytesRef(upperTerm);
return new TermRangeQuery(field, lower, upper, includeLower, includeUpper);
}
/// <summary>
/// Returns the lower value of this range query </summary>
public virtual BytesRef LowerTerm
{
get
{
return lowerTerm;
}
}
/// <summary>
/// Returns the upper value of this range query </summary>
public virtual BytesRef UpperTerm
{
get
{
return upperTerm;
}
}
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public virtual bool IncludesLower
{
get { return includeLower; }
}
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public virtual bool IncludesUpper
{
get { return includeUpper; }
}
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
if (lowerTerm != null && upperTerm != null && lowerTerm.CompareTo(upperTerm) > 0)
{
return TermsEnum.EMPTY;
}
TermsEnum tenum = terms.GetIterator(null);
if ((lowerTerm == null || (includeLower && lowerTerm.Length == 0)) && upperTerm == null)
{
return tenum;
}
return new TermRangeTermsEnum(tenum, lowerTerm, upperTerm, includeLower, includeUpper);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(Field);
buffer.Append(":");
}
buffer.Append(includeLower ? '[' : '{');
// TODO: all these toStrings for queries should just output the bytes, it might not be UTF-8!
buffer.Append(lowerTerm != null ? ("*".Equals(Term.ToString(lowerTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(lowerTerm)) : "*");
buffer.Append(" TO ");
buffer.Append(upperTerm != null ? ("*".Equals(Term.ToString(upperTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(upperTerm)) : "*");
buffer.Append(includeUpper ? ']' : '}');
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + (includeLower ? 1231 : 1237);
result = prime * result + (includeUpper ? 1231 : 1237);
result = prime * result + ((lowerTerm == null) ? 0 : lowerTerm.GetHashCode());
result = prime * result + ((upperTerm == null) ? 0 : upperTerm.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
TermRangeQuery other = (TermRangeQuery)obj;
if (includeLower != other.includeLower)
{
return false;
}
if (includeUpper != other.includeUpper)
{
return false;
}
if (lowerTerm == null)
{
if (other.lowerTerm != null)
{
return false;
}
}
else if (!lowerTerm.Equals(other.lowerTerm))
{
return false;
}
if (upperTerm == null)
{
if (other.upperTerm != null)
{
return false;
}
}
else if (!upperTerm.Equals(other.upperTerm))
{
return false;
}
return true;
}
}
}
| |
using ScriptCs.Contracts;
using ScriptCs.Hosting;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using IOPath = System.IO.Path;
namespace ScriptCs.ComponentModel.Composition
{
/// <summary>
/// Catalog using ScriptCs scripts>
/// </summary>
public class ScriptCsCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement
{
private readonly object _thisLock = new object();
private readonly ScriptCsCatalogOptions _options;
private bool _isDisposed;
private AssemblyCatalog _catalog;
private ReadOnlyCollection<string> _loadedFiles;
/// <summary>
/// Translated absolute path of the path passed into the constructor of <see cref="DirectoryCatalog"/>.
/// </summary>
public string FullPath { get; private set; }
/// <summary>
/// Path passed into the constructor of <see cref="DirectoryCatalog"/>.
/// </summary>
public string Path { get; private set; }
/// <summary>
/// SearchPattern passed into the constructor of <see cref="DirectoryCatalog"/>, or the default *.dll.
/// </summary>
public string SearchPattern { get; private set; }
/// <summary>
/// Set of files that have currently been loaded into the catalog.
/// </summary>
public ReadOnlyCollection<string> LoadedFiles
{
get
{
lock (_thisLock)
{
return _loadedFiles;
}
}
}
/// <summary>
/// Display name of the <see cref="ICompositionElement"/>
/// </summary>
public string DisplayName
{
get { return GetDisplayName(); }
}
/// <summary>
/// Origin of the <see cref="ICompositionElement"/>
/// </summary>
public ICompositionElement Origin
{
get { return null; }
}
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.csx files
/// in the given directory path.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
public ScriptCsCatalog(string path)
: this(path, "*.csx", new ScriptCsCatalogOptions())
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.csx files
/// in the given directory path.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="options">
/// Options of the ScriptCsCatalog.
/// </param>
public ScriptCsCatalog(string path, ScriptCsCatalogOptions options)
: this(path, "*.csx", options)
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the files corresponding to <paramref name="searchPattern"/>
/// in the given directory path.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="searchPattern">
/// Search pattern to get all scripts files from the directory.
/// </param>
public ScriptCsCatalog(string path, string searchPattern)
: this(path, searchPattern, new ScriptCsCatalogOptions())
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the files corresponding to <paramref name="searchPattern"/>
/// in the given directory path.
/// </summary>
/// <param name="path">
/// Path to the directory to scan for assemblies to add to the catalog.
/// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
/// </param>
/// <param name="searchPattern">
/// Search pattern to get all scripts files from the directory.
/// </param>
/// <param name="options">
/// Options of the ScriptCsCatalog.
/// </param>
public ScriptCsCatalog(string path, string searchPattern, ScriptCsCatalogOptions options)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(searchPattern))
{
throw new ArgumentNullException("searchPattern");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
_options = options.OverridesNullByDefault();
Initialize(path, searchPattern);
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the <paramref name="scriptFiles"/>.
/// </summary>
/// <param name="scriptFiles">
/// Scripts files to be executed and added to the catalog.
/// </param>
public ScriptCsCatalog(IEnumerable<string> scriptFiles)
: this(scriptFiles, new ScriptCsCatalogOptions())
{
}
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the <paramref name="scriptFiles"/>.
/// </summary>
/// <param name="scriptFiles">
/// Scripts files to be executed and added to the catalog.
/// </param>
/// <param name="options">
/// Options of the ScriptCsCatalog.
/// </param>
public ScriptCsCatalog(IEnumerable<string> scriptFiles, ScriptCsCatalogOptions options)
{
if (scriptFiles == null || !scriptFiles.Any())
{
throw new ArgumentNullException("scriptFiles");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
_options = options.OverridesNullByDefault();
Initialize(scriptFiles.ToArray());
}
/// <summary>
/// Returns a string representation of the directory catalog.
/// </summary>
/// <returns>
/// A <see cref="String"/> containing the string representation of the <see cref="ScriptCsCatalog"/>.
/// </returns>
public override string ToString()
{
return GetDisplayName();
}
/// <summary>
/// Returns an enumerator that iterates through the catalog
/// </summary>
/// <returns></returns>
public override IEnumerator<ComposablePartDefinition> GetEnumerator()
{
return _catalog.GetEnumerator();
}
/// <summary>
/// Get a list of export definitions that match the constraint defined by the specified <see cref="ImportDefinition"/> object.
/// </summary>
/// <param name="definition">The condition of the <see cref="ExportDefinition"/> objects to be returned.</param>
/// <returns></returns>
public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
return _catalog.GetExports(definition);
}
/// <summary>
/// Refreshes the <see cref="ComposablePartDefinition"/>s with the latest files in the directory that match
/// the searchPattern. If any files have been added they will be added to the catalog and if any files were
/// removed they will be removed from the catalog. For files that have been removed keep in mind that the
/// assembly cannot be unloaded from the process so <see cref="ComposablePartDefinition"/>s for those files
/// will simply be removed from the catalog.
///
/// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/>.
/// </summary>
/// <exception cref="DirectoryNotFoundException">
/// The specified path has been removed since object construction.
/// </exception>
public void Refresh()
{
ThrowIfDisposed();
ComposablePartDefinition[] addedDefinitions;
ComposablePartDefinition[] removedDefinitions;
object changeReferenceObject;
string[] afterFiles;
while (true)
{
afterFiles = GetFiles();
lock (_thisLock)
{
changeReferenceObject = _loadedFiles;
}
var newCatalog = ExecuteScripts(afterFiles);
// Notify listeners to give them a preview before completing the changes
addedDefinitions = newCatalog.ToArray();
removedDefinitions = _catalog.ToArray();
using (var atomicComposition = new AtomicComposition())
{
var changingArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, atomicComposition);
OnChanging(changingArgs);
// if the change went through then write the catalog changes
lock (_thisLock)
{
if (changeReferenceObject != _loadedFiles)
{
// Someone updated the list while we were diffing so we need to try the diff again
continue;
}
_catalog = newCatalog;
_loadedFiles = afterFiles.ToReadOnlyCollection();
// Lastly complete any changes added to the atomicComposition during the change event
atomicComposition.Complete();
// Break out of the while(true)
break;
} // WriteLock
} // AtomicComposition
} // while (true)
var changedArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, null);
OnChanged(changedArgs);
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
if (changedEvent != null)
{
changedEvent(this, e);
}
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
if (changingEvent != null)
{
changingEvent(this, e);
}
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="ComposablePartCatalog" /> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing && !_isDisposed)
{
AssemblyCatalog catalogs = null;
try
{
lock (_thisLock)
{
if (!_isDisposed)
{
catalogs = _catalog;
_catalog = null;
_isDisposed = true;
}
}
}
finally
{
if (catalogs != null)
{
catalogs.Dispose();
}
}
}
}
finally
{
base.Dispose(disposing);
}
}
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException("ScriptCsCatalog");
}
}
private void Initialize(string path, string searchPattern)
{
Path = path;
FullPath = GetFullPath(path);
SearchPattern = searchPattern;
var scriptFiles = GetFiles();
_loadedFiles = scriptFiles.ToReadOnlyCollection();
_catalog = ExecuteScripts(scriptFiles);
}
private void Initialize(string[] scriptFiles)
{
foreach (var scriptFile in scriptFiles)
{
if (!_options.FileSystem.FileExists(scriptFile))
{
throw new FileNotFoundException(string.Format("Script: '{0}' does not exist", scriptFile), scriptFile);
}
}
_loadedFiles = scriptFiles.ToReadOnlyCollection();
_catalog = ExecuteScripts(scriptFiles);
}
private AssemblyCatalog ExecuteScripts(string[] scriptFiles)
{
var services = CreateScriptServices();
ScriptResult result = null;
if (_options.KeepScriptsSeparated && scriptFiles.Any())
{
foreach (var scriptFile in scriptFiles)
{
var loader = GetLoader(scriptFile);
result = ExecuteScript(services, loader);
}
}
else
{
var loader = GetLoader(scriptFiles);
result = ExecuteScript(services, loader);
}
AssemblyCatalog catalog = null;
var marker = result.ReturnValue as Type;
if (marker != null)
{
catalog = new AssemblyCatalog(marker.Assembly, this);
}
return catalog;
}
private ScriptResult ExecuteScript(ScriptServices services, string loader)
{
var result = services.Executor.ExecuteScript(loader);
if (result.CompileExceptionInfo != null)
{
result.CompileExceptionInfo.Throw();
}
if (result.ExecuteExceptionInfo != null)
{
result.ExecuteExceptionInfo.Throw();
}
return result;
}
private string GetFullPath(string path)
{
if (!IOPath.IsPathRooted(path) && _options.FileSystem.CurrentDirectory != null)
{
path = IOPath.Combine(_options.FileSystem.CurrentDirectory, path);
}
return IOPath.GetFullPath(path);
}
private string[] GetFiles()
{
if (!_options.FileSystem.DirectoryExists(FullPath))
{
throw new DirectoryNotFoundException(string.Format("Scripts folder: '{0}' does not exist", FullPath));
}
return _options.FileSystem.EnumerateFiles(FullPath, SearchPattern).ToArray();
}
private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture, "{0} (Path=\"{1}\")", GetType().Name, Path);
}
private string GetLoader(params string[] scriptFiles)
{
var builder = new StringBuilder();
foreach (var scriptFile in scriptFiles)
{
builder.AppendFormat("#load {0}{1}", scriptFile, Environment.NewLine);
}
builder.AppendLine("public class Marker {}");
builder.AppendLine("typeof(Marker)");
return builder.ToString();
}
private ScriptServices CreateScriptServices()
{
var console = new ScriptConsole();
var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);
var initializationServices = new InitializationServices(logProvider, new Dictionary<Type, object> { { typeof(IFileSystem), _options.FileSystem } });
initializationServices.GetAppDomainAssemblyResolver().Initialize();
var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices);
scriptServicesBuilder.Overrides[typeof(IFileSystem)] = _options.FileSystem;
scriptServicesBuilder.LoadScriptPacks();
scriptServicesBuilder.LoadModules(".csx", _options.Modules);
var scriptServices = scriptServicesBuilder.Build();
var assemblies = scriptServices.AssemblyResolver.GetAssemblyPaths(_options.FileSystem.CurrentDirectory, true);
var packs = scriptServices.ScriptPackResolver.GetPacks();
scriptServices.Executor.Initialize(assemblies, packs, _options.ScriptArgs);
scriptServices.Executor.AddReferences(typeof(Attribute), typeof(ExportAttribute));
scriptServices.Executor.ImportNamespaces("System.ComponentModel.Composition");
if (_options.References != null)
{
scriptServices.Executor.AddReferenceAndImportNamespaces(_options.References);
}
return scriptServices;
}
}
}
| |
// 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.
// Do not remove this, it is needed to retain calls to these conditional methods in release builds
#define DEBUG
namespace System.Diagnostics
{
/// <summary>
/// Provides a set of properties and methods for debugging code.
/// </summary>
static partial class Debug
{
private static readonly object s_lock = new object();
public static bool AutoFlush { get { return true; } set { } }
[ThreadStatic]
private static int s_indentLevel;
public static int IndentLevel
{
get
{
return s_indentLevel;
}
set
{
s_indentLevel = value < 0 ? 0 : value;
}
}
private static int s_indentSize = 4;
public static int IndentSize
{
get
{
return s_indentSize;
}
set
{
s_indentSize = value < 0 ? 0 : value;
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Close() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Flush() { }
[System.Diagnostics.Conditional("DEBUG")]
public static void Indent()
{
IndentLevel++;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Unindent()
{
IndentLevel--;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string message)
{
Write(message);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Print(string format, params object[] args)
{
Write(string.Format(null, format, args));
}
private static readonly object s_ForLock = new Object();
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition)
{
Assert(condition, string.Empty, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message)
{
Assert(condition, message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
[System.Security.SecuritySafeCritical]
public static void Assert(bool condition, string message, string detailMessage)
{
if (!condition)
{
string stackTrace;
try
{
stackTrace = Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
}
catch
{
stackTrace = "";
}
WriteLine(FormatAssert(stackTrace, message, detailMessage));
s_logger.ShowAssertDialog(stackTrace, message, detailMessage);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Fail(string message)
{
Assert(false, message, string.Empty);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Fail(string message, string detailMessage)
{
Assert(false, message, detailMessage);
}
private static string FormatAssert(string stackTrace, string message, string detailMessage)
{
string newLine = GetIndentString() + NewLine;
return SR.DebugAssertBanner + newLine
+ SR.DebugAssertShortMessage + newLine
+ message + newLine
+ SR.DebugAssertLongMessage + newLine
+ detailMessage + newLine
+ stackTrace;
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args)
{
Assert(condition, message, string.Format(detailMessageFormat, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string message)
{
Write(message + NewLine);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string message)
{
lock (s_lock)
{
if (message == null)
{
WriteCore(string.Empty);
return;
}
if (s_needIndent)
{
message = GetIndentString() + message;
s_needIndent = false;
}
WriteCore(message);
if (message.EndsWith(NewLine))
{
s_needIndent = true;
}
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object value)
{
WriteLine(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(object value, string category)
{
WriteLine(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string format, params object[] args)
{
WriteLine(string.Format(null, format, args));
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLine(string message, string category)
{
if (category == null)
{
WriteLine(message);
}
else
{
WriteLine(category + ":" + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object value)
{
Write(value?.ToString());
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(string message, string category)
{
if (category == null)
{
Write(message);
}
else
{
Write(category + ":" + message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void Write(object value, string category)
{
Write(value?.ToString(), category);
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string message)
{
if (condition)
{
Write(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object value)
{
if (condition)
{
Write(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, string message, string category)
{
if (condition)
{
Write(message, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteIf(bool condition, object value, string category)
{
if (condition)
{
Write(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object value)
{
if (condition)
{
WriteLine(value);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, object value, string category)
{
if (condition)
{
WriteLine(value, category);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string message)
{
if (condition)
{
WriteLine(message);
}
}
[System.Diagnostics.Conditional("DEBUG")]
public static void WriteLineIf(bool condition, string message, string category)
{
if (condition)
{
WriteLine(message, category);
}
}
private static bool s_needIndent;
private static string s_indentString;
private static string GetIndentString()
{
int indentCount = IndentSize * IndentLevel;
if (s_indentString?.Length == indentCount)
{
return s_indentString;
}
return s_indentString = new string(' ', indentCount);
}
private static void WriteCore(string message)
{
s_logger.WriteCore(message);
}
internal interface IDebugLogger
{
void ShowAssertDialog(string stackTrace, string message, string detailMessage);
void WriteCore(string message);
}
private sealed class DebugAssertException : Exception
{
internal DebugAssertException(string message, string detailMessage, string stackTrace) :
base(message + NewLine + detailMessage + NewLine + stackTrace)
{
}
}
}
}
| |
using System;
namespace Nucleo.Web
{
/// <summary>
/// Represents the type of member that belongs to the control or extender (a property, event, etc.)
/// </summary>
public enum ClientMemberType
{
Property,
Event
}
[Flags]
public enum CoreScriptIncludes
{
Common = 1,
WebUtilities = 2,
ObjectUtilities = 3
}
public enum JavaScriptConvertObjectType
{
Collection,
SingleInstance,
Unknown
}
public enum NumericEditingType
{
WholeNumber,
Money,
Unknown
}
/// <summary>
/// Represents the rendering mode for the control, whether the control renders server-side only, client-side only rendering (meaning the client component takes over more of the rendering, usually wth JavaScript), or a mix of the two options.
/// </summary>
public enum RenderMode
{
ServerOnly = 1,
ClientOnly = 2,
ClientAndServer = 3
}
/// <summary>
/// The type of layout to repeat with.
/// </summary>
public enum RepeatingLayout
{
Table = 0,
Flow = 1,
List = 2
}
/// <summary>
/// The include options for the service reference, controlling when the service reference gets included.
/// </summary>
public enum ServiceReferenceIncludeOptions
{
Any = 0,
UserAuthenticated = 1,
UserUnauthenticated = 2
}
public enum ValidationItemType
{
Error,
Warning,
Information
}
/// <summary>
/// Gets the format of the template using the correct web library.
/// </summary>
/// <remarks>Will add ASP.NET AJAX 4 support later.</remarks>
public enum WebTemplateFormat
{
Prototype = 1
}
}
namespace Nucleo.Web.Browsers
{
public enum BrowserCapabilityFeature
{
ActiveXControls,
Adapters,
AOL,
BackgroundSounds,
Beta,
Browser,
Browsers,
CanCombineFormsInDeck,
CanInitiateVoiceCall,
CanRenderAfterInputOrSelectElement,
CanRenderEmptySelects,
CanRenderInputAndSelectElementsTogether,
CanRenderMixedSelects,
CanRenderOneventAndPrevElementsTogether,
CanRenderPostBackCards,
CanRenderSetvarZeroWithMultiSelectionList,
CanSendMail,
CDF,
ClrVersion,
Cookies,
Crawler,
DefaultSubmitButtonLimit,
EcmaScriptVersion,
Frames,
GatewayMajorVersion,
GatewayMinorVersion,
GatewayVersion,
HasBackButton,
HidesRightAlignedMultiselectScrollbars,
Id,
InputType,
IsColor,
IsMobileDevice,
JavaApplets,
JScriptVersion,
MajorVersion,
MaximumHrefLength,
MaximumRenderedPageSize,
MaximumSoftkeyLabelLength,
MinorVersion,
MinorVersionString,
MobileDeviceManufacturer,
MobileDeviceModel,
MSDomVersion,
NumberOfSoftkeys,
Platform,
PreferredImageMime,
PreferredRenderingMime,
PreferredRenderingType,
PreferredRequestEncoding,
PreferredResponseEncoding,
RendersBreakBeforeWmlSelectAndInput,
RendersBreaksAfterHtmlLists,
RendersBreaksAfterWmlAnchor,
RendersBreaksAfterWmlInput,
RendersWmlDoAcceptsInline,
RendersWmlSelectsAsMenuCards,
RequiredMetaTagNameValue,
RequiresAttributeColonSubstitution,
RequiresContentTypeMetaTag,
RequiresControlStateInSession,
RequiresDBCSCharacter,
RequiresHtmlAdaptiveErrorReporting,
RequiresLeadingPageBreak,
RequiresNoBreakInFormatting,
RequiresOutputOptimization,
RequiresPhoneNumbersAsPlainText,
RequiresSpecialViewStateEncoding,
RequiresUniqueFilePathSuffix,
RequiresUniqueHtmlCheckboxNames,
RequiresUniqueHtmlInputNames,
RequiresUrlEncodedPostfieldValues,
ScreenBitDepth,
ScreenCharactersHeight,
ScreenCharactersWidth,
ScreenPixelsHeight,
ScreenPixelsWidth,
SupportsAccesskeyAttribute,
SupportsBodyColor,
SupportsBold,
SupportsCacheControlMetaTag,
SupportsCallback,
SupportsCss,
SupportsDivAlign,
SupportsDivNoWrap,
SupportsEmptyStringInCookieValue,
SupportsFontColor,
SupportsFontName,
SupportsFontSize,
SupportsImageSubmit,
SupportsIModeSymbols,
SupportsInputIStyle,
SupportsInputMode,
SupportsItalic,
SupportsJPhoneMultiMediaAttributes,
SupportsJPhoneSymbols,
SupportsQueryStringInFormAction,
SupportsRedirectWithCookie,
SupportsSelectMultiple,
SupportsUncheck,
SupportsXmlHttp,
Tables,
TagWriter,
Type,
UseOptimizedCacheKey,
VBScript,
Version,
W3CDomVersion,
Win16,
Win32
}
}
namespace Nucleo.Web.ClientRegistration
{
public enum ClientPropertyContentType
{
Data,
ClientElement,
AjaxComponent,
Event
}
}
namespace Nucleo.Web.CodeGeneration
{
public enum ClassMemberType
{
Method,
Property,
Event
}
}
namespace Nucleo.Web.ControlStorage
{
/// <summary>
/// Represents the storage for control property dictionary.
/// </summary>
public enum ControlPropertyStorage
{
/// <summary>
/// Persist the values.
/// </summary>
Persist,
/// <summary>
/// Don't persist the values.
/// </summary>
DontPersist
}
}
namespace Nucleo.Web.Description
{
public enum ScriptIDFormatting
{
Standard,
Element,
Control,
Extender
}
}
namespace Nucleo.Web.FormControls
{
public enum FormCurrentView
{
ReadOnly,
Insert,
Edit
}
public enum SectionHeaderAppearance
{
None,
H1,
H2,
H3,
Strong
}
}
namespace Nucleo.Web.Pages
{
public enum PageControllerEvent : int
{
Startup = 0,
Initializing = 1,
Loading = 2,
ValidateState = 3,
PrepareToRender = 4,
Rendering = 5,
Rendered = 6,
Unloading = 7
}
public enum PageEvent
{
Init,
InitComplete,
PreInit,
Load,
LoadComplete,
PreLoad,
PreRender,
PreRenderComplete,
Unload,
Validated,
Validating
}
}
namespace Nucleo.Web.Panels
{
public enum FiltrationAction
{
Before,
After
}
}
namespace Nucleo.Web.Security.Configuration
{
public enum AuthorizationCheckAction
{
Redirect,
ThrowException
}
}
namespace Nucleo.Web.ContainerControls
{
/// <summary>
/// Represents the type of operation to perform (dragging or dropping).
/// </summary>
public enum DragDropPanelOperation
{
Drag = 1,
Drop = 2
}
/// <summary>
/// Represents the position for the panel.
/// </summary>
public enum PanelPosition
{
BottomLeft = 1
}
}
namespace Nucleo.Web.ContentControls
{
/// <summary>
/// Represents the type of operation to perform (dragging or dropping).
/// </summary>
public enum DragDropPanelOperation
{
Drag = 1,
Drop = 2
}
}
namespace Nucleo.Web.Controls
{
/// <summary>
/// Represents the click action for a link, whether to redirect to another page, or for firing an event.
/// </summary>
public enum LinkClickAction
{
FireEvent = 1,
Redirect = 2
}
/// <summary>
/// Represents the target for the click action, whether targeting the same window or a new one.
/// </summary>
public enum LinkTargetOptions
{
SameWindow = 1,
NewWindow = 2
}
}
namespace Nucleo.Web.DataSourceControls.Parameters
{
public enum IdentityEvaluation
{
WindowsIdentity,
OnlineUserIdentity
}
}
namespace Nucleo.Web.DropDownControls
{
public enum ComboListDropDownMode
{
ItemTemplate,
Columns,
Custom
}
}
namespace Nucleo.Web.EditorControls
{
/// <summary>
/// Represents the current state of the editor, whether in normal mode or in error mode.
/// </summary>
public enum EditorCurrentState
{
Normal = 1,
Error = 2
}
}
namespace Nucleo.Web.ListControls
{
public enum ListControlExtendedType
{
CheckboxList = 1,
RadioButtonList = 2,
DropDownList = 3,
BulletedList = 4,
ListBox = 5
}
public enum ListInterfaceType
{
CheckboxList = 0,
RadioButtonList = 1,
DropDownList = 2,
BulletedList = 3,
Custom = 4
}
}
namespace Nucleo.Web.MathControls
{
/// <summary>
/// Represents the user interface of the calculator view.
/// </summary>
public enum CalculatorViewAppearance
{
Readonly,
Editable,
Custom
}
}
namespace Nucleo.Web.Scripts
{
public enum ScriptFramework
{
WebForms,
Mvc,
Mvp
}
}
namespace Nucleo.Web.Searching
{
public enum ControlSearcherDirection
{
Up
}
}
namespace Nucleo.Web.TabularControls
{
public enum StaticDetailsViewMode
{
ReadOnly,
Edit,
Insert
}
public enum StaticDetailsViewRowState
{
DataItem,
AlternateItem,
HeaderItem,
FooterItem
}
}
namespace Nucleo.Web.Tags
{
public enum TagRenderingMode
{
Full,
BeginTag,
EndTag,
Children
}
}
namespace Nucleo.Web.Templates
{
public enum ClientTemplateEvaluation
{
MSAjaxFormatString,
Prototype
}
}
namespace Nucleo.Web.Testing
{
public enum TestScope
{
Client,
Server,
ClientAndServer
}
}
namespace Nucleo.Web.ValidationControls
{
/// <summary>
/// Represents the type of validation message to display to the user.
/// </summary>
public enum MessageType
{
Error,
Warning,
Information
}
public enum NumericInputType
{
Any,
WholeNumber,
Decimal,
Money,
FahrenheitTemperature,
CelciusTemperature
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the status of an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/// Instance status provides information about two types of scheduled events for
/// an instance that may require your attention, Scheduled Reboot and Scheduled Retirement.
/// Only information about instances in the running state is returned.
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class DescribeInstanceStatusRequest : EC2Request
{
private List<string> instanceIdField;
private List<Filter> filterField;
private string nextTokenField;
private int? maxResultsField;
private bool? includeAllInstancesField;
/// <summary>
/// List of instance IDs.
/// If not specified, all instances are described.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceId")]
public List<string> InstanceId
{
get
{
if (this.instanceIdField == null)
{
this.instanceIdField = new List<string>();
}
return this.instanceIdField;
}
set { this.instanceIdField = value; }
}
/// <summary>
/// Sets instance IDs.
/// </summary>
/// <param name="list">Instance IDs to describe.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeInstanceStatusRequest WithInstanceId(params string[] list)
{
foreach (string item in list)
{
InstanceId.Add(item);
}
return this;
}
/// <summary>
/// Checks if InstanceId property is set
/// </summary>
/// <returns>true if InstanceId property is set</returns>
public bool IsSetInstanceId()
{
return (InstanceId.Count > 0);
}
/// <summary>
/// A list of filters used to match system-defined properties and user-defined tags associated with
/// the specified Instances.
/// For a complete reference to the available filter keys for this operation, see the
/// Amazon EC2 API reference.
/// </summary>
[XmlElementAttribute(ElementName = "Filter")]
public List<Filter> Filter
{
get
{
if (this.filterField == null)
{
this.filterField = new List<Filter>();
}
return this.filterField;
}
set { this.filterField = value; }
}
/// <summary>
/// Sets filters used to match system-defined properties and user-defined tags associated with
/// the specified Instances.
/// </summary>
/// <param name="list">A list of filters used to match system-defined properties and user-defined tags associated with
/// the specified Instances.
/// For a complete reference to the available filter keys for this operation, see the
/// Amazon EC2 API reference.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeInstanceStatusRequest WithFilter(params Filter[] list)
{
foreach (Filter item in list)
{
Filter.Add(item);
}
return this;
}
/// <summary>
/// Checks if Filter property is set
/// </summary>
/// <returns>true if Filter property is set</returns>
public bool IsSetFilter()
{
return (Filter.Count > 0);
}
/// <summary>
/// Token specifying the next paginated set of results to return.
/// </summary>
public string NextToken
{
get { return this.nextTokenField; }
set { this.nextTokenField = value; }
}
/// <summary>
/// Sets the token specifying the next paginated set of results to return.
/// </summary>
/// <param name="nextToken"></param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeInstanceStatusRequest WithNextToken(string nextToken)
{
this.nextTokenField = nextToken;
return this;
}
/// <summary>
/// Checks if the NextToken property is set.
/// </summary>
/// <returns>true if NextToken property is set</returns>
public bool IsSetNextToken()
{
return this.nextTokenField != null;
}
/// <summary>
/// The maximum number of paginated instance items per response.
/// </summary>
public int MaxResults
{
get { return this.maxResultsField.GetValueOrDefault(); }
set { this.maxResultsField = value; }
}
/// <summary>
/// Sets the maximum number of paginated instance items per response.
/// </summary>
/// <param name="maxResults">Maximum number of paginated instance items</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeInstanceStatusRequest WithMaxResults(int maxResults)
{
this.maxResultsField = maxResults;
return this;
}
/// <summary>
/// Checks if the MaxResults property is set.
/// </summary>
/// <returns>true if MaxResults property is set</returns>
public bool IsSetMaxResults()
{
return this.maxResultsField.HasValue;
}
/// <summary>
/// Gets and sets whether the request includes all or only running instances.
/// When true, returns the health status for all instances (e.g., running, stopped, pending, shutting down, etc.).
/// When false (default), returns only the health status for running instances.
/// </summary>
public bool IncludeAllInstances
{
get { return this.includeAllInstancesField.GetValueOrDefault(); }
set { this.includeAllInstancesField = value; }
}
/// <summary>
/// Sets whether the request includes all or only running instances.
/// </summary>
/// <param name="includeAllInstances">
/// Set true to return the health status for all instances (e.g., running, stopped, pending, shutting down, etc.).
/// Set false to return only the health status for running instances.
/// </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeInstanceStatusRequest WithIncludeAllInstances(bool includeAllInstances)
{
this.includeAllInstancesField = includeAllInstances;
return this;
}
/// <summary>
/// Checks if the IncludeAllInstances property is set.
/// </summary>
/// <returns>True if the IncludeAllInstances property is set.</returns>
public bool IsSetIncludeAllInstances()
{
return this.includeAllInstancesField != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Assets.Scripts.Rules;
using UnityEngine;
public class ButtonComponentSolver : ComponentSolver
{
public ButtonComponentSolver(TwitchModule module) :
base(module)
{
ModuleInformation buttonInfo = ComponentSolverFactory.GetModuleInfo("ButtonComponentSolver", "!{0} tap [tap the button] | !{0} hold [hold the button] | !{0} release 7 [release when the digit shows 7]");
ModuleInformation buttonInfoModified = ComponentSolverFactory.GetModuleInfo("ButtonComponentModifiedSolver", "Click the button with !{0} tap. Click the button at a time with !{0} tap 8:55 8:44 8:33. Hold the button with !{0} hold. Release the button with !{0} release 9:58 9:49 9:30.");
var buttonModule = (ButtonComponent) module.BombComponent;
buttonModule.GetComponent<Selectable>().OnCancel += buttonModule.OnButtonCancel;
_button = buttonModule.button;
ModInfo = VanillaRuleModifier.IsSeedVanilla() ? buttonInfo : buttonInfoModified;
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
bool isModdedSeed = VanillaRuleModifier.IsSeedModded();
inputCommand = inputCommand.ToLowerInvariant().Trim();
if (!_held && inputCommand.EqualsAny("tap", "click"))
{
yield return "tap";
yield return DoInteractionClick(_button);
}
if (!_held && (inputCommand.StartsWith("tap ") ||
inputCommand.StartsWith("click ")))
{
if (!isModdedSeed)
yield break;
yield return "tap2";
IEnumerator releaseCoroutine = ReleaseCoroutineModded(inputCommand.Substring(inputCommand.IndexOf(' ')));
while (releaseCoroutine.MoveNext())
yield return releaseCoroutine.Current;
}
else if (!_held && inputCommand.Equals("hold"))
{
yield return "hold";
_held = true;
DoInteractionStart(_button);
yield return new WaitForSeconds(2.0f);
}
else if (_held)
{
string[] commandParts = inputCommand.Split(' ');
if (commandParts.Length != 2 || !commandParts[0].Equals("release")) yield break;
IEnumerator releaseCoroutine;
if (!isModdedSeed)
{
if (!int.TryParse(commandParts[1], out int second))
yield break;
if (second >= 0 && second <= 9)
releaseCoroutine = ReleaseCoroutineVanilla(second);
else
yield break;
}
else
releaseCoroutine = ReleaseCoroutineModded(inputCommand.Substring(inputCommand.IndexOf(' ')));
while (releaseCoroutine.MoveNext())
yield return releaseCoroutine.Current;
}
}
private IEnumerator ReleaseCoroutineVanilla(int second)
{
yield return "release";
TimerComponent timerComponent = Module.Bomb.Bomb.GetTimer();
string secondString = second.ToString();
float timeRemaining = float.PositiveInfinity;
while (timeRemaining > 0.0f && _held)
{
timeRemaining = timerComponent.TimeRemaining;
if (Module.Bomb.CurrentTimerFormatted.Contains(secondString))
{
DoInteractionEnd(_button);
_held = false;
}
yield return $"trycancel The button was not {(_held ? "released" : "tapped")} due to a request to cancel.";
}
}
private IEnumerator ReleaseCoroutineModded(string second)
{
TimerComponent timerComponent = Module.Bomb.Bomb.GetTimer();
int target = Mathf.FloorToInt(timerComponent.TimeRemaining);
bool waitingMusic = true;
string[] times = second.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
List<int> result = new List<int>();
foreach (string time in times)
{
string[] split = time.Split(':');
int minutesInt = 0, hoursInt = 0, daysInt = 0;
switch (split.Length)
{
case 1 when int.TryParse(split[0], out int secondsInt):
case 2 when int.TryParse(split[0], out minutesInt) && int.TryParse(split[1], out secondsInt):
case 3 when int.TryParse(split[0], out hoursInt) && int.TryParse(split[1], out minutesInt) && int.TryParse(split[2], out secondsInt):
case 4 when int.TryParse(split[0], out daysInt) && int.TryParse(split[1], out hoursInt) && int.TryParse(split[2], out minutesInt) && int.TryParse(split[3], out secondsInt):
result.Add(daysInt * 86400 + hoursInt * 3600 + minutesInt * 60 + secondsInt);
break;
default:
yield break;
}
}
yield return null;
bool minutes = times.Any(x => x.Contains(":"));
minutes |= result.Any(x => x >= 60);
if (!minutes)
{
target %= 60;
result = result.Select(x => x % 60).Distinct().ToList();
}
for (int i = result.Count - 1; i >= 0; i--)
{
int r = result[i];
if (!minutes && !OtherModes.ZenModeOn)
waitingMusic &= target + (r > target ? 60 : 0) - r > 30;
else if (!minutes)
waitingMusic &= r + (r < target ? 60 : 0) - target > 30;
else if (!OtherModes.ZenModeOn)
{
if (r > target)
{
result.RemoveAt(i);
continue;
}
waitingMusic &= target - r > 30;
}
else
{
if (r < target)
{
result.RemoveAt(i);
continue;
}
waitingMusic &= r - target > 30;
}
}
if (!result.Any())
{
yield return
$"sendtochaterror The button was not {(_held ? "released" : "tapped")} because all of your specified times are {(OtherModes.ZenModeOn ? "less" : "greater")} than the time remaining.";
yield break;
}
if (waitingMusic)
yield return "waiting music";
while (result.All(x => x != target))
{
yield return $"trycancel The button was not {(_held ? "released" : "tapped")} due to a request to cancel.";
target = (int) (timerComponent.TimeRemaining + (OtherModes.ZenModeOn ? -0.25f : 0.25f));
if (!minutes) target %= 60;
}
if (!_held)
yield return DoInteractionClick(_button);
else
DoInteractionEnd(_button);
_held = false;
}
private static Rule ForcedSolveRule()
{
Rule rule = new Rule();
rule.Queries.Add(new Query { Property = ButtonForceSolveQuery, Args = new Dictionary<string, object>() });
rule.SolutionArgs = new Dictionary<string, object>();
rule.Solution = ButtonForceSolveSolution;
return rule;
}
private static readonly QueryableButtonProperty ButtonForceSolveQuery = new QueryableButtonProperty
{
Name = "forcesolve",
Text = "If the user with AccessLevel.Admin or higher has issued !# solve on this Big Button instance on Twitch Plays",
QueryFunc = ((_, __) => true)
};
private static readonly Solution ButtonForceSolveSolution = new Solution
{
Text = "Force solve The Button.",
SolutionMethod = (_, __) => 0
};
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
ButtonRuleSet ruleset = RuleManager.Instance.ButtonRuleSet;
ruleset.HoldRuleList.Insert(0, ForcedSolveRule());
ruleset.RuleList.Insert(0, ForcedSolveRule());
if (!_held)
yield return DoInteractionClick(_button);
else
{
DoInteractionEnd(_button);
_held = false;
}
ruleset.HoldRuleList.RemoveAt(0);
ruleset.RuleList.RemoveAt(0);
}
private readonly PressableButton _button;
private bool _held;
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the Network
/// Security Groups for your subscription.
/// </summary>
public partial interface INetworkSecurityGroupOperations
{
/// <summary>
/// Adds a Network Security Group to a network interface.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to a network
/// interface operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> AddToNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Adds a Network Security Group to a Role.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to Role
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> AddToRoleAsync(string serviceName, string deploymentName, string roleName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Adds a Network Security Group to a subnet.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to subnet
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> AddToSubnetAsync(string virtualNetworkName, string subnetName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Adds a Network Security Group to a network interface.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to a network
/// interface operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginAddingToNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Adds a Network Security Group to a Role.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to Role
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginAddingToRoleAsync(string serviceName, string deploymentName, string roleName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Adds a Network Security Group to a subnet.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Add Network Security Group to subnet
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginAddingToSubnetAsync(string virtualNetworkName, string subnetName, NetworkSecurityGroupAddAssociationParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Creates a new Network Security Group.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Network Security Group operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginCreatingAsync(NetworkSecurityGroupCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Deletes the pecified Network Security Group from your
/// subscription.If the Network Security group is still associated
/// with some VM/Role/Subnet, the deletion will fail. In order to
/// successfully delete the Network Security, it needs to be not used.
/// </summary>
/// <param name='networkSecurityGroupName'>
/// The name of the Network Security Group to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginDeletingAsync(string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Deletes a rule from the specified Network Security Group.
/// </summary>
/// <param name='networkSecurityGroupName'>
/// The name of the Network Security Group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginDeletingRuleAsync(string networkSecurityGroupName, string ruleName, CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a network interface.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginRemovingFromNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a role.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginRemovingFromRoleAsync(string serviceName, string deploymentName, string roleName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a subnet.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginRemovingFromSubnetAsync(string virtualNetworkName, string subnetName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Sets a new Network Security Rule to existing Network Security Group.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Set Network Security Rule operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> BeginSettingRuleAsync(string networkSecurityGroupName, string ruleName, NetworkSecuritySetRuleParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Creates a new Network Security Group.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Network Security Group operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> CreateAsync(NetworkSecurityGroupCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Delete Network Security Group operation removes thespecified
/// Network Security Group from your subscription.If the Network
/// Security group is still associated with some VM/Role/Subnet, the
/// deletion will fail. In order to successfully delete the Network
/// Security, it needs to be not used.
/// </summary>
/// <param name='networkSecurityGroupName'>
/// The name of the Network Security Group to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> DeleteAsync(string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// The Delete Network Security Rule operation removes a rule from the
/// specified Network Security Group.
/// </summary>
/// <param name='networkSecurityGroupName'>
/// The name of the Network Security Group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> DeleteRuleAsync(string networkSecurityGroupName, string ruleName, CancellationToken cancellationToken);
/// <summary>
/// Gets the details for the specified Network Security Group in the
/// subscription.
/// </summary>
/// <param name='networkSecurityGroupName'>
/// The name of the Network Security Group to retrieve.
/// </param>
/// <param name='detailLevel'>
/// Use 'Full' to list rules.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A Network Security Group associated with your subscription.
/// </returns>
Task<NetworkSecurityGroupGetResponse> GetAsync(string networkSecurityGroupName, string detailLevel, CancellationToken cancellationToken);
/// <summary>
/// Gets the Network Security Group applied to a specific network
/// interface.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Network Security Group associated with an entity: subnet,
/// network interface or role.
/// </returns>
Task<NetworkSecurityGroupGetAssociationResponse> GetForNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, CancellationToken cancellationToken);
/// <summary>
/// Gets the Network Security Group applied to a specific role.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Network Security Group associated with an entity: subnet,
/// network interface or role.
/// </returns>
Task<NetworkSecurityGroupGetAssociationResponse> GetForRoleAsync(string serviceName, string deploymentName, string roleName, CancellationToken cancellationToken);
/// <summary>
/// Gets the Network Security Group applied to a specific subnet.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Network Security Group associated with an entity: subnet,
/// network interface or role.
/// </returns>
Task<NetworkSecurityGroupGetAssociationResponse> GetForSubnetAsync(string virtualNetworkName, string subnetName, CancellationToken cancellationToken);
/// <summary>
/// Lists all of the Network Security Groups for the subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Definitions operation response.
/// </returns>
Task<NetworkSecurityGroupListResponse> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a network interface.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> RemoveFromNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a role.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> RemoveFromRoleAsync(string serviceName, string deploymentName, string roleName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Removes a Network Security Group from a subnet.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> RemoveFromSubnetAsync(string virtualNetworkName, string subnetName, string networkSecurityGroupName, CancellationToken cancellationToken);
/// <summary>
/// Add new Network Security Rule to existing Network Security Group.
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Set Network Security Rule operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<OperationStatusResponse> SetRuleAsync(string networkSecurityGroupName, string ruleName, NetworkSecuritySetRuleParameters parameters, CancellationToken cancellationToken);
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
namespace Orleans.Runtime
{
/// <summary>
/// SafeTimerBase - an internal base class for implementing sync and async timers in Orleans.
///
/// </summary>
internal class SafeTimerBase : IDisposable
{
private const string asyncTimerName ="Orleans.Runtime.asynTask.SafeTimerBase";
private const string syncTimerName = "Orleans.Runtime.sync.SafeTimerBase";
private Timer timer;
private Func<object, Task> asynTaskCallback;
private TimerCallback syncCallbackFunc;
private TimeSpan dueTime;
private TimeSpan timerFrequency;
private bool timerStarted;
private DateTime previousTickTime;
private int totalNumTicks;
private ILogger logger;
internal SafeTimerBase(ILogger logger, Func<object, Task> asynTaskCallback, object state)
{
Init(logger, asynTaskCallback, null, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(ILogger logger, Func<object, Task> asynTaskCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(logger, asynTaskCallback, null, state, dueTime, period);
Start(dueTime, period);
}
internal SafeTimerBase(ILogger logger, TimerCallback syncCallback, object state)
{
Init(logger, null, syncCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(ILogger logger, TimerCallback syncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(logger, null, syncCallback, state, dueTime, period);
Start(dueTime, period);
}
public void Start(TimeSpan due, TimeSpan period)
{
if (timerStarted) throw new InvalidOperationException(String.Format("Calling start on timer {0} is not allowed, since it was already created in a started mode with specified due.", GetFullName()));
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
timerFrequency = period;
dueTime = due;
timerStarted = true;
previousTickTime = DateTime.UtcNow;
timer.Change(due, Constants.INFINITE_TIMESPAN);
}
private void Init(ILogger logger, Func<object, Task> asynCallback, TimerCallback synCallback, object state, TimeSpan due, TimeSpan period)
{
if (synCallback == null && asynCallback == null) throw new ArgumentNullException("synCallback", "Cannot use null for both sync and asyncTask timer callbacks.");
int numNonNulls = (asynCallback != null ? 1 : 0) + (synCallback != null ? 1 : 0);
if (numNonNulls > 1) throw new ArgumentNullException("synCallback", "Cannot define more than one timer callbacks. Pick one.");
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
this.asynTaskCallback = asynCallback;
syncCallbackFunc = synCallback;
timerFrequency = period;
this.dueTime = due;
totalNumTicks = 0;
this.logger = logger;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerChanging, "Creating timer {0} with dueTime={1} period={2}", GetFullName(), due, period);
timer = new Timer(HandleTimerCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects.
// Dispose() may be called multiple times
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DisposeTimer();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void DisposeTimer()
{
if (timer != null)
{
try
{
var t = timer;
timer = null;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerDisposing, "Disposing timer {0}", GetFullName());
t.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Ignored error disposing timer {0}", GetFullName()), exc);
}
}
}
private string GetFullName()
{
// the type information is really useless and just too long.
if (syncCallbackFunc != null)
return syncTimerName;
if (asynTaskCallback != null)
return asyncTimerName;
throw new InvalidOperationException("invalid SafeTimerBase state");
}
public bool CheckTimerFreeze(DateTime lastCheckTime, Func<string> callerName)
{
return CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, () => String.Format("{0}.{1}", GetFullName(), callerName()), ErrorCode.Timer_SafeTimerIsNotTicking, true);
}
public static bool CheckTimerDelay(DateTime previousTickTime, int totalNumTicks,
TimeSpan dueTime, TimeSpan timerFrequency, ILogger logger, Func<string> getName, ErrorCode errorCode, bool freezeCheck)
{
TimeSpan timeSinceLastTick = DateTime.UtcNow - previousTickTime;
TimeSpan exceptedTimeToNexTick = totalNumTicks == 0 ? dueTime : timerFrequency;
TimeSpan exceptedTimeWithSlack;
if (exceptedTimeToNexTick >= TimeSpan.FromSeconds(6))
{
exceptedTimeWithSlack = exceptedTimeToNexTick + TimeSpan.FromSeconds(3);
}
else
{
exceptedTimeWithSlack = exceptedTimeToNexTick.Multiply(1.5);
}
if (timeSinceLastTick <= exceptedTimeWithSlack) return true;
// did not tick in the last period.
var errMsg = String.Format("{0}{1} did not fire on time. Last fired at {2}, {3} since previous fire, should have fired after {4}.",
freezeCheck ? "Watchdog Freeze Alert: " : "-", // 0
getName == null ? "" : getName(), // 1
LogFormatter.PrintDate(previousTickTime), // 2
timeSinceLastTick, // 3
exceptedTimeToNexTick); // 4
if(freezeCheck)
{
logger.Error(errorCode, errMsg);
}else
{
logger.Warn(errorCode, errMsg);
}
return false;
}
/// <summary>
/// Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
/// </summary>
/// <param name="newDueTime">A TimeSpan representing the amount of time to delay before invoking the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.</param>
/// <param name="period">The time interval between invocations of the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to disable periodic signaling.</param>
/// <returns><c>true</c> if the timer was successfully updated; otherwise, <c>false</c>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool Change(TimeSpan newDueTime, TimeSpan period)
{
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, string.Format("Cannot use TimeSpan.Zero for timer {0} period", GetFullName()));
if (timer == null) return false;
timerFrequency = period;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerChanging, "Changing timer {0} to dueTime={1} period={2}", GetFullName(), newDueTime, period);
try
{
// Queue first new timer tick
return timer.Change(newDueTime, Constants.INFINITE_TIMESPAN);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerChangeError,
string.Format("Error changing timer period - timer {0} not changed", GetFullName()), exc);
return false;
}
}
private void HandleTimerCallback(object state)
{
if (timer == null) return;
if (asynTaskCallback != null)
{
HandleAsyncTaskTimerCallback(state);
}
else
{
HandleSyncTimerCallback(state);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void HandleSyncTimerCallback(object state)
{
try
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerBeforeCallback, "About to make sync timer callback for timer {0}", GetFullName());
syncCallbackFunc(state);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed sync timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during sync timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
private async void HandleAsyncTaskTimerCallback(object state)
{
if (timer == null) return;
// There is a subtle race/issue here w.r.t unobserved promises.
// It may happen than the asyncCallbackFunc will resolve some promises on which the higher level application code is depends upon
// and this promise's await or CW will fire before the below code (after await or Finally) even runs.
// In the unit test case this may lead to the situation where unit test has finished, but p1 or p2 or p3 have not been observed yet.
// To properly fix this we may use a mutex/monitor to delay execution of asyncCallbackFunc until all CWs and Finally in the code below were scheduled
// (not until CW lambda was run, but just until CW function itself executed).
// This however will relay on scheduler executing these in separate threads to prevent deadlock, so needs to be done carefully.
// In particular, need to make sure we execute asyncCallbackFunc in another thread (so use StartNew instead of ExecuteWithSafeTryCatch).
try
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerBeforeCallback, "About to make async task timer callback for timer {0}", GetFullName());
await asynTaskCallback(state);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed async task timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during async task timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void QueueNextTimerTick()
{
try
{
if (timer == null) return;
totalNumTicks++;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerChanging, "About to QueueNextTimerTick for timer {0}", GetFullName());
if (timerFrequency == Constants.INFINITE_TIMESPAN)
{
//timer.Change(Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
DisposeTimer();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerStopped, "Timer {0} is now stopped and disposed", GetFullName());
}
else
{
timer.Change(timerFrequency, Constants.INFINITE_TIMESPAN);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerNextTick, "Queued next tick for timer {0} in {1}", GetFullName(), timerFrequency);
}
}
catch (ObjectDisposedException ode)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Timer {0} already disposed - will not queue next timer tick", GetFullName()), ode);
}
catch (Exception exc)
{
logger.Error(ErrorCode.TimerQueueTickError,
string.Format("Error queueing next timer tick - WARNING: timer {0} is now stopped", GetFullName()), exc);
}
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Text;
namespace TestFu.Data.Populators
{
using TestFu.Data.Generators;
using TestFu.Data.Collections;
/// <summary>
/// An smart random <see cref="DataRow"/> generator.
/// </summary>
/// <include
/// file='Data/TestFu.Data.Doc.xml'
/// path='//example[contains(descendant-or-self::*,"TablePopulator")]'
/// />
public class TablePopulator : ITablePopulator
{
private static Random rnd = new Random((int)DateTime.Now.Ticks);
private IDatabasePopulator database=null;
private DataTable table=null;
private IUniqueValidatorCollection uniques=null;
private IForeignKeyProviderCollection foreignKeys=null;
private IDataGeneratorCollection dataGenerators=new DataGeneratorCollection();
private ICheckValidator checkValidator = null;
private DataRow row=null;
private int maxGenerationCount=100;
private int generationCount=0;
public TablePopulator(IDatabasePopulator database,DataTable table)
{
if (database==null)
throw new ArgumentNullException("database");
if (table==null)
throw new ArgumentNullException("table");
this.database = database;
this.table = table;
this.uniques=new UniqueValidatorCollection(this);
this.foreignKeys=new ForeignKeyProviderCollection(this);
this.PopulateDataGenerators();
this.PopulateUniques();
}
#region ITablePopulator
public IDatabasePopulator Database
{
get
{
return this.database;
}
}
public DataTable Table
{
get
{
return this.table;
}
}
public IUniqueValidatorCollection Uniques
{
get
{
return this.uniques;
}
}
public IForeignKeyProviderCollection ForeignKeys
{
get
{
return this.foreignKeys;
}
}
public IDataGeneratorCollection Columns
{
get
{
return this.dataGenerators;
}
}
public ICheckValidator CheckValidator
{
get
{
return this.checkValidator;
}
set
{
this.checkValidator = value;
}
}
public DataRow Generate()
{
// create a new row
this.CreateEmptyRow();
this.generationCount=0;
while(this.generationCount<this.maxGenerationCount)
{
// count the number of generations
this.generationCount++;
// generate data randomly
this.GenerateData();
// first generate/fetch valid foreign keys
this.GenerateForeignKeys();
// enfore check constraint
// otherwize regenerate
if (!this.EnforceCheck())
break;
// verify unique key constraints
// if not valid, try again
if (this.AreUniqueKeysValid(false))
break;
}
if (this.generationCount==this.maxGenerationCount)
throw new Exception("Could not generate valid row");
// add key to uniques
foreach(IUniqueValidator unique in this.Uniques)
unique.AddKey(this.row);
return this.row;
}
public virtual void ChangeRowValues(DataRow row)
{
if (row == null)
throw new ArgumentNullException("row");
this.ChangeRowValues(row, false);
}
public virtual void ChangeRowValues(DataRow row, bool updateForeignKeys)
{
if (row == null)
throw new ArgumentNullException("row");
this.row = row;
this.generationCount = 0;
while (this.generationCount < this.maxGenerationCount)
{
// count the number of generations
this.generationCount++;
// generate data randomly
this.GenerateDataForNonKeyFields(updateForeignKeys);
if (updateForeignKeys)
this.GenerateForeignKeys();
// enfore check constraint
// otherwize regenerate
if (!this.EnforceCheck())
break;
// verify unique key constraints
// if not valid, try again
if (this.AreUniqueKeysValid(true))
break;
}
if (this.generationCount == this.maxGenerationCount)
throw new Exception("Could not update valid row");
}
protected virtual void CreateEmptyRow()
{
this.row = this.table.NewRow();
}
protected virtual void GenerateData()
{
foreach(IDataGenerator dataGenerator in this.Columns)
{
dataGenerator.GenerateData(this.row);
}
}
protected virtual void GenerateDataForNonKeyFields(bool updateForeignKeys)
{
foreach (IDataGenerator dg in this.Columns)
{
// check it is not a pk
if (this.IsInPrimaryKey(dg.Column))
continue;
// if notupdate foreign keys, check it is not
if (!updateForeignKeys)
{
if (this.IsInForeignKey(dg.Column))
continue;
}
// generate
dg.GenerateData(this.row);
}
}
protected virtual bool IsInPrimaryKey(DataColumn column)
{
foreach (DataColumn pkColumn in this.Table.PrimaryKey)
if (column == pkColumn)
return true;
return false;
}
protected virtual bool IsInForeignKey(DataColumn column)
{
foreach (DataRelation relation in this.Table.ParentRelations)
{
foreach (DataColumn fkColumn in relation.ChildColumns)
if (fkColumn == column)
return true;
}
return false;
}
protected virtual void GenerateForeignKeys()
{
foreach (IForeignKeyProvider foreignKey in this.ForeignKeys)
{
foreignKey.Provide(this.Row);
}
}
protected virtual bool EnforceCheck()
{
if (this.checkValidator == null)
return true;
return this.checkValidator.Enforce(this.Row);
}
protected virtual bool AreUniqueKeysValid(bool ignorePrimaryKey)
{
foreach(IUniqueValidator uniqueKey in this.Uniques)
{
// if the unique key is autoincrement, ignore it
if (uniqueKey.IsIdentity)
continue;
// if we want to ignore primary keys for an update
if (ignorePrimaryKey && uniqueKey.Unique.IsPrimaryKey)
continue;
if (uniqueKey.Contains(this.row))
return false;
}
return true;
}
public DataRow Row
{
get
{
return this.row;
}
}
#endregion
#region Properties
public int MaxGenerationCount
{
get
{
return this.maxGenerationCount;
}
set
{
this.maxGenerationCount=value;
}
}
public int GenerationCount
{
get
{
return this.generationCount;
}
}
#endregion
#region Population
protected virtual void PopulateDataGenerators()
{
foreach(DataColumn column in this.Table.Columns)
{
IDataGenerator gen = DataGeneratorConverter.FromColumn(column);
this.dataGenerators.Add(gen);
}
}
protected virtual void PopulateUniques()
{
foreach(Constraint constraint in this.Table.Constraints)
{
UniqueConstraint unique = constraint as UniqueConstraint;
if (unique==null)
continue;
MethodUniqueValidator muv = this.CreateMethodUniqueValidator(unique);
if (muv != null)
{
this.uniques.Add(muv);
continue;
}
IUniqueValidator uv =new DictionaryUniqueValidator(this,unique);
this.uniques.Add(uv);
}
}
internal void PopulateForeignKeys()
{
foreach(Constraint constraint in this.Table.Constraints)
{
ForeignKeyConstraint fk = constraint as ForeignKeyConstraint;
if (fk==null)
continue;
ITablePopulator foreignTable = null;
if (fk.RelatedTable == this.Table)
foreignTable = this;
else
foreignTable = this.database.Tables[fk.RelatedTable];
// create and add
IForeignKeyProvider fkp = new ForeignKeyProvider(foreignTable,fk);
this.foreignKeys.Add(fkp);
}
}
protected MethodUniqueValidator CreateMethodUniqueValidator(UniqueConstraint unique)
{
StringBuilder methodName = new StringBuilder("FindBy");
foreach (DataColumn col in unique.Columns)
methodName.Append(col.ColumnName);
MethodInfo method =this.Table.GetType().GetMethod(methodName.ToString());
if (method == null)
return null;
MethodUniqueValidator validator = new MethodUniqueValidator(this, unique, method);
return validator;
}
#endregion
public override string ToString()
{
return this.Table.TableName;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="DirectoryHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the DirectoryHelper class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Runtime.InteropServices;
using Microsoft.Exchange.WebServices.Data;
/// <summary>
/// Represents a set of helper methods for using Active Directory services.
/// </summary>
internal class DirectoryHelper
{
#region Static members
/// <summary>
/// Maximum number of SCP hops in an SCP host lookup call.
/// </summary>
private const int AutodiscoverMaxScpHops = 10;
/// <summary>
/// GUID for SCP URL keyword
/// </summary>
private const string ScpUrlGuidString = @"77378F46-2C66-4aa9-A6A6-3E7A48B19596";
/// <summary>
/// GUID for SCP pointer keyword
/// </summary>
private const string ScpPtrGuidString = @"67661d7F-8FC4-4fa7-BFAC-E1D7794C1F68";
/// <summary>
/// Filter string to find SCP Ptrs and Urls.
/// </summary>
private const string ScpFilterString = "(&(objectClass=serviceConnectionPoint)(|(keywords=" + ScpPtrGuidString + ")(keywords=" + ScpUrlGuidString + ")))";
#endregion
#region Private members
private ExchangeServiceBase service;
#endregion
/// <summary>
/// Gets the SCP URL list for domain.
/// </summary>
/// <param name="domainName">Name of the domain.</param>
/// <returns>List of Autodiscover URLs</returns>
public List<string> GetAutodiscoverScpUrlsForDomain(string domainName)
{
int maxHops = AutodiscoverMaxScpHops;
List<string> scpUrlList;
try
{
scpUrlList = this.GetScpUrlList(domainName, null, ref maxHops);
}
catch (InvalidOperationException e)
{
this.TraceMessage(
string.Format("LDAP call failed, exception: {0}", e.ToString()));
scpUrlList = new List<string>();
}
catch (NotSupportedException e)
{
this.TraceMessage(
string.Format("LDAP call failed, exception: {0}", e.ToString()));
scpUrlList = new List<string>();
}
catch (COMException e)
{
this.TraceMessage(
string.Format("LDAP call failed, exception: {0}", e.ToString()));
scpUrlList = new List<string>();
}
return scpUrlList;
}
/// <summary>
/// Search Active Directory for any related SCP URLs for a given domain name.
/// </summary>
/// <param name="domainName">Domain name to search for SCP information</param>
/// <param name="ldapPath">LDAP path to start the search</param>
/// <param name="maxHops">The number of remaining allowed hops</param>
private List<string> GetScpUrlList(
string domainName,
string ldapPath,
ref int maxHops)
{
if (maxHops <= 0)
{
throw new ServiceLocalException(Strings.MaxScpHopsExceeded);
}
maxHops--;
this.TraceMessage(
string.Format("Starting SCP lookup for domainName='{0}', root path='{1}'", domainName, ldapPath));
string scpUrl = null;
string fallBackLdapPath = null;
string rootDsePath = null;
string configPath = null;
// The list of SCP URLs.
List<string> scpUrlList = new List<string>();
// Get the LDAP root path.
rootDsePath = (ldapPath == null) ? "LDAP://RootDSE" : ldapPath + "/RootDSE";
// Get the root directory entry.
using (DirectoryEntry rootDseEntry = new DirectoryEntry(rootDsePath))
{
// Get the configuration path.
configPath = rootDseEntry.Properties["configurationNamingContext"].Value as string;
}
// The container for SCP pointers and URLs objects from Active Directory
SearchResultCollection scpDirEntries = null;
try
{
// Get the configuration entry path.
using (DirectoryEntry configEntry = new DirectoryEntry("LDAP://" + configPath))
{
// Use the configuration entry path to create a query.
using (DirectorySearcher configSearcher = new DirectorySearcher(configEntry))
{
// Filter for Autodiscover SCP URLs and SCP pointers.
configSearcher.Filter = ScpFilterString;
// Identify properties to retrieve using the the query.
configSearcher.PropertiesToLoad.Add("keywords");
configSearcher.PropertiesToLoad.Add("serviceBindingInformation");
this.TraceMessage(
string.Format("Searching for SCP entries in {0}", configEntry.Path));
// Query Active Directory for SCP entries.
scpDirEntries = configSearcher.FindAll();
}
}
// Identify the domain to match.
string domainMatch = "Domain=" + domainName;
// Contains a pointer to the LDAP path of a SCP object.
string scpPtrLdapPath;
this.TraceMessage(
string.Format("Scanning for SCP pointers {0}", domainMatch));
foreach (SearchResult scpDirEntry in scpDirEntries)
{
ResultPropertyValueCollection entryKeywords = scpDirEntry.Properties["keywords"];
// Identify SCP pointers.
if (entryKeywords.CaseInsensitiveContains(ScpPtrGuidString))
{
// Get the LDAP path to SCP pointer.
scpPtrLdapPath = scpDirEntry.Properties["serviceBindingInformation"][0] as string;
// If the SCP pointer matches the user's domain, then restart search from that point.
if (entryKeywords.CaseInsensitiveContains(domainMatch))
{
// Stop the current search, start another from a new location.
this.TraceMessage(
string.Format(
"SCP pointer for '{0}' is found in '{1}', restarting seach in '{2}'",
domainMatch,
scpDirEntry.Path,
scpPtrLdapPath));
return this.GetScpUrlList(domainName, scpPtrLdapPath, ref maxHops);
}
else
{
// Save the first SCP pointer ldapPath for a later call if a SCP URL is not found.
// Directory entries with a SCP pointer should have only one keyword=ScpPtrGuidString.
if ((entryKeywords.Count == 1) && string.IsNullOrEmpty(fallBackLdapPath))
{
fallBackLdapPath = scpPtrLdapPath;
this.TraceMessage(
string.Format(
"Fallback SCP pointer='{0}' for '{1}' is found in '{2}' and saved.",
fallBackLdapPath,
domainMatch,
scpDirEntry.Path));
}
}
}
}
this.TraceMessage(
string.Format("No SCP pointers found for '{0}' in configPath='{1}'", domainMatch, configPath));
// Get the computer's current site.
string computerSiteName = this.GetSiteName();
if (!string.IsNullOrEmpty(computerSiteName))
{
// Search for SCP entries.
string sitePrefix = "Site=";
string siteMatch = sitePrefix + computerSiteName;
List<string> scpListNoSiteMatch = new List<string>();
this.TraceMessage(
string.Format("Scanning for SCP urls for the current computer {0}", siteMatch));
foreach (SearchResult scpDirEntry in scpDirEntries)
{
ResultPropertyValueCollection entryKeywords = scpDirEntry.Properties["keywords"];
// Identify SCP URLs.
if (entryKeywords.CaseInsensitiveContains(ScpUrlGuidString) && scpDirEntry.Properties["serviceBindingInformation"].Count > 0)
{
// Get the SCP URL.
scpUrl = scpDirEntry.Properties["serviceBindingInformation"][0] as string;
// If the SCP URL matches the exact ComputerSiteName.
if (entryKeywords.CaseInsensitiveContains(siteMatch))
{
// Priority 1 SCP URL. Add SCP URL to the list if it's not already there.
if (!scpUrlList.CaseInsensitiveContains(scpUrl))
{
this.TraceMessage(
string.Format(
"Adding (prio 1) '{0}' for the '{1}' from '{2}' to the top of the list (exact match)",
scpUrl,
siteMatch,
scpDirEntry.Path));
scpUrlList.Add(scpUrl);
}
}
// No match between the SCP URL and the ComputerSiteName
else
{
bool hasSiteKeyword = false;
// Check if SCP URL entry has any keyword starting with "Site="
foreach (string keyword in entryKeywords)
{
hasSiteKeyword |= keyword.StartsWith(sitePrefix, StringComparison.OrdinalIgnoreCase);
}
// Add SCP URL to the scpListNoSiteMatch list if it's not already there.
if (!scpListNoSiteMatch.CaseInsensitiveContains(scpUrl))
{
// Priority 2 SCP URL. SCP entry doesn't have any "Site=<otherSite>" keywords, insert at the top of list.
if (!hasSiteKeyword)
{
this.TraceMessage(
string.Format(
"Adding (prio 2) '{0}' from '{1}' to the middle of the list (wildcard)",
scpUrl,
scpDirEntry.Path));
scpListNoSiteMatch.Insert(0, scpUrl);
}
// Priority 3 SCP URL. SCP entry has at least one "Site=<otherSite>" keyword, add to the end of list.
else
{
this.TraceMessage(
string.Format(
"Adding (prio 3) '{0}' from '{1}' to the end of the list (site mismatch)",
scpUrl,
scpDirEntry.Path));
scpListNoSiteMatch.Add(scpUrl);
}
}
}
}
}
// Append SCP URLs to the list. List contains:
// Priority 1 URLs -- URLs with an exact match, "Site=<machineSite>"
// Priority 2 URLs -- URLs without a match, no any "Site=<anySite>" in the entry
// Priority 3 URLs -- URLs without a match, "Site=<nonMachineSite>"
if (scpListNoSiteMatch.Count > 0)
{
foreach (string url in scpListNoSiteMatch)
{
if (!scpUrlList.CaseInsensitiveContains(url))
{
scpUrlList.Add(url);
}
}
}
}
}
finally
{
if (scpDirEntries != null)
{
scpDirEntries.Dispose();
}
}
// If no entries found, try fallBackLdapPath if it's non-empty.
if (scpUrlList.Count == 0)
{
if (!string.IsNullOrEmpty(fallBackLdapPath))
{
this.TraceMessage(
string.Format(
"Restarting search for domain '{0}' in SCP fallback pointer '{1}'",
domainName,
fallBackLdapPath));
return this.GetScpUrlList(domainName, fallBackLdapPath, ref maxHops);
}
}
// Return the list with 0 or more SCP URLs.
return scpUrlList;
}
/// <summary>
/// Get the local site name.
/// </summary>
/// <returns>Name of the local site.</returns>
private string GetSiteName()
{
try
{
using (ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite())
{
return site.Name;
}
}
catch (ActiveDirectoryObjectNotFoundException) // object not found in directory store
{
return null;
}
catch (ActiveDirectoryOperationException) // underlying directory operation failed
{
return null;
}
catch (ActiveDirectoryServerDownException) // server unavailable
{
return null;
}
}
/// <summary>
/// Traces message.
/// </summary>
/// <param name="message">The message.</param>
private void TraceMessage(string message)
{
this.Service.TraceMessage(TraceFlags.AutodiscoverConfiguration, message);
}
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryHelper"/> class.
/// </summary>
/// <param name="service">The service.</param>
public DirectoryHelper(ExchangeServiceBase service)
{
this.service = service;
}
#endregion
#region Properties
internal ExchangeServiceBase Service
{
get { return this.service; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests
{
public class DelegateTests
{
private static readonly string _expectedResponseString = "Hello from delegatee";
[ConditionalFact]
[DelegateSupportedCondition(true)]
public async Task DelegateRequestTest()
{
var queueName = Guid.NewGuid().ToString();
using var receiver = Utilities.CreateHttpServer(out var receiverAddress, async httpContext =>
{
await httpContext.Response.WriteAsync(_expectedResponseString);
},
options =>
{
options.RequestQueueName = queueName;
});
DelegationRule destination = default;
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
{
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
delegateFeature.DelegateRequest(destination);
return Task.CompletedTask;
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
var responseString = await SendRequestAsync(delegatorAddress);
Assert.Equal(_expectedResponseString, responseString);
destination?.Dispose();
}
[ConditionalFact]
[DelegateSupportedCondition(true)]
public async Task DelegateAfterWriteToResponseBodyShouldThrowTest()
{
var queueName = Guid.NewGuid().ToString();
using var receiver = Utilities.CreateHttpServer(out var receiverAddress, httpContext =>
{
httpContext.Response.StatusCode = StatusCodes.Status418ImATeapot;
return Task.CompletedTask;
},
options =>
{
options.RequestQueueName = queueName;
});
DelegationRule destination = default;
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, async httpContext =>
{
await httpContext.Response.WriteAsync(_expectedResponseString);
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
Assert.False(delegateFeature.CanDelegate);
Assert.Throws<InvalidOperationException>(() => delegateFeature.DelegateRequest(destination));
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
var responseString = await SendRequestAsync(delegatorAddress);
Assert.Equal(_expectedResponseString, responseString);
destination?.Dispose();
}
[ConditionalFact]
[DelegateSupportedCondition(true)]
public async Task WriteToBodyAfterDelegateShouldNoOp()
{
var queueName = Guid.NewGuid().ToString();
using var receiver = Utilities.CreateHttpServer(out var receiverAddress, async httpContext =>
{
await httpContext.Response.WriteAsync(_expectedResponseString);
},
options =>
{
options.RequestQueueName = queueName;
});
DelegationRule destination = default;
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
{
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
delegateFeature.DelegateRequest(destination);
Assert.False(delegateFeature.CanDelegate);
httpContext.Response.WriteAsync(_expectedResponseString);
return Task.CompletedTask;
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
var responseString = await SendRequestAsync(delegatorAddress);
Assert.Equal(_expectedResponseString, responseString);
destination?.Dispose();
}
[ConditionalFact]
[DelegateSupportedCondition(true)]
public async Task DelegateAfterRequestBodyReadShouldThrow()
{
var queueName = Guid.NewGuid().ToString();
using var receiver = Utilities.CreateHttpServer(out var receiverAddress, httpContext =>
{
httpContext.Response.StatusCode = StatusCodes.Status418ImATeapot;
return Task.CompletedTask;
},
options =>
{
options.RequestQueueName = queueName;
});
DelegationRule destination = default;
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, async httpContext =>
{
var memoryStream = new MemoryStream();
await httpContext.Request.Body.CopyToAsync(memoryStream);
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
Assert.Throws<InvalidOperationException>(() => delegateFeature.DelegateRequest(destination));
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
_ = await SendRequestWithBodyAsync(delegatorAddress);
destination?.Dispose();
}
[ConditionalFact]
[DelegateSupportedCondition(false)]
public async Task DelegationFeaturesAreNull()
{
// Testing the DelegateSupportedCondition
Assert.True(Environment.OSVersion.Version < new Version(10, 0, 22000), "This should be supported on Win 11.");
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
{
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
Assert.Null(delegateFeature);
return Task.CompletedTask;
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
Assert.Null(delegationProperty);
_ = await SendRequestAsync(delegatorAddress);
}
[ConditionalFact]
[DelegateSupportedCondition(true)]
public async Task UpdateDelegationRuleTest()
{
var queueName = Guid.NewGuid().ToString();
using var receiver = Utilities.CreateHttpServer(out var receiverAddress, async httpContext =>
{
await httpContext.Response.WriteAsync(_expectedResponseString);
},
options =>
{
options.RequestQueueName = queueName;
});
DelegationRule destination = default;
using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
{
var delegateFeature = httpContext.Features.Get<IHttpSysRequestDelegationFeature>();
delegateFeature.DelegateRequest(destination);
return Task.CompletedTask;
});
var delegationProperty = delegator.Features.Get<IServerDelegationFeature>();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
// Send a request to ensure the rule is fully active
var responseString = await SendRequestAsync(delegatorAddress);
destination?.Dispose();
destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress);
responseString = await SendRequestAsync(delegatorAddress);
Assert.Equal(_expectedResponseString, responseString);
destination?.Dispose();
}
private async Task<string> SendRequestAsync(string uri)
{
using var client = new HttpClient();
return await client.GetStringAsync(uri);
}
private async Task<string> SendRequestWithBodyAsync(string uri)
{
using var client = new HttpClient();
var content = new StringContent("Sample request body");
var response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
| |
using System;
using System.Linq;
using OfficeDevPnP.Core;
namespace Microsoft.SharePoint.Client
{
/// <summary>
/// Enables: Ratings / Likes functionality on list in publishing web.
/// </summary>
public static partial class ListRatingExtensions
{
/// TODO: Replace Logging throughout
#region Rating Field
private static readonly Guid RatingsFieldGuid_AverageRating = new Guid("5a14d1ab-1513-48c7-97b3-657a5ba6c742");
private static readonly Guid RatingsFieldGuid_RatingCount = new Guid("b1996002-9167-45e5-a4df-b2c41c6723c7");
private static readonly Guid RatingsFieldGuid_RatedBy = new Guid("4D64B067-08C3-43DC-A87B-8B8E01673313");
private static readonly Guid RatingsFieldGuid_Ratings = new Guid("434F51FB-FFD2-4A0E-A03B-CA3131AC67BA");
private static readonly Guid LikeFieldGuid_LikedBy = new Guid("2cdcd5eb-846d-4f4d-9aaf-73e8e73c7312");
private static readonly Guid LikeFieldGuid_LikeCount = new Guid("6e4d832b-f610-41a8-b3e0-239608efda41");
private static List _library;
#endregion
/// <summary>
/// Enable Social Settings Likes/Ratings on list.
/// Note: 1. Requires Publishing feature enabled on the web.
/// 2. Defaults enable Ratings Experience on the List
/// 3. When experience set to None, fields are not removed from the list since CSOM does not support removing hidden fields
/// </summary>
/// <param name="list">Current List</param>
/// <param name="experience">Likes/Ratings</param>
public static void SetRating(this List list, VotingExperience experience)
{
/* Validate if current web is publishing web
* Add property to RootFolder of List/Library : key: Ratings_VotingExperience value:Likes
* Add rating fields
* Add fields to default view
* */
_library = list;
// only process publishing web
if (!list.ParentWeb.IsPublishingWeb())
{
////_logger.WriteWarning("Is publishing site : No");
}
// Add to property Root Folder of Pages Library
SetProperty(experience);
if (experience == VotingExperience.None)
{
RemoveViewFields();
}
else
{
AddListFields();
// remove already existing fields from the default view to prevent duplicates
RemoveViewFields();
AddViewFields(experience);
}
//_logger.WriteSuccess(string.Format("Enabled {0} on list/library {1}", experience, _library.Title));
}
/// <summary>
/// Removes the view fields associated with any rating type
/// </summary>
private static void RemoveViewFields()
{
_library.Context.Load(_library.DefaultView, p => p.ViewFields);
_library.Context.ExecuteQueryRetry();
var defaultView = _library.DefaultView;
if (defaultView.ViewFields.Contains("LikesCount"))
defaultView.ViewFields.Remove("LikesCount");
if (defaultView.ViewFields.Contains("AverageRating"))
defaultView.ViewFields.Remove("AverageRating");
defaultView.Update();
_library.Context.ExecuteQueryRetry();
}
/// <summary>
/// Add Ratings/Likes related fields to List from current Web
/// </summary>
private static void AddListFields()
{
EnsureField(_library, RatingsFieldGuid_RatingCount);
EnsureField(_library, RatingsFieldGuid_RatedBy);
EnsureField(_library, RatingsFieldGuid_Ratings);
EnsureField(_library, RatingsFieldGuid_AverageRating);
EnsureField(_library, LikeFieldGuid_LikedBy);
EnsureField(_library, LikeFieldGuid_LikeCount);
_library.Update();
_library.Context.ExecuteQueryRetry();
}
/// <summary>
/// Add/Remove Ratings/Likes field in default view depending on exerpeince selected
/// </summary>
/// <param name="experience"></param>
private static void AddViewFields(VotingExperience experience)
{
// Add LikesCount and LikeBy (Explicit) to view fields
_library.Context.Load(_library.DefaultView, p => p.ViewFields);
_library.Context.ExecuteQueryRetry();
var defaultView = _library.DefaultView;
switch (experience)
{
case VotingExperience.Ratings:
// Remove Likes Fields
if (defaultView.ViewFields.Contains("LikesCount"))
defaultView.ViewFields.Remove("LikesCount");
defaultView.ViewFields.Add("AverageRating");
// Add Ratings related field
break;
case VotingExperience.Likes:
// Remove Ratings Fields
// Add Likes related field
if (defaultView.ViewFields.Contains("AverageRating"))
defaultView.ViewFields.Remove("AverageRating");
defaultView.ViewFields.Add("LikesCount");
break;
default:
throw new ArgumentOutOfRangeException(nameof(experience));
}
defaultView.Update();
_library.Context.ExecuteQueryRetry();
//_logger.WriteSuccess("Ensured view-field.");
}
/// <summary>
/// Removes a field from a list
/// </summary>
/// <param name="list"></param>
/// <param name="fieldId"></param>
private static void RemoveField(List list, Guid fieldId)
{
try
{
var listFields = list.Fields;
var field = listFields.GetById(fieldId);
field.DeleteObject();
_library.Context.ExecuteQueryRetry();
}
catch (ArgumentException)
{
// Field does not exist
}
}
/// <summary>
/// Check for Ratings/Likes field and add to ListField if doesn't exists.
/// </summary>
/// <param name="list">List</param>
/// <param name="fieldId">Field Id</param>
/// <returns></returns>
private static void EnsureField(List list, Guid fieldId)
{
FieldCollection fields = list.Fields;
FieldCollection availableFields = list.ParentWeb.AvailableFields;
Field field = availableFields.GetById(fieldId);
_library.Context.Load(fields);
_library.Context.Load(field, p => p.SchemaXmlWithResourceTokens, p => p.Id, p => p.InternalName, p => p.StaticName);
_library.Context.ExecuteQueryRetry();
if (!fields.Any(p => p.Id == fieldId))
{
fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, false, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes);
}
}
/// <summary>
/// Add required key/value settings on List Root-Folder
/// </summary>
/// <param name="experience"></param>
private static void SetProperty(VotingExperience experience)
{
_library.Context.Load(_library.RootFolder, p => p.Properties);
_library.Context.ExecuteQueryRetry();
if (experience != VotingExperience.None)
{
_library.RootFolder.Properties["Ratings_VotingExperience"] = experience.ToString();
}
else
{
_library.RootFolder.Properties["Ratings_VotingExperience"] = string.Empty;
}
_library.RootFolder.Update();
_library.Context.ExecuteQueryRetry();
//_logger.WriteSuccess(string.Format("Ensured {0} Property.", experience));
}
}
}
| |
using Signum.Entities.Basics;
using Signum.Entities.Isolation;
using Signum.Utilities.Reflection;
using Signum.Engine.Processes;
using Signum.Entities.Processes;
namespace Signum.Engine.Isolation;
public static class IsolationLogic
{
public static bool IsStarted;
public static ResetLazy<List<Lite<IsolationEntity>>> Isolations = null!;
internal static Dictionary<Type, IsolationStrategy> strategies = new Dictionary<Type, IsolationStrategy>();
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<IsolationEntity>()
.WithSave(IsolationOperation.Save)
.WithQuery(() => iso => new
{
Entity = iso,
iso.Id,
iso.Name
});
Schema.Current.AttachToUniqueFilter += entity =>
{
var type = entity.GetType();
var hasIsolationMixin = MixinDeclarations.IsDeclared(type, typeof(IsolationMixin));
return hasIsolationMixin == false ? null :
e => e.Mixin<IsolationMixin>().Isolation.Is(entity.Mixin<IsolationMixin>().Isolation);
};
sb.Schema.EntityEventsGlobal.PreSaving += EntityEventsGlobal_PreSaving;
sb.Schema.SchemaCompleted += AssertIsolationStrategies;
OperationLogic.SurroundOperation += OperationLogic_SurroundOperation;
Isolations = sb.GlobalLazy(() => Database.RetrieveAllLite<IsolationEntity>(),
new InvalidateWith(typeof(IsolationEntity)));
ProcessLogic.ApplySession += ProcessLogic_ApplySession;
Validator.OverridePropertyValidator((IsolationMixin m) => m.Isolation).StaticPropertyValidation += (mi, pi) =>
{
if (strategies.GetOrThrow(mi.MainEntity.GetType()) == IsolationStrategy.Isolated && mi.Isolation == null)
return ValidationMessage._0IsNotSet.NiceToString(pi.NiceName());
return null;
};
IsStarted = true;
}
}
static IDisposable? ProcessLogic_ApplySession(ProcessEntity process)
{
return IsolationEntity.Override(process.Data!.TryIsolation());
}
static IDisposable? OperationLogic_SurroundOperation(IOperation operation, OperationLogEntity log, Entity? entity, object?[]? args)
{
return IsolationEntity.Override(entity?.TryIsolation() ?? args.TryGetArgC<Lite<IsolationEntity>>());
}
static void EntityEventsGlobal_PreSaving(Entity ident, PreSavingContext ctx)
{
if (strategies.TryGet(ident.GetType(), IsolationStrategy.None) != IsolationStrategy.None && IsolationEntity.Current != null)
{
if (ident.Mixin<IsolationMixin>().Isolation == null)
{
ident.Mixin<IsolationMixin>().Isolation = IsolationEntity.Current;
ctx.InvalidateGraph();
}
else if (!ident.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current))
throw new ApplicationException(IsolationMessage.Entity0HasIsolation1ButCurrentIsolationIs2.NiceToString(ident, ident.Mixin<IsolationMixin>().Isolation, IsolationEntity.Current));
}
}
static void AssertIsolationStrategies()
{
var result = EnumerableExtensions.JoinStrict(
strategies.Keys,
Schema.Current.Tables.Keys.Where(a => !a.IsEnumEntityOrSymbol() && !typeof(SemiSymbol).IsAssignableFrom(a)),
a => a,
a => a,
(a, b) => 0);
var extra = result.Extra.OrderBy(a => a.Namespace).ThenBy(a => a.Name).ToString(t => " IsolationLogic.Register<{0}>(IsolationStrategy.XXX);".FormatWith(t.Name), "\r\n");
var lacking = result.Missing.GroupBy(a => a.Namespace).OrderBy(gr => gr.Key).ToString(gr => " //{0}\r\n".FormatWith(gr.Key) +
gr.ToString(t => " IsolationLogic.Register<{0}>(IsolationStrategy.XXX);".FormatWith(t.Name), "\r\n"), "\r\n\r\n");
if (extra.HasText() || lacking.HasText())
throw new InvalidOperationException("IsolationLogic's strategies are not synchronized with the Schema.\r\n" +
(extra.HasText() ? ("Remove something like:\r\n" + extra + "\r\n\r\n") : null) +
(lacking.HasText() ? ("Add something like:\r\n" + lacking + "\r\n\r\n") : null));
foreach (var item in strategies.Where(kvp => kvp.Value == IsolationStrategy.Isolated || kvp.Value == IsolationStrategy.Optional).Select(a => a.Key))
{
giRegisterFilterQuery.GetInvoker(item)();
}
Schema.Current.EntityEvents<IsolationEntity>().FilterQuery += () =>
{
if (IsolationEntity.Current == null || ExecutionMode.InGlobal)
return null;
return new FilterQueryResult<IsolationEntity>(
a => a.ToLite().Is(IsolationEntity.Current),
a => a.ToLite().Is(IsolationEntity.Current));
};
}
public static IsolationStrategy GetStrategy(Type type)
{
return strategies[type];
}
static readonly GenericInvoker<Action> giRegisterFilterQuery = new(() => Register_FilterQuery<Entity>());
static void Register_FilterQuery<T>() where T : Entity
{
Schema.Current.EntityEvents<T>().FilterQuery += () =>
{
if (ExecutionMode.InGlobal || IsolationEntity.Current == null)
return null;
return new FilterQueryResult<T>(
a => a.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current),
a => a.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current));
};
Schema.Current.EntityEvents<T>().PreUnsafeInsert += (IQueryable query, LambdaExpression constructor, IQueryable<T> entityQuery) =>
{
if (ExecutionMode.InGlobal || IsolationEntity.Current == null)
return constructor;
if (constructor.Body.Type == typeof(T))
{
var newBody = Expression.Call(
miSetMixin.MakeGenericMethod(typeof(T), typeof(IsolationMixin), typeof(Lite<IsolationEntity>)),
constructor.Body,
Expression.Quote(IsolationLambda),
Expression.Constant(IsolationEntity.Current));
return Expression.Lambda(newBody, constructor.Parameters);
}
return constructor; //MListTable
};
}
static MethodInfo miSetMixin = ReflectionTools.GetMethodInfo((Entity a) => a.SetMixin((IsolationMixin m) => m.Isolation, null)).GetGenericMethodDefinition();
static Expression<Func<IsolationMixin, Lite<IsolationEntity>?>> IsolationLambda = (IsolationMixin m) => m.Isolation;
public static void Register<T>(IsolationStrategy strategy) where T : Entity
{
strategies.Add(typeof(T), strategy);
if (strategy == IsolationStrategy.Isolated || strategy == IsolationStrategy.Optional)
MixinDeclarations.Register(typeof(T), typeof(IsolationMixin));
if (strategy == IsolationStrategy.Optional)
{
Schema.Current.Settings.FieldAttributes((T e) => e.Mixin<IsolationMixin>().Isolation).Remove<ForceNotNullableAttribute>(); //Remove non-null
}
}
public static IEnumerable<T> WhereCurrentIsolationInMemory<T>(this IEnumerable<T> collection) where T : Entity
{
var curr = IsolationEntity.Current;
if (curr == null || strategies[typeof(T)] == IsolationStrategy.None)
return collection;
return collection.Where(a => a.Isolation().Is(curr));
}
public static Lite<IsolationEntity>? GetOnlyIsolation(List<Lite<Entity>> selectedEntities)
{
return selectedEntities.GroupBy(a => a.EntityType)
.Select(gr => strategies[gr.Key] == IsolationStrategy.None ? null : giGetOnlyIsolation.GetInvoker(gr.Key)(gr))
.NotNull()
.Only();
}
static GenericInvoker<Func<IEnumerable<Lite<Entity>>, Lite<IsolationEntity>?>> giGetOnlyIsolation =
new(list => GetOnlyIsolation<Entity>(list));
public static Lite<IsolationEntity>? GetOnlyIsolation<T>(IEnumerable<Lite<Entity>> selectedEntities) where T : Entity
{
return selectedEntities.Cast<Lite<T>>().Chunk(100).Select(gr =>
Database.Query<T>().Where(e => gr.Contains(e.ToLite())).Select(e => e.Isolation()).Only()
).NotNull().Only();
}
public static Dictionary<Type, IsolationStrategy> GetIsolationStrategies()
{
return strategies.ToDictionary();
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.WebSitesExtensions;
using Microsoft.WindowsAzure.WebSitesExtensions.Models;
namespace Microsoft.WindowsAzure.WebSitesExtensions
{
/// <summary>
/// The websites extensions client manages the web sites deployments, web
/// jobs and other extensions.
/// </summary>
public static partial class DeploymentOperationsExtensions
{
/// <summary>
/// Gets a deployment for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <returns>
/// The deployment information operation response.
/// </returns>
public static DeploymentGetResponse Get(this IDeploymentOperations operations, string deploymentId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).GetAsync(deploymentId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a deployment for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <returns>
/// The deployment information operation response.
/// </returns>
public static Task<DeploymentGetResponse> GetAsync(this IDeploymentOperations operations, string deploymentId)
{
return operations.GetAsync(deploymentId, CancellationToken.None);
}
/// <summary>
/// Gets a deployment log for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <param name='deploymentLogId'>
/// Required. The deployment log identifier.
/// </param>
/// <returns>
/// The get log for a deployments operation response.
/// </returns>
public static DeploymentGetLogResponse GetLog(this IDeploymentOperations operations, string deploymentId, string deploymentLogId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).GetLogAsync(deploymentId, deploymentLogId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a deployment log for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <param name='deploymentLogId'>
/// Required. The deployment log identifier.
/// </param>
/// <returns>
/// The get log for a deployments operation response.
/// </returns>
public static Task<DeploymentGetLogResponse> GetLogAsync(this IDeploymentOperations operations, string deploymentId, string deploymentLogId)
{
return operations.GetLogAsync(deploymentId, deploymentLogId, CancellationToken.None);
}
/// <summary>
/// List the deployments for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The list of deployments operation response.
/// </returns>
public static DeploymentListResponse List(this IDeploymentOperations operations, DeploymentListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).ListAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List the deployments for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The list of deployments operation response.
/// </returns>
public static Task<DeploymentListResponse> ListAsync(this IDeploymentOperations operations, DeploymentListParameters parameters)
{
return operations.ListAsync(parameters, CancellationToken.None);
}
/// <summary>
/// List the logs for a deployment for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The list of deployments operation response.
/// </returns>
public static DeploymentListLogsResponse ListLogs(this IDeploymentOperations operations, string deploymentId, DeploymentListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).ListLogsAsync(deploymentId, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List the logs for a deployment for a website.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <param name='parameters'>
/// Optional. Additional parameters.
/// </param>
/// <returns>
/// The list of deployments operation response.
/// </returns>
public static Task<DeploymentListLogsResponse> ListLogsAsync(this IDeploymentOperations operations, string deploymentId, DeploymentListParameters parameters)
{
return operations.ListLogsAsync(deploymentId, parameters, CancellationToken.None);
}
/// <summary>
/// Redeploys a specific website deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Redeploy(this IDeploymentOperations operations, string deploymentId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).RedeployAsync(deploymentId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Redeploys a specific website deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.WebSitesExtensions.IDeploymentOperations.
/// </param>
/// <param name='deploymentId'>
/// Required. The deployment identifier.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> RedeployAsync(this IDeploymentOperations operations, string deploymentId)
{
return operations.RedeployAsync(deploymentId, CancellationToken.None);
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using Common.Logging;
using Quartz.Core;
using Quartz.Simpl;
using Quartz.Spi;
namespace Quartz.Impl
{
/// <summary>
/// A singleton implementation of <see cref="ISchedulerFactory" />.
/// </summary>
/// <remarks>
/// Here are some examples of using this class:
/// <para>
/// To create a scheduler that does not write anything to the database (is not
/// persistent), you can call <see cref="CreateVolatileScheduler" />:
/// </para>
/// <code>
/// DirectSchedulerFactory.Instance.CreateVolatileScheduler(10); // 10 threads
/// // don't forget to start the scheduler:
/// DirectSchedulerFactory.Instance.GetScheduler().Start();
/// </code>
/// <para>
/// Several create methods are provided for convenience. All create methods
/// eventually end up calling the create method with all the parameters:
/// </para>
/// <code>
/// public void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IJobStore jobStore)
/// </code>
/// <para>
/// Here is an example of using this method:
/// </para>
/// <code>
/// // create the thread pool
/// SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, ThreadPriority.Normal);
/// threadPool.Initialize();
/// // create the job store
/// JobStore jobStore = new RAMJobStore();
///
/// DirectSchedulerFactory.Instance.CreateScheduler("My Quartz Scheduler", "My Instance", threadPool, jobStore);
/// // don't forget to start the scheduler:
/// DirectSchedulerFactory.Instance.GetScheduler("My Quartz Scheduler", "My Instance").Start();
/// </code>
/// </remarks>>
/// <author>Mohammad Rezaei</author>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
/// <seealso cref="IJobStore" />
/// <seealso cref="ThreadPool" />
public class DirectSchedulerFactory : ISchedulerFactory
{
private readonly ILog log;
public const string DefaultInstanceId = "SIMPLE_NON_CLUSTERED";
public const string DefaultSchedulerName = "SimpleQuartzScheduler";
private static readonly DefaultThreadExecutor DefaultThreadExecutor = new DefaultThreadExecutor();
private const int DefaultBatchMaxSize = 1;
private readonly TimeSpan DefaultBatchTimeWindow = TimeSpan.Zero;
private bool initialized;
private static readonly DirectSchedulerFactory instance = new DirectSchedulerFactory();
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
public ILog Log
{
get { return log; }
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <value>The instance.</value>
public static DirectSchedulerFactory Instance
{
get { return instance; }
}
/// <summary> <para>
/// Returns a handle to all known Schedulers (made by any
/// StdSchedulerFactory instance.).
/// </para>
/// </summary>
public virtual ICollection<IScheduler> AllSchedulers
{
get { return SchedulerRepository.Instance.LookupAll(); }
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectSchedulerFactory"/> class.
/// </summary>
protected DirectSchedulerFactory()
{
log = LogManager.GetLogger(GetType());
}
/// <summary>
/// Creates an in memory job store (<see cref="RAMJobStore" />)
/// The thread priority is set to Thread.NORM_PRIORITY
/// </summary>
/// <param name="maxThreads">The number of threads in the thread pool</param>
public virtual void CreateVolatileScheduler(int maxThreads)
{
SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, ThreadPriority.Normal);
threadPool.Initialize();
IJobStore jobStore = new RAMJobStore();
CreateScheduler(threadPool, jobStore);
}
/// <summary>
/// Creates a proxy to a remote scheduler. This scheduler can be retrieved
/// via <see cref="DirectSchedulerFactory.GetScheduler()" />.
/// </summary>
/// <throws> SchedulerException </throws>
public virtual void CreateRemoteScheduler(string proxyAddress)
{
CreateRemoteScheduler(DefaultSchedulerName, DefaultInstanceId, proxyAddress);
}
/// <summary>
/// Same as <see cref="DirectSchedulerFactory.CreateRemoteScheduler(string)" />,
/// with the addition of specifying the scheduler name and instance ID. This
/// scheduler can only be retrieved via <see cref="DirectSchedulerFactory.GetScheduler(string)" />.
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="proxyAddress"></param>
/// <throws> SchedulerException </throws>
protected virtual void CreateRemoteScheduler(string schedulerName, string schedulerInstanceId, string proxyAddress)
{
string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedulerName, schedulerInstanceId);
var proxyBuilder = new RemotingSchedulerProxyFactory();
proxyBuilder.Address = proxyAddress;
RemoteScheduler remoteScheduler = new RemoteScheduler(uid, proxyBuilder);
SchedulerRepository schedRep = SchedulerRepository.Instance;
schedRep.Bind(remoteScheduler);
initialized = true;
}
/// <summary>
/// Creates a scheduler using the specified thread pool and job store. This
/// scheduler can be retrieved via DirectSchedulerFactory#GetScheduler()
/// </summary>
/// <param name="threadPool">
/// The thread pool for executing jobs
/// </param>
/// <param name="jobStore">
/// The type of job store
/// </param>
/// <throws> SchedulerException </throws>
/// <summary> if initialization failed
/// </summary>
public virtual void CreateScheduler(IThreadPool threadPool, IJobStore jobStore)
{
CreateScheduler(DefaultSchedulerName, DefaultInstanceId, threadPool, jobStore);
initialized = true;
}
/// <summary>
/// Same as DirectSchedulerFactory#createScheduler(ThreadPool threadPool, JobStore jobStore),
/// with the addition of specifying the scheduler name and instance ID. This
/// scheduler can only be retrieved via DirectSchedulerFactory#getScheduler(String)
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="threadPool">The thread pool for executing jobs</param>
/// <param name="jobStore">The type of job store</param>
public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool,
IJobStore jobStore)
{
CreateScheduler(schedulerName, schedulerInstanceId, threadPool, jobStore, TimeSpan.Zero, TimeSpan.Zero);
}
/// <summary>
/// Creates a scheduler using the specified thread pool and job store and
/// binds it for remote access.
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="threadPool">The thread pool for executing jobs</param>
/// <param name="jobStore">The type of job store</param>
/// <param name="idleWaitTime">The idle wait time. You can specify "-1" for
/// the default value, which is currently 30000 ms.</param>
/// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool,
IJobStore jobStore, TimeSpan idleWaitTime,
TimeSpan dbFailureRetryInterval)
{
CreateScheduler(schedulerName, schedulerInstanceId, threadPool, jobStore, null, idleWaitTime, dbFailureRetryInterval);
}
/// <summary>
/// Creates a scheduler using the specified thread pool and job store and
/// binds it for remote access.
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="threadPool">The thread pool for executing jobs</param>
/// <param name="jobStore">The type of job store</param>
/// <param name="schedulerPluginMap"></param>
/// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
/// the default value, which is currently 30000 ms.</param>
/// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool,
IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime,
TimeSpan dbFailureRetryInterval)
{
CreateScheduler(
schedulerName, schedulerInstanceId, threadPool, DefaultThreadExecutor,
jobStore, schedulerPluginMap, idleWaitTime, dbFailureRetryInterval);
}
/// <summary>
/// Creates a scheduler using the specified thread pool and job store and
/// binds it for remote access.
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="threadPool">The thread pool for executing jobs</param>
/// <param name="threadExecutor">Thread executor.</param>
/// <param name="jobStore">The type of job store</param>
/// <param name="schedulerPluginMap"></param>
/// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
/// the default value, which is currently 30000 ms.</param>
/// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor,
IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime,
TimeSpan dbFailureRetryInterval)
{
CreateScheduler(schedulerName, schedulerInstanceId, threadPool, threadExecutor, jobStore, schedulerPluginMap, idleWaitTime, dbFailureRetryInterval, DefaultBatchMaxSize, DefaultBatchTimeWindow);
}
/// <summary>
/// Creates a scheduler using the specified thread pool and job store and
/// binds it for remote access.
/// </summary>
/// <param name="schedulerName">The name for the scheduler.</param>
/// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
/// <param name="threadPool">The thread pool for executing jobs</param>
/// <param name="threadExecutor">Thread executor.</param>
/// <param name="jobStore">The type of job store</param>
/// <param name="schedulerPluginMap"></param>
/// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
/// the default value, which is currently 30000 ms.</param>
/// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
/// <param name="maxBatchSize">The maximum batch size of triggers, when acquiring them</param>
/// <param name="batchTimeWindow">The time window for which it is allowed to "pre-acquire" triggers to fire</param>
public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor,
IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime,
TimeSpan dbFailureRetryInterval, int maxBatchSize, TimeSpan batchTimeWindow)
{
// Currently only one run-shell factory is available...
IJobRunShellFactory jrsf = new StdJobRunShellFactory();
// Fire everything u
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
threadPool.Initialize();
QuartzSchedulerResources qrs = new QuartzSchedulerResources();
qrs.Name = schedulerName;
qrs.InstanceId = schedulerInstanceId;
SchedulerDetailsSetter.SetDetails(threadPool, schedulerName, schedulerInstanceId);
qrs.JobRunShellFactory = jrsf;
qrs.ThreadPool = threadPool;
qrs.ThreadExecutor= threadExecutor;
qrs.JobStore = jobStore;
qrs.MaxBatchSize = maxBatchSize;
qrs.BatchTimeWindow = batchTimeWindow;
// add plugins
if (schedulerPluginMap != null)
{
foreach (ISchedulerPlugin plugin in schedulerPluginMap.Values)
{
qrs.AddSchedulerPlugin(plugin);
}
}
QuartzScheduler qs = new QuartzScheduler(qrs, idleWaitTime, dbFailureRetryInterval);
ITypeLoadHelper cch = new SimpleTypeLoadHelper();
cch.Initialize();
SchedulerDetailsSetter.SetDetails(jobStore, schedulerName, schedulerInstanceId);
jobStore.Initialize(cch, qs.SchedulerSignaler);
IScheduler scheduler = new StdScheduler(qs);
jrsf.Initialize(scheduler);
qs.Initialize();
// Initialize plugins now that we have a Scheduler instance.
if (schedulerPluginMap != null)
{
foreach (var pluginEntry in schedulerPluginMap)
{
pluginEntry.Value.Initialize(pluginEntry.Key, scheduler);
}
}
Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler '{0}", scheduler.SchedulerName));
Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler version: {0}", qs.Version));
SchedulerRepository schedRep = SchedulerRepository.Instance;
qs.AddNoGCObject(schedRep); // prevents the repository from being
// garbage collected
schedRep.Bind(scheduler);
initialized = true;
}
/// <summary>
/// Returns a handle to the Scheduler produced by this factory.
/// <para>
/// you must call createRemoteScheduler or createScheduler methods before
/// calling getScheduler()
/// </para>
/// </summary>
/// <returns></returns>
/// <throws> SchedulerException </throws>
public virtual IScheduler GetScheduler()
{
if (!initialized)
{
throw new SchedulerException(
"you must call createRemoteScheduler or createScheduler methods before calling getScheduler()");
}
SchedulerRepository schedRep = SchedulerRepository.Instance;
return schedRep.Lookup(DefaultSchedulerName);
}
/// <summary>
/// Returns a handle to the Scheduler with the given name, if it exists.
/// </summary>
public virtual IScheduler GetScheduler(string schedName)
{
SchedulerRepository schedRep = SchedulerRepository.Instance;
return schedRep.Lookup(schedName);
}
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Globalization;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.SqlTypes
{
// Options that are used in comparison
[Flags]
public enum SqlCompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
BinarySort = 0x00008000, // binary sorting
BinarySort2 = 0x00004000, // binary sorting 2
}
/// <devdoc>
/// <para>
/// Represents a variable-length stream of characters to be stored in or retrieved from the database.
/// </para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public struct SqlString : INullable, IComparable
{
private String _value;
private CompareInfo _cmpInfo;
private int _lcid; // Locale Id
private SqlCompareOptions _flag; // Compare flags
private bool _fNotNull; // false if null
/// <devdoc>
/// <para>
/// Represents a null value that can be assigned to the <see cref='System.Data.SqlTypes.SqlString.Value'/> property of an instance of
/// the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public static readonly SqlString Null = new SqlString(true);
internal static readonly UnicodeEncoding x_UnicodeEncoding = new UnicodeEncoding();
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreCase = 0x1;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreWidth = 0x10;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreNonSpace = 0x2;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreKanaType = 0x8;
/// <devdoc>
/// </devdoc>
public static readonly int BinarySort = 0x8000;
/// <devdoc>
/// </devdoc>
public static readonly int BinarySort2 = 0x4000;
private static readonly SqlCompareOptions s_iDefaultFlag =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.IgnoreWidth;
private static readonly CompareOptions s_iValidCompareOptionMask =
CompareOptions.IgnoreCase | CompareOptions.IgnoreWidth |
CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType;
internal static readonly SqlCompareOptions x_iValidSqlCompareOptionMask =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
internal static readonly int x_lcidUSEnglish = 0x00000409;
private static readonly int s_lcidBinary = 0x00008200;
// constructor
// construct a Null
private SqlString(bool fNull)
{
_value = null;
_cmpInfo = null;
_lcid = 0;
_flag = SqlCompareOptions.None;
_fNotNull = false;
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_fNotNull = true;
// m_cmpInfo is set lazily, so that we don't need to pay the cost
// unless the string is used in comparison.
_cmpInfo = null;
if (fUnicode)
{
_value = x_UnicodeEncoding.GetString(data, index, count);
}
else
{
Encoding cpe = Locale.GetEncodingForLcid(_lcid);
_value = cpe.GetString(data, index, count);
}
}
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, bool fUnicode)
: this(lcid, compareOptions, data, 0, data.Length, fUnicode)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count)
: this(lcid, compareOptions, data, index, count, true)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data)
: this(lcid, compareOptions, data, 0, data.Length, true)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data, int lcid, SqlCompareOptions compareOptions)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
_cmpInfo = null;
if (data == null)
{
_fNotNull = false;
_value = null;
}
else
{
_fNotNull = true;
_value = data; // PERF: do not String.Copy
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data, int lcid) : this(data, lcid, s_iDefaultFlag)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data) : this(data, Locale.GetCurrentCultureLcid(), s_iDefaultFlag)
{
}
private SqlString(int lcid, SqlCompareOptions compareOptions, String data, CompareInfo cmpInfo)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_value = data;
_cmpInfo = cmpInfo;
_fNotNull = true;
}
}
// INullable
/// <devdoc>
/// <para>
/// Gets whether the <see cref='System.Data.SqlTypes.SqlString.Value'/> of the <see cref='System.Data.SqlTypes.SqlString'/> is <see cref='System.Data.SqlTypes.SqlString.Null'/>.
/// </para>
/// </devdoc>
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
/// <devdoc>
/// <para>
/// Gets the string that is to be stored.
/// </para>
/// </devdoc>
public String Value
{
get
{
if (!IsNull)
return _value;
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int LCID
{
get
{
if (!IsNull)
return _lcid;
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CultureInfo CultureInfo
{
get
{
if (!IsNull)
return new CultureInfo(Locale.GetLocaleNameForLcid(_lcid));
else
throw new SqlNullValueException();
}
}
private void SetCompareInfo()
{
Debug.Assert(!IsNull);
if (_cmpInfo == null)
_cmpInfo = (new CultureInfo(Locale.GetLocaleNameForLcid(_lcid))).CompareInfo;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CompareInfo CompareInfo
{
get
{
if (!IsNull)
{
SetCompareInfo();
return _cmpInfo;
}
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlCompareOptions SqlCompareOptions
{
get
{
if (!IsNull)
return _flag;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from String to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlString(String x)
{
return new SqlString(x);
}
// Explicit conversion from SqlString to String. Throw exception if x is Null.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator String(SqlString x)
{
return x.Value;
}
/// <devdoc>
/// <para>
/// Converts a <see cref='System.Data.SqlTypes.SqlString'/> object to a string.
/// </para>
/// </devdoc>
public override String ToString()
{
return IsNull ? SQLResource.NullString : _value;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte[] GetUnicodeBytes()
{
if (IsNull)
return null;
return x_UnicodeEncoding.GetBytes(_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte[] GetNonUnicodeBytes()
{
if (IsNull)
return null;
// Get the CultureInfo
Encoding cpe = Locale.GetEncodingForLcid(_lcid);
return cpe.GetBytes(_value);
}
/*
internal int GetSQLCID() {
if (IsNull)
throw new SqlNullValueException();
return MAKECID(m_lcid, m_flag);
}
*/
// Binary operators
// Concatenation
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlString operator +(SqlString x, SqlString y)
{
if (x.IsNull || y.IsNull)
return SqlString.Null;
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.ConcatDiffCollationMessage);
return new SqlString(x._lcid, x._flag, x._value + y._value,
(x._cmpInfo == null) ? y._cmpInfo : x._cmpInfo);
}
// StringCompare: Common compare function which is used by Compare and CompareTo
// In the case of Compare (used by comparison operators) the int result needs to be converted to SqlBoolean type
// while CompareTo needs the result in int type
// Pre-requisite: the null condition of the both string needs to be checked and handled by the caller of this function
private static int StringCompare(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull, "Null condition should be handled by the caller of StringCompare method");
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.CompareDiffCollationMessage);
x.SetCompareInfo();
y.SetCompareInfo();
Debug.Assert(x.FBinarySort() || (x._cmpInfo != null && y._cmpInfo != null));
int iCmpResult;
if ((x._flag & SqlCompareOptions.BinarySort) != 0)
iCmpResult = CompareBinary(x, y);
else if ((x._flag & SqlCompareOptions.BinarySort2) != 0)
iCmpResult = CompareBinary2(x, y);
else
{
// SqlString can be padded with spaces (Padding is turn on by default in SQL Server 2008
// Trim the trailing space for comparison
// Avoid using String.TrimEnd function to avoid extra string allocations
string rgchX = x._value;
string rgchY = y._value;
int cwchX = rgchX.Length;
int cwchY = rgchY.Length;
while (cwchX > 0 && rgchX[cwchX - 1] == ' ')
cwchX--;
while (cwchY > 0 && rgchY[cwchY - 1] == ' ')
cwchY--;
CompareOptions options = CompareOptionsFromSqlCompareOptions(x._flag);
iCmpResult = x._cmpInfo.Compare(x._value, 0, cwchX, y._value, 0, cwchY, options);
}
return iCmpResult;
}
// Comparison operators
private static SqlBoolean Compare(SqlString x, SqlString y, EComparison ecExpectedResult)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
int iCmpResult = StringCompare(x, y);
bool fResult = false;
switch (ecExpectedResult)
{
case EComparison.EQ:
fResult = (iCmpResult == 0);
break;
case EComparison.LT:
fResult = (iCmpResult < 0);
break;
case EComparison.LE:
fResult = (iCmpResult <= 0);
break;
case EComparison.GT:
fResult = (iCmpResult > 0);
break;
case EComparison.GE:
fResult = (iCmpResult >= 0);
break;
default:
Debug.Assert(false, "Invalid ecExpectedResult");
return SqlBoolean.Null;
}
return new SqlBoolean(fResult);
}
// Implicit conversions
// Explicit conversions
// Explicit conversion from SqlBoolean to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlBoolean x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString());
}
// Explicit conversion from SqlByte to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlByte x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt16 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt16 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt32 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt32 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt64 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt64 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlSingle to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlSingle x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDouble to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDouble x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDecimal to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDecimal x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlMoney to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlMoney x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlDateTime to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDateTime x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlGuid to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlGuid x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlString Clone()
{
if (IsNull)
return new SqlString(true);
else
{
SqlString ret = new SqlString(_value, _lcid, _flag);
return ret;
}
}
// Overloading comparison operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator ==(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.EQ);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator !=(SqlString x, SqlString y)
{
return !(x == y);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LT);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GT);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LE);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GE);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlString Concat(SqlString x, SqlString y)
{
return x + y;
}
public static SqlString Add(SqlString x, SqlString y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlString x, SqlString y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlString x, SqlString y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlString x, SqlString y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlString x, SqlString y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlString x, SqlString y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlString x, SqlString y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDateTime ToSqlDateTime()
{
return (SqlDateTime)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// Utility functions and constants
private static void ValidateSqlCompareOptions(SqlCompareOptions compareOptions)
{
if ((compareOptions & x_iValidSqlCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException(nameof(compareOptions));
}
public static CompareOptions CompareOptionsFromSqlCompareOptions(SqlCompareOptions compareOptions)
{
CompareOptions options = CompareOptions.None;
ValidateSqlCompareOptions(compareOptions);
if ((compareOptions & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0)
throw ADP.ArgumentOutOfRange("compareOptions");
else
{
if ((compareOptions & SqlCompareOptions.IgnoreCase) != 0)
options |= CompareOptions.IgnoreCase;
if ((compareOptions & SqlCompareOptions.IgnoreNonSpace) != 0)
options |= CompareOptions.IgnoreNonSpace;
if ((compareOptions & SqlCompareOptions.IgnoreKanaType) != 0)
options |= CompareOptions.IgnoreKanaType;
if ((compareOptions & SqlCompareOptions.IgnoreWidth) != 0)
options |= CompareOptions.IgnoreWidth;
}
return options;
}
/*
private static SqlCompareOptions SqlCompareOptionsFromCompareOptions(CompareOptions compareOptions) {
SqlCompareOptions sqlOptions = SqlCompareOptions.None;
if ((compareOptions & x_iValidCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException ("compareOptions");
else {
if ((compareOptions & CompareOptions.IgnoreCase) != 0)
sqlOptions |= SqlCompareOptions.IgnoreCase;
if ((compareOptions & CompareOptions.IgnoreNonSpace) != 0)
sqlOptions |= SqlCompareOptions.IgnoreNonSpace;
if ((compareOptions & CompareOptions.IgnoreKanaType) != 0)
sqlOptions |= SqlCompareOptions.IgnoreKanaType;
if ((compareOptions & CompareOptions.IgnoreWidth) != 0)
sqlOptions |= SqlCompareOptions.IgnoreWidth;
}
return sqlOptions;
}
*/
private bool FBinarySort()
{
return (!IsNull && (_flag & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0);
}
// Wide-character string comparison for Binary Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a memory comparison.
private static int CompareBinary(SqlString x, SqlString y)
{
byte[] rgDataX = x_UnicodeEncoding.GetBytes(x._value);
byte[] rgDataY = x_UnicodeEncoding.GetBytes(y._value);
int cbX = rgDataX.Length;
int cbY = rgDataY.Length;
int cbMin = cbX < cbY ? cbX : cbY;
int i;
Debug.Assert(cbX % 2 == 0);
Debug.Assert(cbY % 2 == 0);
for (i = 0; i < cbMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
i = cbMin;
int iCh;
int iSpace = (int)' ';
if (cbX < cbY)
{
for (; i < cbY; i += 2)
{
iCh = ((int)rgDataY[i + 1]) << 8 + rgDataY[i];
if (iCh != iSpace)
return (iSpace > iCh) ? 1 : -1;
}
}
else
{
for (; i < cbX; i += 2)
{
iCh = ((int)rgDataX[i + 1]) << 8 + rgDataX[i];
if (iCh != iSpace)
return (iCh > iSpace) ? 1 : -1;
}
}
return 0;
}
// Wide-character string comparison for Binary2 Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a wchar comparison (different from memcmp of BinarySort).
private static int CompareBinary2(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull);
string rgDataX = x._value;
string rgDataY = y._value;
int cwchX = rgDataX.Length;
int cwchY = rgDataY.Length;
int cwchMin = cwchX < cwchY ? cwchX : cwchY;
int i;
for (i = 0; i < cwchMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
// If compares equal up to one of the string terminates,
// pad it with spaces and compare with the rest of the other one.
//
char chSpace = ' ';
if (cwchX < cwchY)
{
for (i = cwchMin; i < cwchY; i++)
{
if (rgDataY[i] != chSpace)
return (chSpace > rgDataY[i]) ? 1 : -1;
}
}
else
{
for (i = cwchMin; i < cwchX; i++)
{
if (rgDataX[i] != chSpace)
return (rgDataX[i] > chSpace) ? 1 : -1;
}
}
return 0;
}
/*
private void Print() {
Debug.WriteLine("SqlString - ");
Debug.WriteLine("\tlcid = " + m_lcid.ToString());
Debug.Write("\t");
if ((m_flag & SqlCompareOptions.IgnoreCase) != 0)
Debug.Write("IgnoreCase, ");
if ((m_flag & SqlCompareOptions.IgnoreNonSpace) != 0)
Debug.Write("IgnoreNonSpace, ");
if ((m_flag & SqlCompareOptions.IgnoreKanaType) != 0)
Debug.Write("IgnoreKanaType, ");
if ((m_flag & SqlCompareOptions.IgnoreWidth) != 0)
Debug.Write("IgnoreWidth, ");
Debug.WriteLine("");
Debug.WriteLine("\tvalue = " + m_value);
Debug.WriteLine("\tcmpinfo = " + m_cmpInfo);
}
*/
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int CompareTo(Object value)
{
if (value is SqlString)
{
SqlString i = (SqlString)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlString));
}
public int CompareTo(SqlString value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
int returnValue = StringCompare(this, value);
// Conver the result into -1, 0, or 1 as this method never returned any other values
// This is to ensure the backcompat
if (returnValue < 0)
{
return -1;
}
if (returnValue > 0)
{
return 1;
}
return 0;
}
// Compares this instance with a specified object
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(Object value)
{
if (!(value is SqlString))
{
return false;
}
SqlString i = (SqlString)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode()
{
if (IsNull)
return 0;
byte[] rgbSortKey;
if (FBinarySort())
rgbSortKey = x_UnicodeEncoding.GetBytes(_value.TrimEnd());
else
{
// VSDevDiv 479660
// GetHashCode should not throw just because this instance has an invalid LCID or compare options.
CompareInfo cmpInfo;
CompareOptions options;
try
{
SetCompareInfo();
cmpInfo = _cmpInfo;
options = CompareOptionsFromSqlCompareOptions(_flag);
}
catch (ArgumentException)
{
// SetCompareInfo throws this when instance's LCID is unsupported
// CompareOptionsFromSqlCompareOptions throws this when instance's options are invalid
cmpInfo = CultureInfo.InvariantCulture.CompareInfo;
options = CompareOptions.None;
}
return cmpInfo.GetHashCode(_value.TrimEnd(), options);
}
return SqlBinary.HashByteArray(rgbSortKey, rgbSortKey.Length);
}
} // SqlString
/*
internal struct SLocaleMapItem {
public int lcid; // the primary key, not nullable
public String name; // unique, nullable
public int idCodePage; // the ANSI default code page of the locale
public SLocaleMapItem(int lid, String str, int cpid) {
lcid = lid;
name = str;
idCodePage = cpid;
}
}
// Struct to map lcid to ordinal
internal struct SLcidOrdMapItem {
internal int lcid;
internal int uiOrd;
};
// Class to store map of lcids to ordinal
internal class CBuildLcidOrdMap {
internal SLcidOrdMapItem[] m_rgLcidOrdMap;
internal int m_cValidLocales;
internal int m_uiPosEnglish; // Start binary searches here - this is index in array, not ordinal
// Constructor builds the array sorted by lcid
// We use a simple n**2 sort because the array is mostly sorted anyway
// and objects of this class will be const, hence this will be called
// only by VC compiler
public CBuildLcidOrdMap() {
int i,j;
m_rgLcidOrdMap = new SLcidOrdMapItem[SqlString.x_cLocales];
// Compact the array
for (i=0,j=0; i < SqlString.x_cLocales; i++) {
if (SqlString.x_rgLocaleMap[i].lcid != SqlString.x_lcidUnused) {
m_rgLcidOrdMap[j].lcid = SqlString.x_rgLocaleMap[i].lcid;
m_rgLcidOrdMap[j].uiOrd = i;
j++;
}
}
m_cValidLocales = j;
// Set the rest to invalid
while (j < SqlString.x_cLocales) {
m_rgLcidOrdMap[j].lcid = SqlString.x_lcidUnused;
m_rgLcidOrdMap[j].uiOrd = 0;
j++;
}
// Now sort in place
// Algo:
// Start from 1, assume list before i is sorted, if next item
// violates this assumption, exchange with prev items until the
// item is in its correct place
for (i=1; i<m_cValidLocales; i++) {
for (j=i; j>0 &&
m_rgLcidOrdMap[j].lcid < m_rgLcidOrdMap[j-1].lcid; j--) {
// Swap with prev element
int lcidTemp = m_rgLcidOrdMap[j-1].lcid;
int uiOrdTemp = m_rgLcidOrdMap[j-1].uiOrd;
m_rgLcidOrdMap[j-1].lcid = m_rgLcidOrdMap[j].lcid;
m_rgLcidOrdMap[j-1].uiOrd = m_rgLcidOrdMap[j].uiOrd;
m_rgLcidOrdMap[j].lcid = lcidTemp;
m_rgLcidOrdMap[j].uiOrd = uiOrdTemp;
}
}
// Set the position of the US_English LCID (Latin1_General)
for (i=0; i<m_cValidLocales && m_rgLcidOrdMap[i].lcid != SqlString.x_lcidUSEnglish; i++)
; // Deliberately empty
SQLDebug.Check(i<m_cValidLocales); // Latin1_General better be present
m_uiPosEnglish = i; // This is index in array, not ordinal
}
} // CBuildLcidOrdMap
*/
} // namespace System.Data.SqlTypes
| |
// 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.Threading.Tasks;
using System.Threading.Tests;
using Xunit;
namespace System.Threading.ThreadPools.Tests
{
public static class ThreadPoolTests
{
private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds;
private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds;
private const int MaxPossibleThreadCount = 0x7fff;
[Fact]
public static void GetMinMaxThreadsTest()
{
int minw, minc;
ThreadPool.GetMinThreads(out minw, out minc);
Assert.True(minw > 0);
Assert.True(minc > 0);
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.True(minw <= maxw);
Assert.True(minc <= maxc);
}
[Fact]
public static void GetAvailableThreadsTest()
{
int w, c;
ThreadPool.GetAvailableThreads(out w, out c);
Assert.True(w >= 0);
Assert.True(c >= 0);
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.True(w <= maxw);
Assert.True(c <= maxc);
}
[Fact]
public static void SetMinMaxThreadsTest()
{
int minw, minc, maxw, maxc;
ThreadPool.GetMinThreads(out minw, out minc);
ThreadPool.GetMaxThreads(out maxw, out maxc);
Action resetThreadCounts =
() =>
{
Assert.True(ThreadPool.SetMaxThreads(maxw, maxc));
VerifyMaxThreads(maxw, maxc);
Assert.True(ThreadPool.SetMinThreads(minw, minc));
VerifyMinThreads(minw, minc);
};
try
{
int mint = Environment.ProcessorCount * 2;
int maxt = mint + 1;
ThreadPool.SetMinThreads(mint, mint);
ThreadPool.SetMaxThreads(maxt, maxt);
Assert.False(ThreadPool.SetMinThreads(maxt + 1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, maxt + 1));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, mint));
Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount + 1));
Assert.False(ThreadPool.SetMinThreads(-1, mint));
Assert.False(ThreadPool.SetMinThreads(mint, -1));
Assert.False(ThreadPool.SetMaxThreads(mint - 1, maxt));
Assert.False(ThreadPool.SetMaxThreads(maxt, mint - 1));
VerifyMinThreads(mint, mint);
VerifyMaxThreads(maxt, maxt);
Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount + 1));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMaxThreads(-1, -1));
VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount));
VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount + 1));
Assert.False(ThreadPool.SetMinThreads(-1, MaxPossibleThreadCount));
Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, -1));
VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount);
Assert.True(ThreadPool.SetMinThreads(0, 0));
VerifyMinThreads(0, 0);
Assert.True(ThreadPool.SetMaxThreads(1, 1));
VerifyMaxThreads(1, 1);
Assert.True(ThreadPool.SetMinThreads(1, 1));
VerifyMinThreads(1, 1);
}
finally
{
resetThreadCounts();
}
}
[Fact]
// Desktop framework doesn't check for this and instead, hits an assertion failure
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void SetMinMaxThreadsTest_ChangedInDotNetCore()
{
int minw, minc, maxw, maxc;
ThreadPool.GetMinThreads(out minw, out minc);
ThreadPool.GetMaxThreads(out maxw, out maxc);
Action resetThreadCounts =
() =>
{
Assert.True(ThreadPool.SetMaxThreads(maxw, maxc));
VerifyMaxThreads(maxw, maxc);
Assert.True(ThreadPool.SetMinThreads(minw, minc));
VerifyMinThreads(minw, minc);
};
try
{
Assert.True(ThreadPool.SetMinThreads(0, 0));
VerifyMinThreads(0, 0);
Assert.False(ThreadPool.SetMaxThreads(0, 0));
VerifyMaxThreads(maxw, maxc);
}
finally
{
resetThreadCounts();
}
}
private static void VerifyMinThreads(int expectedMinw, int expectedMinc)
{
int minw, minc;
ThreadPool.GetMinThreads(out minw, out minc);
Assert.Equal(expectedMinw, minw);
Assert.Equal(expectedMinc, minc);
}
private static void VerifyMaxThreads(int expectedMaxw, int expectedMaxc)
{
int maxw, maxc;
ThreadPool.GetMaxThreads(out maxw, out maxc);
Assert.Equal(expectedMaxw, maxw);
Assert.Equal(expectedMaxc, maxc);
}
[Fact]
public static void QueueRegisterPositiveAndFlowTest()
{
var asyncLocal = new AsyncLocal<int>();
asyncLocal.Value = 1;
var obj = new object();
var registerWaitEvent = new AutoResetEvent(false);
var threadDone = new AutoResetEvent(false);
RegisteredWaitHandle registeredWaitHandle = null;
Exception backgroundEx = null;
int backgroundAsyncLocalValue = 0;
Action<bool, Action> commonBackgroundTest =
(isRegisteredWaitCallback, test) =>
{
try
{
if (isRegisteredWaitCallback)
{
RegisteredWaitHandle toUnregister = registeredWaitHandle;
registeredWaitHandle = null;
Assert.True(toUnregister.Unregister(threadDone));
}
test();
backgroundAsyncLocalValue = asyncLocal.Value;
}
catch (Exception ex)
{
backgroundEx = ex;
}
finally
{
if (!isRegisteredWaitCallback)
{
threadDone.Set();
}
}
};
Action<bool> waitForBackgroundWork =
isWaitForRegisteredWaitCallback =>
{
if (isWaitForRegisteredWaitCallback)
{
registerWaitEvent.Set();
}
threadDone.CheckedWait();
if (backgroundEx != null)
{
throw new AggregateException(backgroundEx);
}
};
ThreadPool.QueueUserWorkItem(
state =>
{
commonBackgroundTest(false, () =>
{
Assert.Same(obj, state);
});
},
obj);
waitForBackgroundWork(false);
Assert.Equal(1, backgroundAsyncLocalValue);
ThreadPool.UnsafeQueueUserWorkItem(
state =>
{
commonBackgroundTest(false, () =>
{
Assert.Same(obj, state);
});
},
obj);
waitForBackgroundWork(false);
Assert.Equal(0, backgroundAsyncLocalValue);
registeredWaitHandle =
ThreadPool.RegisterWaitForSingleObject(
registerWaitEvent,
(state, timedOut) =>
{
commonBackgroundTest(true, () =>
{
Assert.Same(obj, state);
Assert.False(timedOut);
});
},
obj,
UnexpectedTimeoutMilliseconds,
false);
waitForBackgroundWork(true);
Assert.Equal(1, backgroundAsyncLocalValue);
registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
registerWaitEvent,
(state, timedOut) =>
{
commonBackgroundTest(true, () =>
{
Assert.Same(obj, state);
Assert.False(timedOut);
});
},
obj,
UnexpectedTimeoutMilliseconds,
false);
waitForBackgroundWork(true);
Assert.Equal(0, backgroundAsyncLocalValue);
}
[Fact]
public static void QueueRegisterNegativeTest()
{
Assert.Throws<ArgumentNullException>(() => ThreadPool.QueueUserWorkItem(null));
Assert.Throws<ArgumentNullException>(() => ThreadPool.UnsafeQueueUserWorkItem(null, null));
WaitHandle waitHandle = new ManualResetEvent(true);
WaitOrTimerCallback callback = (state, timedOut) => { };
Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(null, callback, null, 0, true));
Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, null, null, 0, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, -2, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, (long)-2, true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, TimeSpan.FromMilliseconds(-2), true));
Assert.Throws<ArgumentOutOfRangeException>(() =>
ThreadPool.RegisterWaitForSingleObject(
waitHandle,
callback,
null,
TimeSpan.FromMilliseconds((double)int.MaxValue + 1),
true));
}
}
}
| |
/*
* @(#)mXparser.cs 4.1.0 2017-04-22
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2017 MARIUSZ GROMADA. 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 <MARIUSZ GROMADA> ``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 <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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* [email protected]
* http://mathparser.org
* http://mathspace.pl
* http://janetsudoku.mariuszgromada.org
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser
* http://mxparser.sourceforge.net
* http://bitbucket.org/mariuszgromada/mxparser
* http://mxparser.codeplex.com
* http://github.com/mariuszgromada/Janet-Sudoku
* http://janetsudoku.codeplex.com
* http://sourceforge.net/projects/janetsudoku
* http://bitbucket.org/mariuszgromada/janet-sudoku
* http://github.com/mariuszgromada/MathParser.org-mXparser
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Globalization;
using org.mariuszgromada.math.mxparser.mathcollection;
using org.mariuszgromada.math.mxparser.parsertokens;
[assembly: CLSCompliant(true)]
namespace org.mariuszgromada.math.mxparser {
/**
* mXparser class provides usefull methods when parsing, calculating or
* parameters transforming.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:[email protected]">[email protected]</a><br>
* <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br>
* <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br>
* <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br>
* <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br>
* <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br>
* <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br>
*
* @version 4.1.0
*
* @see RecursiveArgument
* @see Expression
* @see Function
* @see Constant
*/
[CLSCompliant(true)]
public sealed class mXparser {
/**
* mXparser version
*/
internal const String VERSION = "4.1.0";
/**
* FOUND / NOT_FOUND
* used for matching purposes
*/
internal const int NOT_FOUND = -1;
internal const int FOUND = 0;
/**
* Console output string for below methods
*
* @see mXparser.#consolePrintln(Object)
* @see mXparser.#consolePrint(Object)
*/
private static String CONSOLE_OUTPUT = "";
private static String CONSOLE_PREFIX = "[mXparser-v." + VERSION + "] ";
private static String CONSOLE_OUTPUT_PREFIX = CONSOLE_PREFIX;
private static int CONSOLE_ROW_NUMBER = 1;
/**
* Prime numbers cache
*/
public static PrimesCache primesCache;
public const int PRIMES_CACHE_NOT_INITIALIZED = -1;
/**
* Threads number settings
*/
private static int THREADS_NUMBER = Environment.ProcessorCount;
/**
* Empty expression for general help purposes.
*/
private static Expression mXparserHelp = new Expression();
/**
* Double floating-point precision arithmetic causes
* rounding problems, i.e. 0.1 + 0.1 + 0.1 is different than 0.3
*
* mXparser provides intelligent ULP rounding to avoid this
* type of errors.
*/
internal static bool ulpRounding = true;
/**
* List of built-in tokens to remove.
*/
internal static List<String> tokensToRemove = new List<String>();
/**
* List of built-in tokens to modify
*/
internal static List<TokenModification> tokensToModify = new List<TokenModification>();
/**
* Initialization of prime numbers cache.
* Cache size according to {@link PrimesCache#DEFAULT_MAX_NUM_IN_CACHE}
* @see PrimesCache
*/
public static void initPrimesCache() {
primesCache = new PrimesCache();
}
/**
* Initialization of prime numbers cache.
* @param mximumNumberInCache The maximum integer number that
* will be stored in cache.
* @see PrimesCache
*/
public static void initPrimesCache(int mximumNumberInCache) {
primesCache = new PrimesCache(mximumNumberInCache);
}
/**
* Initialization of prime numbers cache.
* @param primesCache The primes cache object
* @see PrimesCache
*/
public static void initPrimesCache(PrimesCache primesCache) {
mXparser.primesCache = primesCache;
}
/**
* Sets {@link mXparser#primesCache} to null
*/
public static void setNoPrimesCache() {
primesCache = null;
}
/**
* Returns maximum integer number in primes cache
* @return If primes cache was initialized then maximum number in
* primes cache, otherwise {@link mXparser#PRIMES_CACHE_NOT_INITIALIZED}
*/
public static int getMaxNumInPrimesCache() {
if (primesCache != null)
return primesCache.getMaxNumInCache();
else
return PRIMES_CACHE_NOT_INITIALIZED;
}
/**
* Gets maximum threads number
* @return Threads number.
*/
public static int getThreadsNumber() {
return THREADS_NUMBER;
}
/**
* Sets default threads number
* @param threadsNumber Thread number.
*/
public static void setDefaultThreadsNumber() {
THREADS_NUMBER = Environment.ProcessorCount;
}
/**
* Sets threads number
*/
public static void setThreadsNumber(int threadsNumber) {
if (threadsNumber > 0) THREADS_NUMBER = threadsNumber;
}
private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long currentTimeMillis() {
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
/**
* Calculates function f(x0) (given as expression) assigning Argument x = x0;
*
*
* @param f the expression
* @param x the argument
* @param x0 the argument value
*
* @return f.calculate()
*
* @see Expression
*/
public static double getFunctionValue(Expression f, Argument x, double x0) {
x.setArgumentValue(x0);
return f.calculate();
}
/**
* Converts List of double to double[]
*
* @param numbers the numbers list
*
* @return numbers array
*/
public static double[] arrayList2double(List<Double> numbers) {
if (numbers == null)
return null;
int size = numbers.Count;
double[] newNumbers = new double[size];
for (int i = 0; i < size; i++)
newNumbers[i] = numbers[i];
return newNumbers;
}
/**
* Returns array of double values of the function f(i)
* calculated on the range: i = from to i = to by step = delta
*
* @param f Function expression
* @param index Index argument
* @param from 'from' value
* @param to 'to' value
* @param delta 'delta' step definition
* @return Array of function values
*/
public static double[] getFunctionValues(Expression f, Argument index, double from, double to, double delta) {
if ((Double.IsNaN(delta)) || (Double.IsNaN(from)) || (Double.IsNaN(to)) || (delta == 0))
return null;
int n = 0;
double[] values;
if ((to >= from) && (delta > 0)) {
for (double i = from; i < to; i += delta)
n++;
n++;
values = new double[n];
int j = 0;
for (double i = from; i < to; i += delta) {
values[j] = getFunctionValue(f, index, i);
j++;
}
values[j] = getFunctionValue(f, index, to);
} else if ((to <= from) && (delta < 0)) {
for (double i = from; i > to; i += delta)
n++;
n++;
values = new double[n];
int j = 0;
for (double i = from; i > to; i += delta) {
values[j] = getFunctionValue(f, index, i);
j++;
}
values[j] = getFunctionValue(f, index, to);
} else if (from == to) {
n = 1;
values = new double[n];
values[0] = getFunctionValue(f, index, from);
} else values = null;
return values;
}
/**
* Modifies random generator used by the ProbabilityDistributions class.
*
* @param randomGenerator Random generator.
* @see ProbabilityDistributions
* @see ProbabilityDistributions#randomGenerator
*/
public static void setRandomGenerator(Random randomGenerator) {
if (randomGenerator != null) ProbabilityDistributions.randomGenerator = randomGenerator;
}
/**
* Sets comparison mode to EXACT.
* @see BinaryRelations
*/
public static void setExactComparison() {
BinaryRelations.setExactComparison();
}
/**
* Sets comparison mode to EPSILON.
* @see BinaryRelations
*/
public static void setEpsilonComparison() {
BinaryRelations.setEpsilonComparison();
}
/**
* Sets epsilon value.
* @param epsilon Epsilon value (grater than 0).
*
* @see #setEpsilonComparison()
* @see BinaryRelations
*/
public static void setEpsilon(double epsilon) {
BinaryRelations.setEpsilon(epsilon);
}
/**
* Sets default epsilon value.
*
* @see #setEpsilonComparison()
* @see BinaryRelations#DEFAULT_COMPARISON_EPSILON
* @see BinaryRelations
*/
public static void setDefaultEpsilon() {
BinaryRelations.setDefaultEpsilon();
}
/**
* Returns current epsilon value.
* @return Returns current epsilon value.
*
* @see #setEpsilonComparison()
* @see BinaryRelations
*/
public static double getEpsilon() {
return BinaryRelations.getEpsilon();
}
/**
* Checks if epsilon comparison mode is active;
* @return True if epsilon mode is active, otherwise returns false.
* @see #setEpsilonComparison()
* @see #setExactComparison()
* @see BinaryRelations
*/
public static bool checkIfEpsilonMode() {
return BinaryRelations.checkIfEpsilonMode();
}
/**
* Checks if exact comparison mode is active;
* @return True if exact mode is active, otherwise returns false.
* @see #setEpsilonComparison()
* @see #setExactComparison()
* @see BinaryRelations
*/
public static bool checkIfExactMode() {
return BinaryRelations.checkIfExactMode();
}
/**
* Double floating-point precision arithmetic causes
* rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3,
* additionally doubles are having a lot of advantages
* providing flexible number representation regardless of
* number size. mXparser is fully based on double numbers
* and that is why is providing intelligent ULP rounding
* to minimize misleading results. By default this option is
* enabled resulting in automatic rounding only in some cases.
* Using this mode 0.1 + 0.1 + 0.1 = 0.3
*/
public static void enableUlpRounding() {
ulpRounding = true;
}
/**
* Double floating-point precision arithmetic causes
* rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3,
* additionally doubles are having a lot of advantages
* providing flexible number representation regardless of
* number size. mXparser is fully based on double numbers
* and that is why is providing intelligent ULP rounding
* to minimize misleading results. By default this option is
* enabled resulting in automatic rounding only in some cases.
* Disabling this mode 0.1 + 0.1 + 0.1 will be slightly different than 0.3.
*/
public static void disableUlpRounding() {
ulpRounding = false;
}
/**
* Double floating-point precision arithmetic causes
* rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3,
* additionally doubles are having a lot of advantages
* providing flexible number representation regardless of
* number size. mXparser is fully based on double numbers
* and that is why is providing intelligent ULP rounding
* to minimize misleading results. By default this option is
* enabled resulting in automatic rounding only in some cases.
* Using this mode 0.1 + 0.1 + 0.1 = 0.3
*
* @return True if ULP rounding is enabled, otherwise false.
*/
public static bool checkIfUlpRounding() {
return ulpRounding;
}
/**
* Removes built-in tokens form the list of tokens recognized by the parsers.
* Procedure affects only tokens classified to built-in functions, built-in
* constants, built-in units, built-in random variables.
*
* @param tokens List of tokens to remove.
*/
public static void removeBuiltinTokens(params String[] tokens) {
if (tokens == null) return;
foreach (String token in tokens)
if (token != null)
if (token.Length > 0)
if (!tokensToRemove.Contains(token))
tokensToRemove.Add(token);
}
/**
* Un-marks tokens previously marked to be removed.
* @param tokens List of tokens to un-mark.
*/
public static void unremoveBuiltinTokens(params String[] tokens) {
if (tokens == null) return;
if (tokens.Length == 0) return;
if (tokensToRemove.Count == 0) return;
foreach (String token in tokens)
if (token != null)
tokensToRemove.Remove(token);
}
/**
* Un-marks all tokens previously marked to be removed.
*/
public static void unremoveAllBuiltinTokens() {
tokensToRemove.Clear();
}
/**
* Returns current list of tokens marked to be removed.
* @return Current list of tokens marked to be removed
*/
public static String[] getBuiltinTokensToRemove() {
int tokensNum = tokensToRemove.Count;
String[] tokensToRemoveArray = new String[tokensNum];
for (int i = 0; i < tokensNum; i++)
tokensToRemoveArray[i] = tokensToRemove[i];
return tokensToRemoveArray;
}
/**
* Method to change definition of built-in token - more precisely
* using this method allows to modify token string recognized by the parser
* (i.e. sin(x) -> sinus(x)).
* Procedure affects only tokens classified to built-in functions, built-in
* constants, built-in units, built-in random variables.
* @param currentToken Current token name
* @param newToken New token name
*/
public static void modifyBuiltinToken(String currentToken, String newToken) {
if (currentToken == null) return;
if (currentToken.Length == 0) return;
if (newToken == null) return;
if (newToken.Length == 0) return;
foreach (TokenModification tm in tokensToModify)
if (tm.currentToken.Equals(currentToken)) return;
TokenModification tma = new TokenModification();
tma.currentToken = currentToken;
tma.newToken = newToken;
tma.newTokenDescription = null;
tokensToModify.Add(tma);
}
/**
* Method to change definition of built-in token - more precisely
* using this method allows to modify token string recognized by the parser
* (i.e. sin(x) -> sinus(x)).
* Procedure affects only tokens classified to built-in functions, built-in
* constants, built-in units, built-in random variables.
* @param currentToken Current token name
* @param newToken New token name
* @param newTokenDescription New token description (if null the previous one will be used)
*/
public static void modifyBuiltinToken(String currentToken, String newToken, String newTokenDescription) {
if (currentToken == null) return;
if (currentToken.Length == 0) return;
if (newToken == null) return;
if (newToken.Length == 0) return;
foreach (TokenModification tm in tokensToModify)
if (tm.currentToken.Equals(currentToken)) return;
TokenModification tma = new TokenModification();
tma.currentToken = currentToken;
tma.newToken = newToken;
tma.newTokenDescription = newTokenDescription;
tokensToModify.Add(tma);
}
/**
* Un-marks tokens previously marked to be modified.
* @param currentOrNewTokens List of tokens to be un-marked (current or modified).
*/
public static void unmodifyBuiltinTokens(params String[] currentOrNewTokens) {
if (currentOrNewTokens == null) return;
if (currentOrNewTokens.Length == 0) return;
if (tokensToModify.Count == 0) return;
List<TokenModification> toRemove = new List<TokenModification>();
foreach (String token in currentOrNewTokens)
if (token != null)
if (token.Length > 0) {
foreach (TokenModification tm in tokensToModify)
if ((token.Equals(tm.currentToken)) || (token.Equals(tm.newToken))) toRemove.Add(tm);
}
foreach (TokenModification tm in toRemove)
tokensToModify.Remove(tm);
}
/**
* Un-marks all tokens previously marked to be modified.
*/
public static void unmodifyAllBuiltinTokens() {
tokensToModify.Clear();
}
/**
* Return details on tokens marked to be modified.
* @return String[i][0] - current token, String[i][1] - new token,
* String[i][2] - new token description.
*/
public static String[,] getBuiltinTokensToModify() {
int tokensNum = tokensToModify.Count;
String[,] tokensToModifyArray = new String[tokensNum, 3];
for (int i = 0; i < tokensNum; i++) {
TokenModification tm = tokensToModify[i];
tokensToModifyArray[i, 0] = tm.currentToken;
tokensToModifyArray[i, 1] = tm.newToken;
tokensToModifyArray[i, 2] = tm.newTokenDescription;
}
return tokensToModifyArray;
}
/**
* Converts integer number to hex string (plain text)
*
* @param number Integer number
* @return Hex string (i.e. FF23)
*/
public static String numberToHexString(int number) {
return number.ToString("X");
}
/**
* Converts long number to hex string (plain text)
*
* @param number Long number
* @return Hex string (i.e. FF23)
*/
public static String numberToHexString(long number) {
return number.ToString("X");
}
/**
* Converts (long)double number to hex string (plain text)
*
* @param number Double number
* @return Hex string (i.e. FF23)
*/
public static String numberToHexString(double number) {
return numberToHexString((long)number);
}
/**
* Converts hex string into ASCII string, where each letter is
* represented by two hex digits (byte) from the hex string.
*
* @param hexString Hex string (i.e. 48656C6C6F)
* @return ASCII string (i.e. '48656C6C6F' = 'Hello')
*/
public static String hexString2AsciiString(String hexString) {
String hexByteStr;
int hexByteInt;
String asciiString = "";
for (int i = 0; i < hexString.Length; i += 2) {
hexByteStr = hexString.Substring(i, 2);
hexByteInt = int.Parse(hexByteStr, NumberStyles.HexNumber);
asciiString = asciiString + (char)hexByteInt;
}
return asciiString;
}
/**
* Converts number into ASCII string, where each letter is
* represented by two hex digits (byte) from the hex representation
* of the original number
*
* @param number Integer number (i.e. 310939249775 = '48656C6C6F')
* @return ASCII string (i.e. '48656C6C6F' = 'Hello')
*/
public static String numberToAsciiString(int number) {
return hexString2AsciiString(numberToHexString(number));
}
/**
* Converts number into ASCII string, where each letter is
* represented by two hex digits (byte) from the hex representation
* of the original number
*
* @param number Long number (i.e. 310939249775 = '48656C6C6F')
* @return ASCII string (i.e. '48656C6C6F' = 'Hello')
*/
public static String numberToAsciiString(long number) {
return hexString2AsciiString(numberToHexString(number));
}
/**
* Converts (long)double number into ASCII string, where each letter is
* represented by two hex digits (byte) from the hex representation
* of the original number casted to long type.
*
* @param number Double number (i.e. 310939249775 = '48656C6C6F')
* @return ASCII string (i.e. '48656C6C6F' = 'Hello')
*/
public static String numberToAsciiString(double number) {
return hexString2AsciiString(numberToHexString(number));
}
public static void doNothing(Object o) {
}
private static void consoleWriteLine(Object o) {
#if PCL || NETSTANDARD
System.Diagnostics.Debug.WriteLine(o);
#else
Console.WriteLine(o);
#endif
}
private static void consoleWriteLine() {
#if PCL || NETSTANDARD
System.Diagnostics.Debug.WriteLine("");
#else
Console.WriteLine();
#endif
}
private static void consoleWrite(Object o) {
#if PCL || NETSTANDARD
System.Diagnostics.Debug.WriteLine(o);
#else
Console.Write(o);
#endif
}
/**
* Prints object.toString to the Console + new line
*
* @param o Object to print
*/
public static void consolePrintln(Object o) {
if ((CONSOLE_ROW_NUMBER == 1) && (CONSOLE_OUTPUT.Equals(""))) {
consoleWrite(CONSOLE_PREFIX);
CONSOLE_OUTPUT = CONSOLE_PREFIX;
}
consoleWriteLine(o);
CONSOLE_ROW_NUMBER++;
consoleWrite(CONSOLE_PREFIX);
CONSOLE_OUTPUT = CONSOLE_OUTPUT + o + "\n" + CONSOLE_OUTPUT_PREFIX;
}
/**
* Prints new line to the Console, no new line
*
*/
public static void consolePrintln() {
if ((CONSOLE_ROW_NUMBER == 1) && (CONSOLE_OUTPUT.Equals(""))) {
consoleWrite(CONSOLE_PREFIX);
CONSOLE_OUTPUT = CONSOLE_PREFIX;
}
consoleWriteLine();
CONSOLE_ROW_NUMBER++;
consoleWrite(CONSOLE_PREFIX);
CONSOLE_OUTPUT = CONSOLE_OUTPUT + "\n" + CONSOLE_OUTPUT_PREFIX;
}
/**
* Prints object.toString to the Console, no new line
*
* @param o Object to print
*/
public static void consolePrint(Object o) {
if ((CONSOLE_ROW_NUMBER == 1) && (CONSOLE_OUTPUT.Equals(""))) {
consoleWrite(CONSOLE_PREFIX);
CONSOLE_OUTPUT = CONSOLE_PREFIX;
}
consoleWrite(o);
CONSOLE_OUTPUT = CONSOLE_OUTPUT + o;
}
/**
* Resets console output string, console output
* string is being built by consolePrintln(), consolePrint().
*
* @see mXparser#consolePrint(Object)
* @see mXparser#consolePrintln(Object)
* @see mXparser#consolePrintln()
* @see mXparser#resetConsoleOutput()
*/
public static void resetConsoleOutput() {
CONSOLE_OUTPUT = "";
CONSOLE_ROW_NUMBER = 1;
}
/**
* Sets default console prefix.
*/
public void setDefaultConsolePrefix() {
CONSOLE_PREFIX = "[mXparser-v." + VERSION + "] ";
}
/**
* Sets default console output string prefix.
*/
public void setDefaultConsoleOutputPrefix() {
CONSOLE_OUTPUT_PREFIX = "[mXparser-v." + VERSION + "] ";
}
/**
* Sets console prefix.
* @param consolePrefix String containing console prefix definition.
*/
public void setConsolePrefix(String consolePrefix) {
CONSOLE_PREFIX = consolePrefix;
}
/**
* Sets console output string prefix.
* @param consoleOutputPrefix String containing console output prefix definition.
*/
public void setConsoleOutputPrefix(String consoleOutputPrefix) {
CONSOLE_OUTPUT_PREFIX = consoleOutputPrefix;
}
/**
* Returns console output string, console output string
* is being built by consolePrintln(), consolePrint().
*
* @return Console output string
*
* @see mXparser#consolePrint(Object)
* @see mXparser#consolePrintln(Object)
* @see mXparser#consolePrintln();
* @see mXparser#resetConsoleOutput();
*/
public static String getConsoleOutput() {
return CONSOLE_OUTPUT;
}
/**
* General mXparser expression help
*
* @return String with all general help content
*/
public static String getHelp() {
return mXparserHelp.getHelp();
}
/**
* General mXparser expression help - in-line key word searching
* @param word Key word to be searched
* @return String with all help content
* lines containing given keyword
*/
public static String getHelp(String word) {
return mXparserHelp.getHelp(word);
}
/**
* Prints all help content.
*/
public static void consolePrintHelp() {
consoleWriteLine(getHelp());
}
/**
* Prints filtered help content.
* @param word Key word.
*/
public static void consolePrintHelp(String word) {
consoleWriteLine(getHelp(word));
}
/**
* Function used to introduce some compatibility
* between JAVA and C# while regexp matching.
*
* @param str String
* @param pattern Pattern (regexp)
*
* @return True if pattern matches entirely, False otherwise
*/
internal static bool regexMatch(String str, String pattern){
return Regex.IsMatch(str, "^(" + pattern + ")$");
}
/**
* Prints tokens to the console.
* @param tokens Tokens list.
*
* @see Expression#getCopyOfInitialTokens()
* @see Token
*/
public static void consolePrintTokens(List<Token> tokens) {
Expression.showTokens(tokens);
}
/**
* License info.
*/
public const String LICENSE =
" mXparser - version " + VERSION + "\n" +
" A flexible mathematical eXpressions parser for C#.\n" +
" (port from mXparser for JAVA)\n" +
"\n" +
"You may use this software under the condition of Simplified BSD License:\n" +
"\n" +
"Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved.\n" +
"\n" +
"Redistribution and use in source and binary forms, with or without modification, are\n" +
"permitted provided that the following conditions are met:\n" +
"\n" +
" 1. Redistributions of source code must retain the above copyright notice, this list of\n" +
" conditions and the following disclaimer.\n" +
"\n" +
" 2. Redistributions in binary form must reproduce the above copyright notice, this list\n" +
" of conditions and the following disclaimer in the documentation and/or other materials\n" +
" provided with the distribution.\n" +
"\n" +
"THIS SOFTWARE IS PROVIDED BY MARIUSZ GROMADA ``AS IS'' AND ANY EXPRESS OR IMPLIED\n" +
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n" +
"FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MARIUSZ GROMADA OR\n" +
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" +
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n" +
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n" +
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" +
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n" +
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" +
"\n" +
"The views and conclusions contained in the software and documentation are those of the\n" +
"authors and should not be interpreted as representing official policies, either expressed\n" +
"or implied, of MARIUSZ GROMADA.\n" +
"\n" +
"If you have any questions/bugs feel free to contact:\n" +
"\n" +
" Mariusz Gromada\n" +
" [email protected]\n" +
" http://mathspace.plt/\n" +
" http://mathparser.org/\n" +
" http://github.com/mariuszgromada/MathParser.org-mXparser\n" +
" http://mariuszgromada.github.io/MathParser.org-mXparser/\n" +
" http://mxparser.sourceforge.net/\n" +
" http://bitbucket.org/mariuszgromada/mxparser/\n" +
" http://mxparser.codeplex.com/\n" +
" http://janetsudoku.mariuszgromada.org/\n"
;
/**
* Gets license info
*
* @return license info as string.
*/
public String getLicense() {
return mXparser.LICENSE;
}
/**
* Waits given number of milliseconds
*
* @param n Number of milliseconds
*/
public static void wait(int n) {
long t0, t1;
t0 = DateTime.Now.Millisecond;
do {
t1 = DateTime.Now.Millisecond;
} while (t1 - t0 < n);
}
}
}
| |
//#define UNITY_ANDROID
//#define UNITY_IOS
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using AudienceNetwork.Utility;
namespace AudienceNetwork
{
public delegate void FBNativeAdBridgeCallback();
public delegate void FBNativeAdBridgeErrorCallback(string error);
internal delegate void FBNativeAdBridgeExternalCallback(int uniqueId);
internal delegate void FBNativeAdBridgeErrorExternalCallback(int uniqueId, string error);
public sealed class NativeAd : IDisposable
{
private int uniqueId;
private bool isLoaded;
private int minViewabilityPercentage;
internal const float MIN_ALPHA = 0.9f;
internal const int MAX_ROTATION = 45;
internal const int CHECK_VIEWABILITY_INTERVAL = 1;
private NativeAdHandler handler;
public string PlacementId { get; private set; }
public string Title { get; private set; }
public string Subtitle { get; private set; }
public string Body { get; private set; }
public string CallToAction { get; private set; }
public string SocialContext { get; private set; }
public string IconImageURL { get; private set; }
public string CoverImageURL { get; private set; }
public Sprite IconImage { get; private set; }
public Sprite CoverImage { get; private set; }
public FBNativeAdBridgeCallback NativeAdDidLoad
{
internal get
{
return this.nativeAdDidLoad;
}
set
{
this.nativeAdDidLoad = value;
NativeAdBridge.Instance.OnLoad(uniqueId, nativeAdDidLoad);
}
}
public FBNativeAdBridgeCallback NativeAdWillLogImpression
{
internal get
{
return this.nativeAdWillLogImpression;
}
set
{
this.nativeAdWillLogImpression = value;
NativeAdBridge.Instance.OnImpression(uniqueId, nativeAdWillLogImpression);
}
}
public FBNativeAdBridgeErrorCallback NativeAdDidFailWithError
{
internal get
{
return this.nativeAdDidFailWithError;
}
set
{
this.nativeAdDidFailWithError = value;
NativeAdBridge.Instance.OnError(uniqueId, nativeAdDidFailWithError);
}
}
public FBNativeAdBridgeCallback NativeAdDidClick
{
internal get
{
return this.nativeAdDidClick;
}
set
{
this.nativeAdDidClick = value;
NativeAdBridge.Instance.OnClick(uniqueId, nativeAdDidClick);
}
}
public FBNativeAdBridgeCallback NativeAdDidFinishHandlingClick
{
internal get
{
return this.nativeAdDidFinishHandlingClick;
}
set
{
this.nativeAdDidFinishHandlingClick = value;
NativeAdBridge.Instance.OnFinishedClick(uniqueId, nativeAdDidFinishHandlingClick);
}
}
private FBNativeAdBridgeCallback nativeAdDidLoad;
private FBNativeAdBridgeCallback nativeAdWillLogImpression;
private FBNativeAdBridgeErrorCallback nativeAdDidFailWithError;
private FBNativeAdBridgeCallback nativeAdDidClick;
private FBNativeAdBridgeCallback nativeAdDidFinishHandlingClick;
public NativeAd(string placementId)
{
this.PlacementId = placementId;
uniqueId = NativeAdBridge.Instance.Create(placementId, this);
NativeAdBridge.Instance.OnLoad(uniqueId, NativeAdDidLoad);
NativeAdBridge.Instance.OnImpression(uniqueId, NativeAdWillLogImpression);
NativeAdBridge.Instance.OnClick(uniqueId, NativeAdDidClick);
NativeAdBridge.Instance.OnError(uniqueId, NativeAdDidFailWithError);
NativeAdBridge.Instance.OnFinishedClick(uniqueId, NativeAdDidFinishHandlingClick);
}
~NativeAd()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(Boolean iAmBeingCalledFromDisposeAndNotFinalize)
{
if (this.handler)
{
this.handler.stopImpressionValidation();
this.handler.removeFromParent();
}
Debug.Log("Native Ad Disposed.");
NativeAdBridge.Instance.Release(uniqueId);
}
public override string ToString()
{
return string.Format(
"[NativeAd: " +
"PlacementId={0}, " +
"Title={1}, " +
"Subtitle={2}, " +
"Body={3}, " +
"CallToAction={4}, " +
"SocialContext={5}, " +
"IconImageURL={6}, " +
"CoverImageURL={7}, " +
"IconImage={8}, " +
"CoverImage={9}, " +
"NativeAdDidLoad={10}, " +
"NativeAdWillLogImpression={11}, " +
"NativeAdDidFailWithError={12}, " +
"NativeAdDidClick={13}, " +
"NativeAdDidFinishHandlingClick={14}]",
PlacementId,
Title,
Subtitle,
Body,
CallToAction,
SocialContext,
IconImageURL,
CoverImageURL,
IconImage,
CoverImage,
NativeAdDidLoad,
NativeAdWillLogImpression,
NativeAdDidFailWithError,
NativeAdDidClick,
NativeAdDidFinishHandlingClick);
}
private static TextureFormat imageFormat()
{
return TextureFormat.RGBA32;
}
public IEnumerator LoadIconImage(string url)
{
Texture2D texture = new Texture2D(4, 4, NativeAd.imageFormat(), false);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(texture);
if (texture)
{
this.IconImage = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
public IEnumerator LoadCoverImage(string url)
{
Texture2D texture = new Texture2D(4, 4, NativeAd.imageFormat(), false);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(texture);
if (texture)
{
this.CoverImage = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
/* Signals the native ad to load data from the server */
public void LoadAd()
{
NativeAdBridge.Instance.Load(this.uniqueId);
}
public bool IsValid()
{
return (this.isLoaded && NativeAdBridge.Instance.IsValid(this.uniqueId));
}
private void RegisterGameObjectForManualImpression(GameObject gameObject)
{
this.createHandler(gameObject);
}
public void RegisterGameObjectForImpression(GameObject gameObject,
Button[] clickableButtons)
{
this.RegisterGameObjectForImpression(gameObject, clickableButtons, Camera.main);
}
public void RegisterGameObjectForImpression(GameObject gameObject,
Button[] clickableButtons,
Camera camera)
{
// Register click handler
foreach (Button button in clickableButtons)
{
button.onClick.RemoveAllListeners();
button.onClick.AddListener(delegate ()
{
AdLogger.Log("Native ad with unique id " + this.uniqueId + " clicked!");
this.ExternalClick();
});
}
this.createHandler(camera, gameObject);
}
public void RegisterGameObjectForImpression(GameObject gameObject, UIButton[] clickableButtons)
{
this.RegisterGameObjectForImpression(gameObject, clickableButtons, Camera.main);
}
public void RegisterGameObjectForImpression(GameObject gameObject, UIButton[] clickableButtons, Camera camera)
{
foreach (UIButton button in clickableButtons)
{
button.onClick.Clear();
button.onClick.Add(new EventDelegate(delegate ()
{
AdLogger.Log("Native ad with unique id " + this.uniqueId + " clicked!");
this.ExternalClick();
}));
}
this.createHandler(camera, gameObject);
}
private void createHandler(GameObject gameObject)
{
this.createHandler(null, gameObject);
}
private void createHandler(Camera camera,
GameObject gameObject)
{
this.handler = gameObject.AddComponent<NativeAdHandler>();
this.handler.camera = camera;
this.handler.minAlpha = NativeAd.MIN_ALPHA;
this.handler.maxRotation = NativeAd.MAX_ROTATION;
this.handler.checkViewabilityInterval = NativeAd.CHECK_VIEWABILITY_INTERVAL;
this.handler.validationCallback = (delegate (bool success)
{
Debug.Log("Native ad viewability check for unique id " + this.uniqueId + " returned success? " + success);
if (success)
{
AdLogger.Log("Native ad with unique id " + this.uniqueId + " registered impression!");
this.ExternalLogImpression();
this.handler.stopImpressionValidation();
}
});
}
private void ManualLogImpression()
{
NativeAdBridge.Instance.ManualLogImpression(this.uniqueId);
}
private void ManualClick()
{
NativeAdBridge.Instance.ManualLogClick(this.uniqueId);
}
internal void ExternalLogImpression()
{
NativeAdBridge.Instance.ExternalLogImpression(this.uniqueId);
}
internal void ExternalClick()
{
NativeAdBridge.Instance.ExternalLogClick(this.uniqueId);
}
internal void loadAdFromData()
{
if (this.handler == null)
{
throw new InvalidOperationException("Native ad was loaded before it was registered. " +
"Ensure RegisterGameObjectForManualImpression () or RegisterGameObjectForImpression () are called.");
}
int uniqueId = this.uniqueId;
this.Title = NativeAdBridge.Instance.GetTitle(uniqueId);
this.Subtitle = NativeAdBridge.Instance.GetSubtitle(uniqueId);
this.Body = NativeAdBridge.Instance.GetBody(uniqueId);
this.CallToAction = NativeAdBridge.Instance.GetCallToAction(uniqueId);
this.SocialContext = NativeAdBridge.Instance.GetSocialContext(uniqueId);
this.CoverImageURL = NativeAdBridge.Instance.GetCoverImageURL(uniqueId);
this.IconImageURL = NativeAdBridge.Instance.GetIconImageURL(uniqueId);
this.isLoaded = true;
this.minViewabilityPercentage = NativeAdBridge.Instance.GetMinViewabilityPercentage(uniqueId);
this.handler.minViewabilityPercentage = this.minViewabilityPercentage;
if (this.NativeAdDidLoad != null)
{
this.handler.executeOnMainThread(() =>
{
this.NativeAdDidLoad();
});
}
this.handler.executeOnMainThread(() =>
{
this.handler.startImpressionValidation();
});
}
internal void executeOnMainThread(Action action)
{
if (this.handler)
{
this.handler.executeOnMainThread(action);
}
}
public static implicit operator bool (NativeAd obj)
{
return !(object.ReferenceEquals(obj, null));
}
}
internal interface INativeAdBridge
{
int Create(string placementId,
NativeAd nativeAd);
int Load(int uniqueId);
bool IsValid(int uniqueId);
string GetTitle(int uniqueId);
string GetSubtitle(int uniqueId);
string GetBody(int uniqueId);
string GetCallToAction(int uniqueId);
string GetSocialContext(int uniqueId);
string GetIconImageURL(int uniqueId);
string GetCoverImageURL(int uniqueId);
int GetMinViewabilityPercentage(int uniqueId);
void ManualLogImpression(int uniqueId);
void ManualLogClick(int uniqueId);
void ExternalLogImpression(int uniqueId);
void ExternalLogClick(int uniqueId);
void Release(int uniqueId);
void OnLoad(int uniqueId,
FBNativeAdBridgeCallback callback);
void OnImpression(int uniqueId,
FBNativeAdBridgeCallback callback);
void OnClick(int uniqueId,
FBNativeAdBridgeCallback callback);
void OnError(int uniqueId,
FBNativeAdBridgeErrorCallback callback);
void OnFinishedClick(int uniqueId,
FBNativeAdBridgeCallback callback);
}
internal class NativeAdBridge : INativeAdBridge
{
/* Interface to native implementation */
internal static readonly string source =
"AudienceNetworkUnityBridge " + AudienceNetwork.SdkVersion.Build + " (Unity " + Application.unityVersion + ")";
public static readonly INativeAdBridge Instance;
private FBNativeAdBridgeCallback onLoadCallback;
private FBNativeAdBridgeCallback onImpressionCallback;
private FBNativeAdBridgeCallback onClickCallback;
private List<NativeAd> nativeAds = new List<NativeAd>();
internal NativeAdBridge()
{
}
static NativeAdBridge()
{
Instance = NativeAdBridge.createInstance();
}
private static INativeAdBridge createInstance()
{
if (Application.platform != RuntimePlatform.OSXEditor)
{
#if UNITY_IOS
return new NativeAdBridgeIOS ();
#elif UNITY_ANDROID
return new NativeAdBridgeAndroid();
#else
return new NativeAdBridge ();
#endif
}
else
{
return new NativeAdBridge();
}
}
public virtual int Create(string placementId,
NativeAd nativeAd)
{
nativeAds.Add(nativeAd);
return nativeAds.Count - 1;
}
public virtual int Load(int uniqueId)
{
NativeAd nativeAd = this.nativeAds[uniqueId];
nativeAd.loadAdFromData();
var callback = this.onLoadCallback;
if (callback != null)
{
callback();
}
return uniqueId;
}
public virtual bool IsValid(int uniqueId)
{
return true;
}
public virtual string GetTitle(int uniqueId)
{
return "Facebook Test Ad";
}
public virtual string GetSubtitle(int uniqueId)
{
return "An ad for Facebook";
}
public virtual string GetBody(int uniqueId)
{
return "Your ad integration works. Woohoo!";
}
public virtual string GetCallToAction(int uniqueId)
{
return "Install Now";
}
public virtual string GetSocialContext(int uniqueId)
{
return "Available on the App Store";
}
public virtual string GetIconImageURL(int uniqueId)
{
return "http://dragon.ak.fbcdn.net/hphotos-ak-prn1/t39.3079-6/851551_836527893040166_1350205352_n.png";
}
public virtual string GetCoverImageURL(int uniqueId)
{
return "http://dragon.ak.fbcdn.net/hphotos-ak-ash3/t39.3079-6/851568_791289324214590_659409906_n.jpg";
}
public virtual int GetMinViewabilityPercentage(int uniqueId)
{
return 1;
}
public virtual void ManualLogImpression(int uniqueId)
{
var callback = this.onImpressionCallback;
if (callback != null)
{
callback();
}
}
public virtual void ManualLogClick(int uniqueId)
{
var callback = this.onClickCallback;
if (callback != null)
{
callback();
}
}
public virtual void ExternalLogImpression(int uniqueId)
{
var callback = this.onImpressionCallback;
if (callback != null)
{
callback();
}
}
public virtual void ExternalLogClick(int uniqueId)
{
var callback = this.onClickCallback;
if (callback != null)
{
callback();
}
}
public virtual void Release(int uniqueId)
{
}
public virtual void OnLoad(int uniqueId,
FBNativeAdBridgeCallback callback)
{
this.onLoadCallback = callback;
}
public virtual void OnImpression(int uniqueId,
FBNativeAdBridgeCallback callback)
{
this.onImpressionCallback = callback;
}
public virtual void OnClick(int uniqueId,
FBNativeAdBridgeCallback callback)
{
this.onClickCallback = callback;
}
public virtual void OnError(int uniqueId,
FBNativeAdBridgeErrorCallback callback)
{
}
public virtual void OnFinishedClick(int uniqueId,
FBNativeAdBridgeCallback callback)
{
}
}
#if UNITY_ANDROID
internal class NativeAdBridgeAndroid : NativeAdBridge
{
private static Dictionary<int, NativeAdContainer> nativeAds = new Dictionary<int, NativeAdContainer>();
private static int lastKey = 0;
private AndroidJavaObject nativeAdForNativeAdId(int uniqueId)
{
NativeAdContainer nativeAdContainer = null;
bool success = NativeAdBridgeAndroid.nativeAds.TryGetValue(uniqueId, out nativeAdContainer);
if (success)
{
return nativeAdContainer.bridgedNativeAd;
}
else
{
return null;
}
}
private string getStringForNativeAdId(int uniqueId,
string method)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
return nativeAd.Call<string>(method);
}
else
{
return null;
}
}
private string getImageURLForNativeAdId(int uniqueId,
string method)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
AndroidJavaObject image = nativeAd.Call<AndroidJavaObject>(method);
if (image != null)
{
return image.Call<string>("getUrl");
}
}
return null;
}
public override int Create(string placementId,
NativeAd nativeAd)
{
AdUtility.prepare();
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
AndroidJavaObject bridgedNativeAd = new AndroidJavaObject("com.facebook.ads.NativeAd", context, placementId);
NativeAdBridgeListenerProxy proxy = new NativeAdBridgeListenerProxy(nativeAd, bridgedNativeAd);
bridgedNativeAd.Call("setAdListener", proxy);
NativeAdBridgeImpressionListenerProxy impressionListenerProxy = new NativeAdBridgeImpressionListenerProxy(nativeAd, bridgedNativeAd);
bridgedNativeAd.Call("setImpressionListener", impressionListenerProxy);
NativeAdContainer nativeAdContainer = new NativeAdContainer(nativeAd);
nativeAdContainer.bridgedNativeAd = bridgedNativeAd;
nativeAdContainer.listenerProxy = proxy;
nativeAdContainer.impressionListenerProxy = impressionListenerProxy;
int key = NativeAdBridgeAndroid.lastKey;
NativeAdBridgeAndroid.nativeAds.Add(key, nativeAdContainer);
NativeAdBridgeAndroid.lastKey++;
return key;
}
public override int Load(int uniqueId)
{
AdUtility.prepare();
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
nativeAd.Call("registerExternalLogReceiver", NativeAdBridge.source);
nativeAd.Call("loadAd");
}
return uniqueId;
}
public override bool IsValid(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
return nativeAd.Call<bool>("isAdLoaded");
}
else
{
return false;
}
}
public override string GetTitle(int uniqueId)
{
return this.getStringForNativeAdId(uniqueId, "getAdTitle");
}
public override string GetSubtitle(int uniqueId)
{
return this.getStringForNativeAdId(uniqueId, "getAdSubtitle");
}
public override string GetBody(int uniqueId)
{
return this.getStringForNativeAdId(uniqueId, "getAdBody");
}
public override string GetCallToAction(int uniqueId)
{
return this.getStringForNativeAdId(uniqueId, "getAdCallToAction");
}
public override string GetSocialContext(int uniqueId)
{
return this.getStringForNativeAdId(uniqueId, "getAdSocialContext");
}
public override string GetIconImageURL(int uniqueId)
{
return this.getImageURLForNativeAdId(uniqueId, "getAdIcon");
}
public override string GetCoverImageURL(int uniqueId)
{
return this.getImageURLForNativeAdId(uniqueId, "getAdCoverImage");
}
public override int GetMinViewabilityPercentage(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
return nativeAd.Call<int>("getMinViewabilityPercentage");
}
return 1;
}
private string getId(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
return nativeAd.Call<string>("getId");
}
else
{
return null;
}
}
public override void ManualLogImpression(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
this.sendIntentToBroadcastManager(uniqueId, "com.facebook.ads.native.impression");
}
}
public override void ManualLogClick(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
this.sendIntentToBroadcastManager(uniqueId, "com.facebook.ads.native.click");
}
}
public override void ExternalLogImpression(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
nativeAd.Call("logExternalImpression");
}
}
public override void ExternalLogClick(int uniqueId)
{
AndroidJavaObject nativeAd = this.nativeAdForNativeAdId(uniqueId);
if (nativeAd != null)
{
nativeAd.Call("logExternalClick", NativeAdBridge.source);
}
}
private bool sendIntentToBroadcastManager(int uniqueId,
string intent)
{
if (intent != null)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject clickIntent = new AndroidJavaObject("android.content.Intent", intent + ":" + getId(uniqueId));
AndroidJavaClass localBroadcastManagerClass = new AndroidJavaClass("android.support.v4.content.LocalBroadcastManager");
AndroidJavaObject localBroadcastManager =
localBroadcastManagerClass.CallStatic<AndroidJavaObject>("getInstance", currentActivity);
return localBroadcastManager.Call<bool>("sendBroadcast", clickIntent);
}
return false;
}
public override void Release(int uniqueId)
{
NativeAdBridgeAndroid.nativeAds.Remove(uniqueId);
}
public override void OnLoad(int uniqueId, FBNativeAdBridgeCallback callback) { }
public override void OnImpression(int uniqueId, FBNativeAdBridgeCallback callback) { }
public override void OnClick(int uniqueId, FBNativeAdBridgeCallback callback) { }
public override void OnError(int uniqueId, FBNativeAdBridgeErrorCallback callback) { }
public override void OnFinishedClick(int uniqueId, FBNativeAdBridgeCallback callback) { }
}
#endif
#if UNITY_IOS
internal class NativeAdBridgeIOS : NativeAdBridge {
private static Dictionary<int, NativeAdContainer> nativeAds = new Dictionary<int, NativeAdContainer>();
private static NativeAdContainer nativeAdContainerForNativeAdId (int uniqueId)
{
NativeAdContainer nativeAd = null;
bool success = NativeAdBridgeIOS.nativeAds.TryGetValue (uniqueId, out nativeAd);
if (success) {
return nativeAd;
} else {
return null;
}
}
[DllImport ("__Internal")]
private static extern int FBNativeAdBridgeCreate (string placementId);
[DllImport ("__Internal")]
private static extern int FBNativeAdBridgeLoad (int uniqueId);
[DllImport ("__Internal")]
private static extern bool FBNativeAdBridgeIsValid (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetTitle (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetSubtitle (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetBody (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetCallToAction (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetSocialContext (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetIconImageURL (int uniqueId);
[DllImport ("__Internal")]
private static extern string FBNativeAdBridgeGetCoverImageURL (int uniqueId);
[DllImport ("__Internal")]
private static extern int FBNativeAdBridgeGetMinViewabilityPercentage (int uniqueId);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeManualLogImpression (int uniqueId);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeManualClick (int uniqueId);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeExternalLogImpression (int uniqueId,
string source);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeExternalClick (int uniqueId,
string source);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeRelease (int uniqueId);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeOnLoad(int uniqueId,
FBNativeAdBridgeExternalCallback callback);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeOnImpression(int uniqueId,
FBNativeAdBridgeExternalCallback callback);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeOnClick(int uniqueId,
FBNativeAdBridgeExternalCallback callback);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeOnError(int uniqueId,
FBNativeAdBridgeErrorExternalCallback callback);
[DllImport ("__Internal")]
private static extern void FBNativeAdBridgeOnFinishedClick(int uniqueId,
FBNativeAdBridgeExternalCallback callback);
public override int Create (string placementId, NativeAd nativeAd)
{
int uniqueId = NativeAdBridgeIOS.FBNativeAdBridgeCreate (placementId);
NativeAdBridgeIOS.nativeAds.Add (uniqueId, new NativeAdContainer(nativeAd));
NativeAdBridgeIOS.FBNativeAdBridgeOnLoad (uniqueId, nativeAdDidLoadBridgeCallback);
NativeAdBridgeIOS.FBNativeAdBridgeOnImpression (uniqueId, nativeAdWillLogImpressionBridgeCallback);
NativeAdBridgeIOS.FBNativeAdBridgeOnClick (uniqueId, nativeAdDidClickBridgeCallback);
NativeAdBridgeIOS.FBNativeAdBridgeOnError (uniqueId, nativeAdDidFailWithErrorBridgeCallback);
NativeAdBridgeIOS.FBNativeAdBridgeOnFinishedClick (uniqueId, nativeAdDidFinishHandlingClickBridgeCallback);
return uniqueId;
}
public override int Load (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeLoad (uniqueId);
}
public override bool IsValid (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeIsValid (uniqueId);
}
public override string GetTitle (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetTitle (uniqueId);
}
public override string GetSubtitle (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetSubtitle (uniqueId);
}
public override string GetBody (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetBody (uniqueId);
}
public override string GetCallToAction (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetCallToAction (uniqueId);
}
public override string GetSocialContext (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetSocialContext (uniqueId);
}
public override string GetIconImageURL (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetIconImageURL (uniqueId);
}
public override string GetCoverImageURL (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetCoverImageURL (uniqueId);
}
public override int GetMinViewabilityPercentage (int uniqueId)
{
return NativeAdBridgeIOS.FBNativeAdBridgeGetMinViewabilityPercentage(uniqueId);
}
public override void ManualLogImpression (int uniqueId)
{
NativeAdBridgeIOS.FBNativeAdBridgeManualLogImpression (uniqueId);
}
public override void ManualLogClick (int uniqueId)
{
NativeAdBridgeIOS.FBNativeAdBridgeManualClick (uniqueId);
}
public override void ExternalLogImpression (int uniqueId)
{
NativeAdBridgeIOS.FBNativeAdBridgeExternalLogImpression (uniqueId, NativeAdBridge.source);
}
public override void ExternalLogClick (int uniqueId)
{
NativeAdBridgeIOS.FBNativeAdBridgeExternalClick (uniqueId, NativeAdBridge.source);
}
public override void Release (int uniqueId)
{
NativeAdBridgeIOS.nativeAds.Remove (uniqueId);
NativeAdBridgeIOS.FBNativeAdBridgeRelease (uniqueId);
}
// Sets up internal managed callbacks
public override void OnLoad (int uniqueId,
FBNativeAdBridgeCallback callback)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container) {
container.onLoad = (delegate() {
container.nativeAd.loadAdFromData ();
if (callback != null) {
callback ();
}
});
}
}
public override void OnImpression (int uniqueId,
FBNativeAdBridgeCallback callback)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container) {
container.onImpression = callback;
}
}
public override void OnClick (int uniqueId,
FBNativeAdBridgeCallback callback)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container) {
container.onClick = callback;
}
}
public override void OnError (int uniqueId,
FBNativeAdBridgeErrorCallback callback)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container) {
container.onError = callback;
}
}
public override void OnFinishedClick (int uniqueId,
FBNativeAdBridgeCallback callback)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container) {
container.onFinishedClick = callback;
}
}
// External unmanaged callbacks (must be static)
[MonoPInvokeCallback (typeof (FBNativeAdBridgeExternalCallback))]
private static void nativeAdDidLoadBridgeCallback(int uniqueId)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container && container.onLoad != null) {
container.onLoad ();
}
}
[MonoPInvokeCallback (typeof (FBNativeAdBridgeExternalCallback))]
private static void nativeAdWillLogImpressionBridgeCallback(int uniqueId)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container && container.onImpression != null) {
container.onImpression ();
}
}
[MonoPInvokeCallback (typeof (FBNativeAdBridgeErrorExternalCallback))]
private static void nativeAdDidFailWithErrorBridgeCallback(int uniqueId, string error)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container && container.onError != null) {
container.onError (error);
}
}
[MonoPInvokeCallback (typeof (FBNativeAdBridgeExternalCallback))]
private static void nativeAdDidClickBridgeCallback(int uniqueId)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container && container.onClick != null) {
container.onClick ();
}
}
[MonoPInvokeCallback (typeof (FBNativeAdBridgeExternalCallback))]
private static void nativeAdDidFinishHandlingClickBridgeCallback(int uniqueId)
{
NativeAdContainer container = NativeAdBridgeIOS.nativeAdContainerForNativeAdId (uniqueId);
if (container && container.onFinishedClick != null) {
container.onFinishedClick ();
}
}
}
#endif
internal class NativeAdContainer
{
internal NativeAd nativeAd { get; set; }
// iOS
internal FBNativeAdBridgeCallback onLoad { get; set; }
internal FBNativeAdBridgeCallback onImpression { get; set; }
internal FBNativeAdBridgeCallback onClick { get; set; }
internal FBNativeAdBridgeErrorCallback onError { get; set; }
internal FBNativeAdBridgeCallback onFinishedClick { get; set; }
// Android
#if UNITY_ANDROID
internal AndroidJavaProxy listenerProxy;
internal AndroidJavaObject bridgedNativeAd;
internal AndroidJavaProxy impressionListenerProxy;
#endif
internal NativeAdContainer(NativeAd nativeAd)
{
this.nativeAd = nativeAd;
}
public static implicit operator bool (NativeAdContainer obj)
{
return !(object.ReferenceEquals(obj, null));
}
}
#if UNITY_ANDROID
internal class NativeAdBridgeListenerProxy : AndroidJavaProxy
{
private NativeAd nativeAd;
#pragma warning disable 0414
private AndroidJavaObject bridgedNativeAd;
#pragma warning restore 0414
public NativeAdBridgeListenerProxy(NativeAd nativeAd, AndroidJavaObject bridgedNativeAd)
: base("com.facebook.ads.AdListener")
{
this.nativeAd = nativeAd;
this.bridgedNativeAd = bridgedNativeAd;
}
void onError(AndroidJavaObject ad, AndroidJavaObject error)
{
string errorMessage = error.Call<string>("getErrorMessage");
this.nativeAd.executeOnMainThread(() =>
{
if (nativeAd.NativeAdDidFailWithError != null)
{
nativeAd.NativeAdDidFailWithError(errorMessage);
}
});
}
void onAdLoaded(AndroidJavaObject ad)
{
this.nativeAd.executeOnMainThread(() =>
{
nativeAd.loadAdFromData();
if (nativeAd.NativeAdDidLoad != null)
{
nativeAd.NativeAdDidLoad();
}
});
}
void onAdClicked(AndroidJavaObject ad)
{
this.nativeAd.executeOnMainThread(() =>
{
if (nativeAd.NativeAdDidClick != null)
{
nativeAd.NativeAdDidClick();
}
});
}
void onLoggingImpression(AndroidJavaObject ad)
{
this.nativeAd.executeOnMainThread(() =>
{
if (nativeAd.NativeAdWillLogImpression != null)
{
nativeAd.NativeAdWillLogImpression();
}
});
}
}
internal class NativeAdBridgeImpressionListenerProxy : AndroidJavaProxy
{
private NativeAd nativeAd;
#pragma warning disable 0414
private AndroidJavaObject bridgedNativeAd;
#pragma warning restore 0414
public NativeAdBridgeImpressionListenerProxy(NativeAd nativeAd, AndroidJavaObject bridgedNativeAd)
: base("com.facebook.ads.ImpressionListener")
{
this.nativeAd = nativeAd;
this.bridgedNativeAd = bridgedNativeAd;
}
void onLoggingImpression(AndroidJavaObject ad)
{
this.nativeAd.executeOnMainThread(() =>
{
if (nativeAd.NativeAdWillLogImpression != null)
{
nativeAd.NativeAdWillLogImpression();
}
});
}
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
namespace System.Data
{
/// <summary>
/// Provides an entry point so that Cast operator call can be intercepted within an extension method.
/// </summary>
public abstract class EnumerableRowCollection : IEnumerable
{
internal abstract Type ElementType { get; }
internal abstract DataTable Table { get; }
internal EnumerableRowCollection()
{
}
IEnumerator IEnumerable.GetEnumerator()
{
return null;
}
}
/// <summary>
/// This class provides a wrapper for DataTables to allow for querying via LINQ.
/// </summary>
public class EnumerableRowCollection<TRow> : EnumerableRowCollection, IEnumerable<TRow>
{
private readonly DataTable _table;
private readonly IEnumerable<TRow> _enumerableRows;
private readonly List<Func<TRow, bool>> _listOfPredicates;
// Stores list of sort expression in the order provided by user. E.g. order by, thenby, thenby descending..
private readonly SortExpressionBuilder<TRow> _sortExpression;
private readonly Func<TRow, TRow> _selector;
internal override Type ElementType
{
get
{
return typeof(TRow);
}
}
internal IEnumerable<TRow> EnumerableRows
{
get
{
return _enumerableRows;
}
}
internal override DataTable Table
{
get
{
return _table;
}
}
/// <summary>
/// This constructor is used when Select operator is called with output Type other than input row Type.
/// Basically fail on GetLDV(), but other LINQ operators must work.
/// </summary>
internal EnumerableRowCollection(IEnumerable<TRow> enumerableRows, bool isDataViewable, DataTable table)
{
Debug.Assert(!isDataViewable || table != null, "isDataViewable bug table is null");
_enumerableRows = enumerableRows;
if (isDataViewable)
{
_table = table;
}
_listOfPredicates = new List<Func<TRow, bool>>();
_sortExpression = new SortExpressionBuilder<TRow>();
}
/// <summary>
/// Basic Constructor
/// </summary>
internal EnumerableRowCollection(DataTable table)
{
_table = table;
_enumerableRows = table.Rows.Cast<TRow>();
_listOfPredicates = new List<Func<TRow, bool>>();
_sortExpression = new SortExpressionBuilder<TRow>();
}
/// <summary>
/// Copy Constructor that sets the input IEnumerable as enumerableRows
/// Used to maintain IEnumerable that has linq operators executed in the same order as the user
/// </summary>
internal EnumerableRowCollection(EnumerableRowCollection<TRow> source, IEnumerable<TRow> enumerableRows, Func<TRow, TRow> selector)
{
Debug.Assert(null != enumerableRows, "null enumerableRows");
_enumerableRows = enumerableRows;
_selector = selector;
if (null != source)
{
if (null == source._selector)
{
_table = source._table;
}
_listOfPredicates = new List<Func<TRow, bool>>(source._listOfPredicates);
//deep copy the List
_sortExpression = source._sortExpression.Clone();
}
else
{
_listOfPredicates = new List<Func<TRow, bool>>();
_sortExpression = new SortExpressionBuilder<TRow>();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// This method returns an strongly typed iterator
/// for the underlying DataRow collection.
/// </summary>
/// <returns>A strongly typed iterator.</returns>
public IEnumerator<TRow> GetEnumerator()
{
return _enumerableRows.GetEnumerator();
}
/// <summary>
/// Evaluates filter and sort if necessary and returns
/// a LinqDataView representing the LINQ query this class has collected.
/// </summary>
/// <returns>LinqDataView repesenting the LINQ query</returns>
internal LinqDataView GetLinqDataView() // Called by AsLinqDataView
{
if ((null == _table) || !typeof(DataRow).IsAssignableFrom(typeof(TRow)))
{
throw DataSetUtil.NotSupported(SR.ToLDVUnsupported);
}
LinqDataView view = null;
#region BuildSinglePredicate
Func<DataRow, bool> finalPredicate = null; // Conjunction of all .Where(..) predicates
if ((null != _selector) && (0 < _listOfPredicates.Count))
{
// Hook up all individual predicates into one predicate
// This lambda is a conjunction of multiple predicates set by the user
// Note: This is a Short-Circuit Conjunction
finalPredicate =
(DataRow row) =>
{
if (!object.ReferenceEquals(row, _selector((TRow)(object)row)))
{
throw DataSetUtil.NotSupported(SR.ToLDVUnsupported);
}
foreach (Func<TRow, bool> pred in _listOfPredicates)
{
if (!pred((TRow)(object)row))
{
return false;
}
}
return true;
};
}
else if (null != _selector)
{
finalPredicate =
(DataRow row) =>
{
if (!object.ReferenceEquals(row, _selector((TRow)(object)row)))
{
throw DataSetUtil.NotSupported(SR.ToLDVUnsupported);
}
return true;
};
}
else if (0 < _listOfPredicates.Count)
{
finalPredicate =
(DataRow row) =>
{
foreach (Func<TRow, bool> pred in _listOfPredicates)
{
if (!pred((TRow)(object)row))
{
return false;
}
}
return true;
};
}
#endregion BuildSinglePredicate
#region Evaluate Filter/Sort
// All of this complexity below is because we want to create index only once.
//
// If we only have filter, we set _view.Predicate - 1 index creation
// If we only have sort, we set _view.SortExpression() - 1 index creation
// If we have BOTH, we set them through the constructor - 1 index creation
//
// Filter AND Sort
if ((null != finalPredicate) && (0 < _sortExpression.Count))
{
// A lot more work here because constructor does not know type K,
// so the responsibility to create appropriate delegate comparers
// is outside of the constructor.
view = new LinqDataView(
_table,
row => finalPredicate(row), // System.Predicate
(DataRow a, DataRow b) => // Comparison for DV for Index creation
_sortExpression.Compare(
_sortExpression.Select((TRow)(object)a),
_sortExpression.Select((TRow)(object)b)),
(object key, DataRow row) => // Comparison_K_T for DV's Find()
_sortExpression.Compare(
(List<object>)key,
_sortExpression.Select((TRow)(object)row)),
_sortExpression.CloneCast<DataRow>());
}
else if (null != finalPredicate)
{
// Only Filtering
view = new LinqDataView(
_table,
row => finalPredicate(row), // System.Predicate
null,
null,
_sortExpression.CloneCast<DataRow>());
}
else if (0 < _sortExpression.Count)
{
// Only Sorting
view = new LinqDataView(
_table,
null,
(DataRow a, DataRow b) =>
_sortExpression.Compare(
_sortExpression.Select((TRow)(object)a),
_sortExpression.Select((TRow)(object)b)),
(object key, DataRow row) =>
_sortExpression.Compare(
(List<object>)key,
_sortExpression.Select((TRow)(object)row)),
_sortExpression.CloneCast<DataRow>());
}
else
{
view = new LinqDataView(_table, _sortExpression.CloneCast<DataRow>());
}
#endregion Evaluate Filter and Sort
return view;
}
/// <summary>
/// Used to add a filter predicate.
/// A conjunction of all predicates are evaluated in LinqDataView
/// </summary>
internal void AddPredicate(Func<TRow, bool> pred)
{
Debug.Assert(pred != null);
_listOfPredicates.Add(pred);
}
/// <summary>
/// Adds a sort expression when Keyselector is provided but not Comparer
/// </summary>
internal void AddSortExpression<TKey>(Func<TRow, TKey> keySelector, bool isDescending, bool isOrderBy)
{
AddSortExpression<TKey>(keySelector, Comparer<TKey>.Default, isDescending, isOrderBy);
}
/// <summary>
/// Adds a sort expression when Keyselector and Comparer are provided.
/// </summary>
internal void AddSortExpression<TKey>(Func<TRow, TKey> keySelector, IComparer<TKey> comparer, bool isDescending, bool isOrderBy)
{
DataSetUtil.CheckArgumentNull(keySelector, nameof(keySelector));
DataSetUtil.CheckArgumentNull(comparer, nameof(comparer));
_sortExpression.Add(
delegate (TRow input)
{
return keySelector(input);
},
delegate (object val1, object val2)
{
return (isDescending ? -1 : 1) * comparer.Compare((TKey)val1, (TKey)val2);
},
isOrderBy);
}
}
}
| |
// 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 Internal.Runtime;
namespace System.Runtime
{
internal unsafe static class DispatchResolve
{
// CS0649: Field '{blah}' is never assigned to, and will always have its default value
#pragma warning disable 649
public struct DispatchMapEntry
{
public ushort _usInterfaceIndex;
public ushort _usInterfaceMethodSlot;
public ushort _usImplMethodSlot;
}
public struct DispatchMap
{
public uint _entryCount;
public DispatchMapEntry _dispatchMap; // Actually a variable length array
}
#pragma warning restore
public static IntPtr FindInterfaceMethodImplementationTarget(EEType* pTgtType,
EEType* pItfType,
ushort itfSlotNumber)
{
// Start at the current type and work up the inheritance chain
EEType* pCur = pTgtType;
UInt32 iCurInheritanceChainDelta = 0;
if (pItfType->IsCloned)
pItfType = pItfType->CanonicalEEType;
while (pCur != null)
{
UInt16 implSlotNumber;
if (FindImplSlotForCurrentType(
pCur, pItfType, itfSlotNumber, &implSlotNumber))
{
IntPtr targetMethod;
if (implSlotNumber < pCur->NumVtableSlots)
{
// true virtual - need to get the slot from the target type in case it got overridden
targetMethod = pTgtType->GetVTableStartAddress()[implSlotNumber];
}
else
{
// sealed virtual - need to get the slot form the implementing type, because
// it's not present on the target type
targetMethod = pCur->GetSealedVirtualSlot((ushort)(implSlotNumber - pCur->NumVtableSlots));
}
return targetMethod;
}
if (pCur->IsArray)
pCur = pCur->GetArrayEEType();
else
pCur = pCur->NonArrayBaseType;
iCurInheritanceChainDelta++;
}
return IntPtr.Zero;
}
private static bool FindImplSlotForCurrentType(EEType* pTgtType,
EEType* pItfType,
UInt16 itfSlotNumber,
UInt16* pImplSlotNumber)
{
bool fRes = false;
// If making a call and doing virtual resolution don't look into the dispatch map,
// take the slot number directly.
if (!pItfType->IsInterface)
{
*pImplSlotNumber = itfSlotNumber;
// Only notice matches if the target type and search types are the same
// This will make dispatch to sealed slots work correctly
return pTgtType == pItfType;
}
if (pTgtType->HasDispatchMap)
{
// For variant interface dispatch, the algorithm is to walk the parent hierarchy, and at each level
// attempt to dispatch exactly first, and then if that fails attempt to dispatch variantly. This can
// result in interesting behavior such as a derived type only overriding one particular instantiation
// and funneling all the dispatches to it, but its the algorithm.
bool fDoVariantLookup = false; // do not check variance for first scan of dispatch map
fRes = FindImplSlotInSimpleMap(
pTgtType, pItfType, itfSlotNumber, pImplSlotNumber, fDoVariantLookup);
if (!fRes)
{
fDoVariantLookup = true; // check variance for second scan of dispatch map
fRes = FindImplSlotInSimpleMap(
pTgtType, pItfType, itfSlotNumber, pImplSlotNumber, fDoVariantLookup);
}
}
return fRes;
}
private static bool FindImplSlotInSimpleMap(EEType* pTgtType,
EEType* pItfType,
UInt32 itfSlotNumber,
UInt16* pImplSlotNumber,
bool actuallyCheckVariance)
{
Debug.Assert(pTgtType->HasDispatchMap, "Missing dispatch map");
EEType* pItfOpenGenericType = null;
EETypeRef* pItfInstantiation = null;
int itfArity = 0;
GenericVariance* pItfVarianceInfo = null;
bool fCheckVariance = false;
bool fArrayCovariance = false;
if (actuallyCheckVariance)
{
fCheckVariance = pItfType->HasGenericVariance;
fArrayCovariance = pTgtType->IsArray;
// Non-arrays can follow array variance rules iff
// 1. They have one generic parameter
// 2. That generic parameter is array covariant.
//
// This special case is to allow array enumerators to work
if (!fArrayCovariance && pTgtType->HasGenericVariance)
{
int tgtEntryArity = (int)pTgtType->GenericArity;
GenericVariance* pTgtVarianceInfo = pTgtType->GenericVariance;
if ((tgtEntryArity == 1) && pTgtVarianceInfo[0] == GenericVariance.ArrayCovariant)
{
fArrayCovariance = true;
}
}
// Arrays are covariant even though you can both get and set elements (type safety is maintained by
// runtime type checks during set operations). This extends to generic interfaces implemented on those
// arrays. We handle this by forcing all generic interfaces on arrays to behave as though they were
// covariant (over their one type parameter corresponding to the array element type).
if (fArrayCovariance && pItfType->IsGeneric)
fCheckVariance = true;
// If there is no variance checking, there is no operation to perform. (The non-variance check loop
// has already completed)
if (!fCheckVariance)
{
return false;
}
}
DispatchMap* pMap = pTgtType->DispatchMap;
DispatchMapEntry* i = &pMap->_dispatchMap;
DispatchMapEntry* iEnd = (&pMap->_dispatchMap) + pMap->_entryCount;
for (; i != iEnd; ++i)
{
if (i->_usInterfaceMethodSlot == itfSlotNumber)
{
EEType* pCurEntryType =
pTgtType->InterfaceMap[i->_usInterfaceIndex].InterfaceType;
if (pCurEntryType->IsCloned)
pCurEntryType = pCurEntryType->CanonicalEEType;
if (pCurEntryType == pItfType)
{
*pImplSlotNumber = i->_usImplMethodSlot;
return true;
}
else if (fCheckVariance && ((fArrayCovariance && pCurEntryType->IsGeneric) || pCurEntryType->HasGenericVariance))
{
// Interface types don't match exactly but both the target interface and the current interface
// in the map are marked as being generic with at least one co- or contra- variant type
// parameter. So we might still have a compatible match.
// Retrieve the unified generic instance for the callsite interface if we haven't already (we
// lazily get this then cache the result since the lookup isn't necessarily cheap).
if (pItfOpenGenericType == null)
{
pItfOpenGenericType = pItfType->GenericDefinition;
itfArity = (int)pItfType->GenericArity;
pItfInstantiation = pItfType->GenericArguments;
pItfVarianceInfo = pItfType->GenericVariance;
}
// Retrieve the unified generic instance for the interface we're looking at in the map.
EEType* pCurEntryGenericType = pCurEntryType->GenericDefinition;
// If the generic types aren't the same then the types aren't compatible.
if (pItfOpenGenericType != pCurEntryGenericType)
continue;
// Grab instantiation details for the candidate interface.
EETypeRef* pCurEntryInstantiation = pCurEntryType->GenericArguments;
int curEntryArity = (int)pCurEntryType->GenericArity;
GenericVariance* pCurEntryVarianceInfo = pCurEntryType->GenericVariance;
// The types represent different instantiations of the same generic type. The
// arity of both had better be the same.
Debug.Assert(itfArity == curEntryArity, "arity mismatch betweeen generic instantiations");
if (TypeCast.TypeParametersAreCompatible(itfArity, pCurEntryInstantiation, pItfInstantiation, pItfVarianceInfo, fArrayCovariance))
{
*pImplSlotNumber = i->_usImplMethodSlot;
return true;
}
}
}
}
return false;
}
}
}
| |
//
// LastfmSourceContents.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008-2009 Novell, Inc.
//
// 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 Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
using Lastfm;
using Lastfm.Data;
namespace Banshee.Lastfm
{
public class LastfmSourceContents : Hyena.Widgets.ScrolledWindow, ISourceContents
{
private VBox main_box;
private LastfmSource lastfm;
private NumberedList recently_loved;
private NumberedList recently_played;
private NumberedList top_artists;
private Viewport viewport;
// "Coming Soon: Profile, Friends, Events etc")
public LastfmSourceContents () : base ()
{
HscrollbarPolicy = PolicyType.Never;
VscrollbarPolicy = PolicyType.Automatic;
viewport = new Viewport ();
viewport.ShadowType = ShadowType.None;
main_box = new VBox ();
main_box.Spacing = 6;
main_box.BorderWidth = 5;
main_box.ReallocateRedraws = true;
// Clamp the width, preventing horizontal scrolling
SizeAllocated += delegate (object o, SizeAllocatedArgs args) {
// TODO '- 10' worked for Nereid, but not for Cubano; properly calculate the right width we should request
main_box.WidthRequest = args.Allocation.Width - 30;
};
viewport.Add (main_box);
StyleSet += delegate {
viewport.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
viewport.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
AddWithFrame (viewport);
ShowAll ();
}
public bool SetSource (ISource src)
{
lastfm = src as LastfmSource;
if (lastfm == null) {
return false;
}
if (lastfm.Connection.Connected) {
UpdateForUser (lastfm.Account.UserName);
} else {
lastfm.Connection.StateChanged += HandleConnectionStateChanged;
}
return true;
}
public ISource Source {
get { return lastfm; }
}
public void ResetSource ()
{
lastfm = null;
}
public Widget Widget {
get { return this; }
}
public void Refresh ()
{
if (user != null) {
user.RecentLovedTracks.Refresh ();
user.RecentTracks.Refresh ();
user.GetTopArtists (TopType.Overall).Refresh ();
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
}
}
private string last_user;
private LastfmUserData user;
private void UpdateForUser (string username)
{
if (username == last_user) {
return;
}
last_user = username;
while (main_box.Children.Length != 0) {
main_box.Remove (main_box.Children[0]);
}
recently_loved = new NumberedList (lastfm, Catalog.GetString ("Recently Loved Tracks"));
recently_played = new NumberedList (lastfm, Catalog.GetString ("Recently Played Tracks"));
top_artists = new NumberedList (lastfm, Catalog.GetString ("My Top Artists"));
//recommended_artists = new NumberedList (Catalog.GetString ("Recommended Artists"));
main_box.PackStart (recently_loved, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (recently_played, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (top_artists, false, false, 0);
//PackStart (recommended_artists, true, true, 0);
try {
user = new LastfmUserData (username);
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
} catch (Exception e) {
lastfm.SetStatus ("Failed to get information from your Last.fm profile", true, ConnectionState.InvalidAccount);
Log.Exception (String.Format ("LastfmUserData query failed for {0}", username), e);
}
ShowAll ();
}
private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args)
{
if (args.State == ConnectionState.Connected) {
ThreadAssist.ProxyToMain (delegate {
if (lastfm != null && lastfm.Account != null) {
UpdateForUser (lastfm.Account.UserName);
}
});
}
}
public class NumberedTileView : TileView
{
private int i = 1;
public NumberedTileView (int cols) : base (cols)
{
}
public new void ClearWidgets ()
{
i = 1;
base.ClearWidgets ();
}
public void AddNumberedWidget (Tile tile)
{
tile.PrimaryText = String.Format ("{0}. {1}", i++, tile.PrimaryText);
AddWidget (tile);
}
}
protected class NumberedList : TitledList
{
protected ArtworkManager artwork_manager = ServiceManager.Get<ArtworkManager> ();
protected LastfmSource lastfm;
protected NumberedTileView tile_view;
protected Dictionary<object, RecentTrack> widget_track_map = new Dictionary<object, RecentTrack> ();
public NumberedList (LastfmSource lastfm, string name) : base (name)
{
this.lastfm = lastfm;
artwork_manager.AddCachedSize(40);
tile_view = new NumberedTileView (1);
PackStart (tile_view, true, true, 0);
tile_view.Show ();
StyleSet += delegate {
tile_view.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
tile_view.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
}
// TODO generalize this
public void SetList (LastfmData<UserTopArtist> artists)
{
tile_view.ClearWidgets ();
foreach (UserTopArtist artist in artists) {
MenuTile tile = new MenuTile ();
tile.PrimaryText = artist.Name;
tile.SecondaryText = String.Format (Catalog.GetString ("{0} plays"), artist.PlayCount);
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
public void SetList (LastfmData<RecentTrack> tracks)
{
tile_view.ClearWidgets ();
foreach (RecentTrack track in tracks) {
MenuTile tile = new MenuTile ();
widget_track_map [tile] = track;
tile.PrimaryText = track.Name;
tile.SecondaryText = track.Artist;
tile.ButtonPressEvent += OnTileActivated;
// Unfortunately the recently loved list doesn't include what album the song is on
if (!String.IsNullOrEmpty (track.Album)) {
AlbumInfo album = new AlbumInfo (track.Album);
album.ArtistName = track.Artist;
Gdk.Pixbuf pb = artwork_manager == null ? null : artwork_manager.LookupScalePixbuf (album.ArtworkId, 40);
if (pb != null) {
tile.Pixbuf = pb;
}
}
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
private void OnTileActivated (object sender, EventArgs args)
{
(sender as Button).Relief = ReliefStyle.Normal;
RecentTrack track = widget_track_map [sender];
lastfm.Actions.CurrentArtist = track.Artist;
lastfm.Actions.CurrentAlbum = track.Album;
lastfm.Actions.CurrentTrack = track.Name;
Gtk.Menu menu = ServiceManager.Get<InterfaceActionService> ().UIManager.GetWidget ("/LastfmTrackPopup") as Menu;
// For an event
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Add to Google Calendar"));
// For a user
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Listen to Recommended Station"));
//menu.Append (new MenuItem ("Listen to Loved Station"));
//menu.Append (new MenuItem ("Listen to Neighbors Station"));
menu.ShowAll ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.Deactivated += delegate {
(sender as Button).Relief = ReliefStyle.None;
};
}
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// CertificateOperations operations.
/// </summary>
internal partial class CertificateOperations : Microsoft.Rest.IServiceOperations<BatchServiceClient>, ICertificateOperations
{
/// <summary>
/// Initializes a new instance of the CertificateOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CertificateOperations(BatchServiceClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the BatchServiceClient
/// </summary>
public BatchServiceClient Client { get; private set; }
/// <summary>
/// Adds a certificate to the specified account.
/// </summary>
/// <param name='certificate'>
/// The certificate to be added.
/// </param>
/// <param name='certificateAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateAddHeaders>> AddWithHttpMessagesAsync(CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (certificate == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "certificate");
}
if (certificate != null)
{
certificate.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateAddOptions != null)
{
timeout = certificateAddOptions.Timeout;
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateAddOptions != null)
{
clientRequestId = certificateAddOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateAddOptions != null)
{
returnClientRequestId = certificateAddOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateAddOptions != null)
{
ocpDate = certificateAddOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("certificate", certificate);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
if(certificate != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(certificate, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateAddHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateAddHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='certificateListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>> ListWithHttpMessagesAsync(CertificateListOptions certificateListOptions = default(CertificateListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string filter = default(string);
if (certificateListOptions != null)
{
filter = certificateListOptions.Filter;
}
string select = default(string);
if (certificateListOptions != null)
{
select = certificateListOptions.Select;
}
int? maxResults = default(int?);
if (certificateListOptions != null)
{
maxResults = certificateListOptions.MaxResults;
}
int? timeout = default(int?);
if (certificateListOptions != null)
{
timeout = certificateListOptions.Timeout;
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateListOptions != null)
{
clientRequestId = certificateListOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateListOptions != null)
{
returnClientRequestId = certificateListOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateListOptions != null)
{
ocpDate = certificateListOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("filter", filter);
tracingParameters.Add("select", select);
tracingParameters.Add("maxResults", maxResults);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (maxResults != null)
{
_queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Certificate>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateListHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Cancels a failed deletion of a certificate from the specified account.
/// </summary>
/// <remarks>
/// If you try to delete a certificate that is being used by a pool or compute
/// node, the status of the certificate changes to deleteFailed. If you decide
/// that you want to continue using the certificate, you can use this operation
/// to set the status of the certificate back to active. If you intend to
/// delete the certificate, you do not need to run this operation after the
/// deletion failed. You must make sure that the certificate is not being used
/// by any resources, and then you can try again to delete the certificate.
/// </remarks>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate being deleted.
/// </param>
/// <param name='certificateCancelDeletionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateCancelDeletionHeaders>> CancelDeletionWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateCancelDeletionOptions != null)
{
timeout = certificateCancelDeletionOptions.Timeout;
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateCancelDeletionOptions != null)
{
clientRequestId = certificateCancelDeletionOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateCancelDeletionOptions != null)
{
returnClientRequestId = certificateCancelDeletionOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateCancelDeletionOptions != null)
{
ocpDate = certificateCancelDeletionOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CancelDeletion", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateCancelDeletionHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateCancelDeletionHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a certificate from the specified account.
/// </summary>
/// <remarks>
/// You cannot delete a certificate if a resource (pool or compute node) is
/// using it. Before you can delete a certificate, you must therefore make sure
/// that the certificate is not associated with any existing pools, the
/// certificate is not installed on any compute nodes (even if you remove a
/// certificate from a pool, it is not removed from existing compute nodes in
/// that pool until they restart), and no running tasks depend on the
/// certificate. If you try to delete a certificate that is in use, the
/// deletion fails. The certificate status changes to deleteFailed. You can use
/// Cancel Delete Certificate to set the status back to active if you decide
/// that you want to continue using the certificate.
/// </remarks>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to be deleted.
/// </param>
/// <param name='certificateDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateDeleteHeaders>> DeleteWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
int? timeout = default(int?);
if (certificateDeleteOptions != null)
{
timeout = certificateDeleteOptions.Timeout;
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateDeleteOptions != null)
{
clientRequestId = certificateDeleteOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateDeleteOptions != null)
{
returnClientRequestId = certificateDeleteOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateDeleteOptions != null)
{
ocpDate = certificateDeleteOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<CertificateDeleteHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateDeleteHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets information about the specified certificate.
/// </summary>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to get.
/// </param>
/// <param name='certificateGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Certificate,CertificateGetHeaders>> GetWithHttpMessagesAsync(string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (thumbprintAlgorithm == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprintAlgorithm");
}
if (thumbprint == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "thumbprint");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string select = default(string);
if (certificateGetOptions != null)
{
select = certificateGetOptions.Select;
}
int? timeout = default(int?);
if (certificateGetOptions != null)
{
timeout = certificateGetOptions.Timeout;
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateGetOptions != null)
{
clientRequestId = certificateGetOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateGetOptions != null)
{
returnClientRequestId = certificateGetOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateGetOptions != null)
{
ocpDate = certificateGetOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("thumbprintAlgorithm", thumbprintAlgorithm);
tracingParameters.Add("thumbprint", thumbprint);
tracingParameters.Add("select", select);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})").ToString();
_url = _url.Replace("{thumbprintAlgorithm}", System.Uri.EscapeDataString(thumbprintAlgorithm));
_url = _url.Replace("{thumbprint}", System.Uri.EscapeDataString(thumbprint));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Certificate,CertificateGetHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Certificate>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateGetHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='certificateListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
System.Guid? clientRequestId = default(System.Guid?);
if (certificateListNextOptions != null)
{
clientRequestId = certificateListNextOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (certificateListNextOptions != null)
{
returnClientRequestId = certificateListNextOptions.ReturnClientRequestId;
}
System.DateTime? ocpDate = default(System.DateTime?);
if (certificateListNextOptions != null)
{
ocpDate = certificateListNextOptions.OcpDate;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
}
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 = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Certificate>,CertificateListHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Certificate>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<CertificateListHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Runtime.CompilerServices;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaUtils
{
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string adjustForNameSearch(string target)
{
int lth = target.Length;
if (lth == 0)
{
return "";
}
//target = target.ToUpper();
string rtn = target.Substring(0, lth - 1);
char c = target[lth - 1];
int asciiCode = (byte)c - 1;
c = (char)asciiCode;
rtn = rtn + c + '~';
return rtn;
}
/// <summary>
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string adjustForNumericSearch(string target)
{
Int64 iTarget = Convert.ToInt64(target);
return Convert.ToString(iTarget - 1);
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string setDirectionParam(string direction)
{
if (String.IsNullOrEmpty(direction))
{
return "1";
}
if (!String.Equals(direction, "1") && !String.Equals(direction, "-1"))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid direction. Must be 1 or -1.");
}
return direction;
}
// These 2 methods should be reduced to one where only dfn and arg are required, the other args optional.
// Problem with doing that now is you can't null an int (nrpts).
//[MethodImpl(MethodImplOptions.Synchronized)]
public static MdoQuery buildReportTextRequest(string dfn, string fromDate, string toDate, int nrpts, string arg)
{
if (String.IsNullOrEmpty(fromDate) || fromDate.Equals("0"))
{
fromDate = DateUtils.MinDate;
}
if (String.IsNullOrEmpty(toDate))
{
toDate = "0";
}
CheckRpcParams(dfn, fromDate, toDate);
if (String.IsNullOrEmpty(arg))
{
throw new NullOrEmptyParamException("routine name");
}
VistaQuery vq = new VistaQuery("ORWRP REPORT TEXT");
vq.addParameter(vq.LITERAL, dfn);
if (nrpts != 0)
{
arg += nrpts.ToString();
}
vq.addParameter(vq.LITERAL, arg);
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, "");
if (fromDate != "0")
{
fromDate = VistaTimestamp.fromUtcString(fromDate);
}
vq.addParameter(vq.LITERAL, fromDate);
if (toDate != "0")
{
toDate = VistaTimestamp.fromUtcString(toDate);
}
vq.addParameter(vq.LITERAL, toDate);
return vq;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static MdoQuery buildReportTextRequest_AllResults(string dfn, string arg)
{
CheckRpcParams(dfn);
if (String.IsNullOrEmpty(arg))
{
throw new NullOrEmptyParamException("routine name");
}
VistaQuery vq = new VistaQuery("ORWRP REPORT TEXT");
vq.addParameter(vq.LITERAL, dfn);
vq.addParameter(vq.LITERAL, arg + '0');
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, "50000");
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, "0");
vq.addParameter(vq.LITERAL, "0");
return vq;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string responseOrOk(string response)
{
if (response != "")
{
return response;
}
return "OK";
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string errMsgOrOK(string response)
{
string[] flds = StringUtils.split(response, StringUtils.CARET);
if (flds[0] != "1")
{
return flds[1];
}
return "OK";
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string errMsgOrZero(string response)
{
string[] flds = StringUtils.split(response, StringUtils.CARET);
if (flds[0] != "0")
{
return flds[1];
}
return "OK";
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string errMsgOrIen(string response)
{
if (response != "" && !StringUtils.isNumeric(response))
{
throw new ArgumentException("Non-numeric IEN");
}
return response;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string removeCtlChars(string s)
{
if (String.IsNullOrEmpty(s))
{
return "";
}
StringBuilder result = new StringBuilder();
int i = 0;
while (i < s.Length)
{
int c = Convert.ToByte(s[i]);
if (c == 9 || c == 10 || c == 13 || (c > 31 && c < 127))
{
result.Append(s[i]);
}
i++;
}
return result.ToString();
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string getVistaName(string s)
{
if (!PersonName.isValid(s))
{
return "";
}
string[] flds = StringUtils.split(s, StringUtils.COMMA);
if (flds.Length != 2)
{
return "";
}
string result = flds[0] + ',' + flds[1];
return result.ToUpper();
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string getVistaGender(string s)
{
if (StringUtils.isEmpty(s))
{
return "";
}
string result = s.Substring(0, 1).ToUpper();
if (result != "M" && result != "F")
{
return "";
}
return result;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string getVisitString(Encounter encounter)
{
return encounter.LocationId + ';' +
VistaTimestamp.fromUtcString(encounter.Timestamp) + ';' +
encounter.Type;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static void CheckVisitString(string s)
{
if (String.IsNullOrEmpty(s))
{
throw new NullOrEmptyParamException("Visit String");
}
string[] pieces = s.Split(new char[] { ';' });
if (pieces.Length != 3)
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid visit string (need 3 semi-colon delimited pieces): " + s);
}
if (!isWellFormedIen(pieces[0]))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid visit string (invalid location IEN): " + s);
}
if (!VistaTimestamp.isValid(pieces[1]))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid visit string (invalid VistA timestamp): " + s);
}
if (pieces[2] != "A" && pieces[2] != "H" && pieces[2] != "E")
{
throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid visit string (type must be 'A', 'H' or 'E'): " + s);
}
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static StringDictionary toStringDictionary(string[] response)
{
if (response == null || response.Length == 0)
{
return null;
}
StringDictionary result = new StringDictionary();
for (int i = 0; i < response.Length; i++)
{
string[] flds = StringUtils.split(response[i], StringUtils.CARET);
result.Add(flds[0], flds[1]);
}
return result;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string getVariableValue(AbstractConnection cxn, string arg)
{
MdoQuery request = buildGetVariableValueRequest(arg);
string response = "";
try
{
response = (string)cxn.query(request);
return response;
}
catch (Exception exc)
{
throw new MdoException(request, response, exc);
}
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static MdoQuery buildGetVariableValueRequest(string arg)
{
if (String.IsNullOrEmpty(arg))
{
throw new NullOrEmptyParamException("arg");
}
VistaQuery vq = new VistaQuery("XWB GET VARIABLE VALUE");
vq.addParameter(vq.REFERENCE, arg);
return vq;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string buildFromToDateScreenParam(string fromDate, string toDate, int node, int pieceNum)
{
if (fromDate == "")
{
return "";
}
DateUtils.CheckDateRange(fromDate, toDate);
// Need test for valid dates.
fromDate = VistaTimestamp.fromUtcFromDate(fromDate);
toDate = VistaTimestamp.fromUtcString(toDate);
return "S FD=" + fromDate + ",TD=" + toDate + ",CDT=$P(^(" + node + "),U," + pieceNum + ") I CDT>=FD,CDT<TD";
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static string encrypt(string inString)
{
const int MAXKEY = 19;
String[] cipherPad =
{
"wkEo-ZJt!dG)49K{nX1BS$vH<&:Myf*>Ae0jQW=;|#PsO`\'%+rmb[gpqN,l6/hFC@DcUa ]z~R}\"V\\iIxu?872.(TYL5_3",
"rKv`R;M/9BqAF%&tSs#Vh)dO1DZP> *fX\'u[.4lY=-mg_ci802N7LTG<]!CWo:3?{+,5Q}(@jaExn$~p\\IyHwzU\"|k6Jeb",
"\\pV(ZJk\"WQmCn!Y,y@1d+~8s?[lNMxgHEt=uw|X:qSLjAI*}6zoF{T3#;ca)/h5%`P4$r]G\'9e2if_>UDKb7<v0&- RBO.",
"depjt3g4W)qD0V~NJar\\B \"?OYhcu[<Ms%Z`RIL_6:]AX-zG.#}$@vk7/5x&*m;(yb2Fn+l\'PwUof1K{9,|EQi>H=CT8S!",
"NZW:1}K$byP;jk)7\'`x90B|cq@iSsEnu,(l-hf.&Y_?J#R]+voQXU8mrV[!p4tg~OMez CAaGFD6H53%L/dT2<*>\"{\\wI=",
"vCiJ<oZ9|phXVNn)m K`t/SI%]A5qOWe\\&?;jT~M!fz1l>[D_0xR32c*4.P\"G{r7}E8wUgyudF+6-:B=$(sY,LkbHa#\'@Q",
"hvMX,\'4Ty;[a8/{6l~F_V\"}qLI\\!@x(D7bRmUH]W15J%N0BYPkrs&9:$)Zj>u|zwQ=ieC-oGA.#?tfdcO3gp`S+En K2*<",
"jd!W5[];4\'<C$/&x|rZ(k{>?ghBzIFN}fAK\"#`p_TqtD*1E37XGVs@0nmSe+Y6Qyo-aUu%i8c=H2vJ\\) R:MLb.9,wlO~P",
"2ThtjEM+!=xXb)7,ZV{*ci3\"8@_l-HS69L>]\\AUF/Q%:qD?1~m(yvO0e\'<#o$p4dnIzKP|`NrkaGg.ufCRB[; sJYwW}5&",
"vB\\5/zl-9y:Pj|=(R\'7QJI *&CTX\"p0]_3.idcuOefVU#omwNZ`$Fs?L+1Sk<,b)hM4A6[Y%aDrg@~KqEW8t>H};n!2xG{",
"sFz0Bo@_HfnK>LR}qWXV+D6`Y28=4Cm~G/7-5A\\b9!a#rP.l&M$hc3ijQk;),TvUd<[:I\"u1\'NZSOw]*gxtE{eJp|y (?%",
"M@,D}|LJyGO8`$*ZqH .j>c~h<d=fimszv[#-53F!+a;NC\'6T91IV?(0x&/{B)w\"]Q\\YUWprk4:ol%g2nE7teRKbAPuS_X",
".mjY#_0*H<B=Q+FML6]s;r2:e8R}[ic&KA 1w{)vV5d,$u\"~xD/Pg?IyfthO@CzWp%!`N4Z\'3-(o|J9XUE7k\\TlqSb>anG",
"xVa1\']_GU<X`|\\NgM?LS9{\"jT%s$}y[nvtlefB2RKJW~(/cIDCPow4,>#zm+:5b@06O3Ap8=*7ZFY!H-uEQk; .q)i&rhd",
"I]Jz7AG@QX.\"%3Lq>METUo{Pp_ |a6<0dYVSv8:b)~W9NK`(r\'4fs&wim\\kReC2hg=HOj$1B*/nxt,;c#y+![?lFuZ-5D}",
"Rr(Ge6F Hx>q$m&C%M~Tn,:\"o\'tX/*yP.{lZ!YkiVhuw_<KE5a[;}W0gjsz3]@7cI2\\QN?f#4p|vb1OUBD9)=-LJA+d`S8",
"I~k>y|m};d)-7DZ\"Fe/Y<B:xwojR,Vh]O0Sc[`$sg8GXE!1&Qrzp._W%TNK(=J 3i*2abuHA4C\'?Mv\\Pq{n#56LftUl@9+",
"~A*>9 WidFN,1KsmwQ)GJM{I4:C%}#Ep(?HB/r;t.&U8o|l[\'Lg\"2hRDyZ5`nbf]qjc0!zS-TkYO<_=76a\\X@$Pe3+xVvu",
"yYgjf\"5VdHc#uA,W1i+v\'6|@pr{n;DJ!8(btPGaQM.LT3oe?NB/&9>Z`-}02*%x<7lsqz4OS ~E$\\R]KI[:UwC_=h)kXmF",
"5:iar.{YU7mBZR@-K|2 \"+~`M%8sq4JhPo<_X\\Sg3WC;Tuxz,fvEQ1p9=w}FAI&j/keD0c?)LN6OHV]lGy\'$*>nd[(tb!#"
};
Random r = new Random();
int associatorIndex = r.Next(MAXKEY);
int identifierIndex = 0;
do
{
identifierIndex = r.Next(MAXKEY);
} while (associatorIndex == identifierIndex);
String xlatedString = "";
for (int i = 0; i < inString.Length; i++)
{
char inChar = inString[i];
int pos = cipherPad[associatorIndex].IndexOf(inChar);
if (pos == -1)
{
xlatedString += inChar;
}
else
{
xlatedString += cipherPad[identifierIndex][pos];
}
}
return (char)(associatorIndex + 32) +
xlatedString +
(char)(identifierIndex + 32);
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static AbstractCredentials getAdministrativeCredentials(Site site)
{
AbstractCredentials credentials = new VistaCredentials();
credentials.LocalUid = VistaAccount.getAdminLocalUid(site.Id);
credentials.FederatedUid = "123456789";
credentials.SubjectName = "DEPARTMENT OF DEFENSE,USER";
credentials.SubjectPhone = "";
credentials.AuthenticationSource = site.getDataSourceByModality("HIS");
credentials.AuthenticationToken = site.Id + '_' + credentials.LocalUid;
return credentials;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static StringDictionary reverseKeyValue(StringDictionary d)
{
StringDictionary result = new StringDictionary();
foreach (string key in d.Keys)
{
result.Add(d[key], key);
}
return result;
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static bool isWellFormedDuz(string duz)
{
return !String.IsNullOrEmpty(duz) && !duz.Equals("0") && StringUtils.isNumeric(duz);
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static bool isWellFormedIen(string ien)
{
return !String.IsNullOrEmpty(ien) && !ien.Equals("0") &&
(StringUtils.isNumeric(ien) || StringUtils.isDecimal(ien));
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static void CheckRpcParams(string ien, string fromDate = null, string toDate = null)
{
if (!isWellFormedIen(ien))
{
throw new InvalidlyFormedRecordIdException(ien);
}
//4/14/2011 David Parshan
//Added toDate check, as there is the ability to have a valid
//fromDate with a default "" toDate
if (!String.IsNullOrEmpty(fromDate) && fromDate != "0" && toDate != "" && toDate != "0" && toDate != "-1")
{
DateUtils.CheckDateRange(fromDate, toDate);
}
else
{
if (!String.IsNullOrEmpty(fromDate) && fromDate != "0")
{
if (!DateUtils.isWellFormedUtcDateTime(fromDate))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_DATE_FORMAT, "Invalid 'from' date: " + fromDate);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Project858.ComponentModel.Client;
using System.Net.Sockets;
using Project858.Diagnostics;
using System.Threading;
namespace Project858.Net
{
/// <summary>
/// Klient zabezpecujuci komunikaciu pomocou udp protokolu
/// </summary>
public class UdpTransportClient : ClientBase, ITransportClient
{
#region - Constructor -
/// <summary>
/// Initialize this class
/// </summary>
/// <param name="localAddress">Ip adresa na ktorej upd klient pocuva</param>
/// <param name="localPort">Ip port na ktorom upd klient pocuva</param>
/// <param name="remoteAddress">Ip adresa na ktoru sa data odosielaju</param>
/// <param name="remotePort">Ip port na ktory sa data odosielaju</param>
public UdpTransportClient(IPAddress localAddress, int localPort, IPAddress remoteAddress, int remotePort)
: this(new IPEndPoint(localAddress, localPort), new IPEndPoint(remoteAddress, remotePort))
{
}
/// <summary>
/// Initialize this class
/// </summary>
/// <param name="localIpEndPoint">Ip end point servera</param>
/// <param name="remoteIpEndPoint">Ip end point kde klient pocuva</param>
public UdpTransportClient(IPEndPoint localIpEndPoint, IPEndPoint remoteIpEndPoint)
{
if (localIpEndPoint == null)
throw new ArgumentNullException("localIpEndPoint");
if (remoteIpEndPoint == null)
throw new ArgumentNullException("remoteIpEndPoint");
this.m_localIpEndPoint = localIpEndPoint;
this.m_remoteIpEndPoint = remoteIpEndPoint;
}
#endregion
#region - Event -
/// <summary>
/// Event na oznamenie spustenia spojenia pre vyssu vrstvu
/// </summary>
private event EventHandler m_connectedEvent = null;
/// <summary>
/// Event na oznamenie spustenia spojenia pre vyssu vrstvu
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
public event EventHandler ConnectedEvent
{
add
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.m_connectedEvent += value;
}
remove
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.m_connectedEvent -= value;
}
}
/// <summary>
/// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu
/// </summary>
private event EventHandler disconnectedEvent = null;
/// <summary>
/// Event na oznamenie ukoncenia spojenia pre vyssu vrstvu
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
public event EventHandler DisconnectedEvent
{
add
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.disconnectedEvent += value;
}
remove
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.disconnectedEvent -= value;
}
}
/// <summary>
/// Event na oznamenue prichodu dat na transportnej vrstve
/// </summary>
private event DataEventHandler m_receivedDataEvent = null;
/// <summary>
/// Event na oznamenue prichodu dat na transportnej vrstve
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
public event DataEventHandler ReceivedDataEvent
{
add
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.m_receivedDataEvent += value;
}
remove
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
//netusim preco ale to mi zvykne zamrznut thread a ja fakt neviem preco
lock (this.m_eventLock)
this.m_receivedDataEvent -= value;
}
}
/// <summary>
/// Event oznamujuci zmenu stavu pripojenia
/// </summary>
private event EventHandler m_changeConnectionStateEvent = null;
/// <summary>
/// Event oznamujuci zmenu stavu pripojenia
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
/// <exception cref="InvalidOperationException">
/// Ak nie je autoreconnect povoleny
/// </exception>
public event EventHandler ChangeConnectionStateEvent
{
add
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.m_changeConnectionStateEvent += value;
}
remove
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
lock (this.m_eventLock)
this.m_changeConnectionStateEvent -= value;
}
}
#endregion
#region - Proeprties -
/// <summary>
/// (Get / Set) Stav v akom sa nachadza komunikacia / komunikacny kanal
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
public ConnectionStates ConnectionState
{
get
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
return this.m_connectionState;
}
}
/// <summary>
/// (Get) Detekcia pripojenia
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
public Boolean IsConnected
{
get
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
return this.m_isConnectied;
}
}
/// <summary>
/// Ip end point kam je klient pripojeny
/// </summary>
public IPEndPoint RemoteIpEndPoint
{
get {
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
return m_remoteIpEndPoint;
}
}
/// <summary>
/// Ip end point kde klient pocuva
/// </summary>
public IPEndPoint LocalIpEndPoint
{
get {
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
return m_localIpEndPoint; }
}
#endregion
#region - Variable -
/// <summary>
/// detekcia pripojenia
/// </summary>
private volatile Boolean m_isConnectied = false;
/// <summary>
/// Thred zabezpecujuci citani dat.
/// </summary>
private Thread m_thread = null;
/// <summary>
/// Stav v akom sa nachadza komunikacia / komunikacny kanal
/// </summary>
private ConnectionStates m_connectionState = ConnectionStates.Closed;
/// <summary>
/// Ip end point kam je klient pripojeny
/// </summary>
private IPEndPoint m_remoteIpEndPoint = null;
/// <summary>
/// Ip end point kde klient pocuva
/// </summary>
private IPEndPoint m_localIpEndPoint = null;
/// <summary>
/// Klient na udp komunikaciu
/// </summary>
private UdpClient m_client = null;
#endregion
#region - Public Method -
/// <summary>
/// Vrati meno triedy
/// </summary>
/// <returns>Meno triedy</returns>
public override string ToString()
{
return String.Format("TUdpTransportClient");
}
/// <summary>
/// Zapise _data na komunikacnu linku
/// </summary>
/// <exception cref="InvalidOperationException">
/// Vynimka v pripade ze sa snazime zapisat _data, ale spojenie nie je.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Ak je object v stave _isDisposed
/// </exception>
/// <returns>True = _data boli uspesne zapisane, False = chyba pri zapise dat</returns>
public Boolean Write(Byte[] data)
{
//je objekt _isDisposed ?
if (this.IsDisposed)
throw new ObjectDisposedException("Object was disposed");
//otvorenie nie je mozne ak je connection == true
if (!this.m_isConnectied)
throw new InvalidOperationException("Zapis dat nie je mozny ! Spojenie nie je !");
try
{
//zalogujeme
//this.InternalTrace(TraceTypes.Verbose, "Odosielanie dat: [{0}]", BitConverter.ToString(_data));
this.InternalTrace(TraceTypes.Verbose, "Odosielanie dat: [{0}]", data.Length);
//zapiseme _data
this.m_client.Send(data, data.Length);
//zalogujeme prijate dat
this.InternalTrace(TraceTypes.Verbose, "Data boli uspesne odoslane...");
//uspesne ukoncenie metody
return true;
}
catch (Exception ex)
{
//zalogujeme
this.InternalTrace(TraceTypes.Error, "Chyba pri zapise dat. {0}", ex.Message);
//ukoncime klienta
this.InternalStop();
//chybne ukoncenie metody
return false;
}
}
#endregion
#region - Private Method -
/// <summary>
/// Vykona interny start klienta
/// </summary>
/// <returns>True = start klienta bol uspesny</returns>
protected override bool InternalStart()
{
//zacina pripajanie
this.m_connectionState = ConnectionStates.Connecting;
//doslo k zmene stavu
this.OnChangeConnectionState(EventArgs.Empty);
//inicializujeme spojenie
return this.InternalConnect();
}
/// <summary>
/// Vykona interny stop klienta
/// </summary>
protected override void InternalStop()
{
//ukoncime pracovne vlakno
this.InternalDeinitializeThread();
//ukoncime spojenie
this.InternalDisconnect();
//doslo ku konektu
this.m_isConnectied = false;
//ukoncenie spojenia
this.OnDisconnected(EventArgs.Empty);
//zmena stavu
this.m_connectionState = ConnectionStates.Closed;
//event oznamujuci zmenu stavu
this.OnChangeConnectionState(EventArgs.Empty);
}
#endregion
#region - Private Method -
/// <summary>
/// Vykona interny pokus o pripojenie k vzdialenemu bodu
/// </summary>
/// <returns>True = spojenie bolo uspesne vytvorene</returns>
private Boolean InternalConnect()
{
try
{
lock (this)
{
//inicializujeme klienta
this.m_client = new UdpClient(this.m_localIpEndPoint);
this.m_client.Connect(this.m_remoteIpEndPoint);
//spustime vlakno na citanie dat
this.InternalInitializeThread();
//doslo ku konektu
this.m_isConnectied = true;
//spojenie bolo vytvorene
this.OnConnected(EventArgs.Empty);
//start komunikacie sa podaril
this.m_connectionState = ConnectionStates.Connected;
//doslo k zmene stavu
this.OnChangeConnectionState(EventArgs.Empty);
}
//inicializacia komunikacie bola uspesna
return true;
}
catch (Exception ex)
{
//zalogujeme
this.InternalTrace(TraceTypes.Error, "Chyba pri vytvarani spojenia. {0}", ex);
//inicializacia nebola uspesna
return false;
}
}
/// <summary>
/// Interny disconnect
/// </summary>
private void InternalDisconnect()
{
try
{
//ukoncime klienta
if (this.m_client != null)
{
this.m_client.Close();
}
}
catch (Exception ex)
{
//zalogujeme
this.InternalTrace(TraceTypes.Error, "Chyba pri ukoncovani spojenia spojenia. {0}", ex);
}
finally
{
//deinicializujeme klienta
this.m_client = null;
}
}
/// <summary>
/// Inicializuje pracovne vlakno zabezpecujuce citanie dat
/// </summary>
private void InternalInitializeThread()
{
//inicializujeme pracovne vlakno
this.m_thread = new Thread(new ThreadStart(this.InternalReceive));
this.m_thread.IsBackground = true;
//spustime pracovne vlakno
this.m_thread.Start();
}
/// <summary>
/// Deinicializuje pracovne vlakno
/// </summary>
private void InternalDeinitializeThread()
{
try
{
if (this.m_thread != null)
{
this.m_thread.Abort();
this.m_thread.Join();
}
}
catch (Exception ex)
{
//zalogujeme
this.InternalTrace(TraceTypes.Error, "Chyba pri ukoncovani pracovneho vlakna. {0}", ex);
}
finally
{
this.m_thread = null;
}
}
/// <summary>
/// Pracovne vlakno zabezpecujuce citanie dat
/// </summary>
private void InternalReceive()
{
try
{
while (this.IsRun)
{
//ip end point z ktoreho prijmame data
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
//nacitame data
byte[] data = this.m_client.Receive(ref remoteEndPoint);
//ak boli nejake data nacitane
if (data != null || data.Length > 0)
{
//odosleme data na spracovanie
this.OnReceivedData(new DataEventArgs(data, remoteEndPoint));
}
}
}
catch (ThreadAbortException)
{
//chybu ignorujeme
}
catch (Exception ex)
{
//zalogujeme
this.InternalTrace(TraceTypes.Error, "Chyba pracovneho vlakna aplikacie. {0}", ex);
//ukoncime
this.InternalStop();
}
}
#endregion
#region - Call Event Method -
/// <summary>
/// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu
/// oznamujuceho prijatie dat
/// </summary>
/// <param name="e">EventArgs obsahujuci _data</param>
protected virtual void OnReceivedData(DataEventArgs e)
{
DataEventHandler handler = this.m_receivedDataEvent;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu
/// oznamujuceho pripojenie
/// </summary>
/// <param name="e">EventArgs</param>
protected virtual void OnConnected(EventArgs e)
{
EventHandler handler = this.m_connectedEvent;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Vytvori asynchronne volanie na metodu zabezpecujucu vytvorenie eventu
/// oznamujuceho pad spojenia
/// </summary>
/// <param name="e">EventArgs</param>
protected virtual void OnDisconnected(EventArgs e)
{
EventHandler handler = this.disconnectedEvent;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Vygeneruje event oznamujui zmenu stavu pripojenia
/// </summary>
/// <param name="e">EventArgs</param>
protected virtual void OnChangeConnectionState(EventArgs e)
{
//ziskame pristup
EventHandler handler = this.m_changeConnectionStateEvent;
//vyvolame event
if (handler != null)
handler(this, e);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// This file is part of Microsoft Robotics Developer Studio Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// $File: DriveControl.Designer.cs $ $Revision: 1 $
//-----------------------------------------------------------------------
namespace TrackRoamer.Robotics.Services.TrackRoamerDashboard
{
partial class DriveControl
{
/// <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.Windows.Forms.Label label1;
System.Windows.Forms.Label label5;
System.Windows.Forms.Label label6;
System.Windows.Forms.Label label7;
System.Windows.Forms.Label label2;
System.Windows.Forms.Label label4;
System.Windows.Forms.Label label3;
System.Windows.Forms.Label label8;
System.Windows.Forms.Label label10;
this.cbJoystick = new System.Windows.Forms.ComboBox();
this.lblX = new System.Windows.Forms.Label();
this.lblY = new System.Windows.Forms.Label();
this.lblZ = new System.Windows.Forms.Label();
this.lblButtons = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkStop = new System.Windows.Forms.CheckBox();
this.chkDrive = new System.Windows.Forms.CheckBox();
this.picJoystick = new System.Windows.Forms.PictureBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.linkDirectory = new System.Windows.Forms.LinkLabel();
this.lblNode = new System.Windows.Forms.Label();
this.listDirectory = new System.Windows.Forms.ListBox();
this.btnConnect = new System.Windows.Forms.Button();
this.txtPort = new System.Windows.Forms.MaskedTextBox();
this.txtMachine = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnDisconnect = new System.Windows.Forms.Button();
this.lblDelay = new System.Windows.Forms.Label();
this.btnConnectLRF = new System.Windows.Forms.Button();
this.btnStartLRF = new System.Windows.Forms.Button();
this.picLRF = new System.Windows.Forms.PictureBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.lblLag = new System.Windows.Forms.Label();
this.lblMotor = new System.Windows.Forms.Label();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.btnBrowse = new System.Windows.Forms.Button();
this.txtLogFile = new System.Windows.Forms.TextBox();
this.chkLog = new System.Windows.Forms.CheckBox();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPageConnect = new System.Windows.Forms.TabPage();
this.tabPageDrive = new System.Windows.Forms.TabPage();
this.tabPageLog = new System.Windows.Forms.TabPage();
this.tabPageOther = new System.Windows.Forms.TabPage();
label1 = new System.Windows.Forms.Label();
label5 = new System.Windows.Forms.Label();
label6 = new System.Windows.Forms.Label();
label7 = new System.Windows.Forms.Label();
label2 = new System.Windows.Forms.Label();
label4 = new System.Windows.Forms.Label();
label3 = new System.Windows.Forms.Label();
label8 = new System.Windows.Forms.Label();
label10 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picJoystick)).BeginInit();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picLRF)).BeginInit();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPageConnect.SuspendLayout();
this.tabPageDrive.SuspendLayout();
this.SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(6, 25);
label1.Name = "label1";
label1.Size = new System.Drawing.Size(44, 13);
label1.TabIndex = 1;
label1.Text = "Device:";
//
// label5
//
label5.AutoSize = true;
label5.Location = new System.Drawing.Point(34, 50);
label5.Name = "label5";
label5.Size = new System.Drawing.Size(17, 13);
label5.TabIndex = 5;
label5.Text = "X:";
label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label6
//
label6.AutoSize = true;
label6.Location = new System.Drawing.Point(34, 67);
label6.Name = "label6";
label6.Size = new System.Drawing.Size(17, 13);
label6.TabIndex = 6;
label6.Text = "Y:";
label6.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label7
//
label7.AutoSize = true;
label7.Location = new System.Drawing.Point(34, 84);
label7.Name = "label7";
label7.Size = new System.Drawing.Size(17, 13);
label7.TabIndex = 7;
label7.Text = "Z:";
label7.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label2
//
label2.AutoSize = true;
label2.Location = new System.Drawing.Point(6, 101);
label2.Name = "label2";
label2.Size = new System.Drawing.Size(46, 13);
label2.TabIndex = 8;
label2.Text = "Buttons:";
label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label4
//
label4.AutoSize = true;
label4.Location = new System.Drawing.Point(7, 50);
label4.Name = "label4";
label4.Size = new System.Drawing.Size(29, 13);
label4.TabIndex = 1;
label4.Text = "Port:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new System.Drawing.Point(7, 20);
label3.Name = "label3";
label3.Size = new System.Drawing.Size(51, 13);
label3.TabIndex = 0;
label3.Text = "Machine:";
//
// label8
//
label8.AutoSize = true;
label8.Location = new System.Drawing.Point(14, 17);
label8.Name = "label8";
label8.Size = new System.Drawing.Size(37, 13);
label8.TabIndex = 16;
label8.Text = "Motor:";
label8.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label10
//
label10.AutoSize = true;
label10.Location = new System.Drawing.Point(23, 34);
label10.Name = "label10";
label10.Size = new System.Drawing.Size(28, 13);
label10.TabIndex = 18;
label10.Text = "Lag:";
label10.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// cbJoystick
//
this.cbJoystick.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbJoystick.FormattingEnabled = true;
this.cbJoystick.Location = new System.Drawing.Point(60, 22);
this.cbJoystick.Name = "cbJoystick";
this.cbJoystick.Size = new System.Drawing.Size(179, 21);
this.cbJoystick.TabIndex = 0;
this.cbJoystick.SelectedIndexChanged += new System.EventHandler(this.cbJoystick_SelectedIndexChanged);
//
// lblX
//
this.lblX.Location = new System.Drawing.Point(60, 50);
this.lblX.Name = "lblX";
this.lblX.Size = new System.Drawing.Size(35, 13);
this.lblX.TabIndex = 2;
this.lblX.Text = "0";
this.lblX.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblY
//
this.lblY.Location = new System.Drawing.Point(60, 67);
this.lblY.Name = "lblY";
this.lblY.Size = new System.Drawing.Size(35, 13);
this.lblY.TabIndex = 3;
this.lblY.Text = "0";
this.lblY.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblZ
//
this.lblZ.Location = new System.Drawing.Point(60, 84);
this.lblZ.Name = "lblZ";
this.lblZ.Size = new System.Drawing.Size(35, 13);
this.lblZ.TabIndex = 4;
this.lblZ.Text = "0";
this.lblZ.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblButtons
//
this.lblButtons.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblButtons.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblButtons.Location = new System.Drawing.Point(63, 101);
this.lblButtons.Name = "lblButtons";
this.lblButtons.Size = new System.Drawing.Size(176, 13);
this.lblButtons.TabIndex = 9;
this.lblButtons.Text = "O";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkStop);
this.groupBox1.Controls.Add(this.chkDrive);
this.groupBox1.Controls.Add(this.picJoystick);
this.groupBox1.Controls.Add(label1);
this.groupBox1.Controls.Add(this.lblButtons);
this.groupBox1.Controls.Add(this.cbJoystick);
this.groupBox1.Controls.Add(label2);
this.groupBox1.Controls.Add(this.lblX);
this.groupBox1.Controls.Add(label7);
this.groupBox1.Controls.Add(this.lblY);
this.groupBox1.Controls.Add(label6);
this.groupBox1.Controls.Add(this.lblZ);
this.groupBox1.Controls.Add(label5);
this.groupBox1.Location = new System.Drawing.Point(13, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(245, 151);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Direct Input Device";
//
// chkStop
//
this.chkStop.Appearance = System.Windows.Forms.Appearance.Button;
this.chkStop.Location = new System.Drawing.Point(112, 117);
this.chkStop.Name = "chkStop";
this.chkStop.Size = new System.Drawing.Size(77, 24);
this.chkStop.TabIndex = 12;
this.chkStop.Text = "Stop";
this.chkStop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.chkStop.UseVisualStyleBackColor = true;
this.chkStop.CheckedChanged += new System.EventHandler(this.chkStop_CheckedChanged);
//
// chkDrive
//
this.chkDrive.Appearance = System.Windows.Forms.Appearance.Button;
this.chkDrive.Location = new System.Drawing.Point(9, 117);
this.chkDrive.Name = "chkDrive";
this.chkDrive.Size = new System.Drawing.Size(76, 24);
this.chkDrive.TabIndex = 11;
this.chkDrive.Text = "Drive";
this.chkDrive.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.chkDrive.UseVisualStyleBackColor = true;
this.chkDrive.CheckedChanged += new System.EventHandler(this.chkDrive_CheckedChanged);
//
// picJoystick
//
this.picJoystick.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.picJoystick.Location = new System.Drawing.Point(129, 49);
this.picJoystick.Name = "picJoystick";
this.picJoystick.Size = new System.Drawing.Size(49, 49);
this.picJoystick.TabIndex = 10;
this.picJoystick.TabStop = false;
this.picJoystick.MouseLeave += new System.EventHandler(this.picJoystick_MouseLeave);
this.picJoystick.MouseMove += new System.Windows.Forms.MouseEventHandler(this.picJoystick_MouseMove);
this.picJoystick.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picJoystick_MouseUp);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.linkDirectory);
this.groupBox2.Controls.Add(this.lblNode);
this.groupBox2.Controls.Add(this.listDirectory);
this.groupBox2.Controls.Add(this.btnConnect);
this.groupBox2.Controls.Add(this.txtPort);
this.groupBox2.Controls.Add(this.txtMachine);
this.groupBox2.Controls.Add(label4);
this.groupBox2.Controls.Add(label3);
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(3, 3);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(710, 671);
this.groupBox2.TabIndex = 11;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Connect to DifferentialDrive on a Remote Node";
//
// linkDirectory
//
this.linkDirectory.AutoSize = true;
this.linkDirectory.Enabled = false;
this.linkDirectory.LinkArea = new System.Windows.Forms.LinkArea(8, 9);
this.linkDirectory.Location = new System.Drawing.Point(7, 75);
this.linkDirectory.Name = "linkDirectory";
this.linkDirectory.Size = new System.Drawing.Size(94, 17);
this.linkDirectory.TabIndex = 8;
this.linkDirectory.TabStop = true;
this.linkDirectory.Text = "Service Directory:";
this.linkDirectory.UseCompatibleTextRendering = true;
this.linkDirectory.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkDirectory_LinkClicked);
//
// lblNode
//
this.lblNode.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblNode.AutoEllipsis = true;
this.lblNode.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblNode.Location = new System.Drawing.Point(10, 96);
this.lblNode.Name = "lblNode";
this.lblNode.Size = new System.Drawing.Size(691, 15);
this.lblNode.TabIndex = 7;
//
// listDirectory
//
this.listDirectory.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listDirectory.FormattingEnabled = true;
this.listDirectory.Location = new System.Drawing.Point(10, 119);
this.listDirectory.Name = "listDirectory";
this.listDirectory.Size = new System.Drawing.Size(694, 537);
this.listDirectory.TabIndex = 5;
this.listDirectory.DoubleClick += new System.EventHandler(this.listDirectory_DoubleClick);
//
// btnConnect
//
this.btnConnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnConnect.Location = new System.Drawing.Point(649, 42);
this.btnConnect.Name = "btnConnect";
this.btnConnect.Size = new System.Drawing.Size(55, 23);
this.btnConnect.TabIndex = 4;
this.btnConnect.Text = "Connect";
this.btnConnect.UseVisualStyleBackColor = true;
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// txtPort
//
this.txtPort.Location = new System.Drawing.Point(64, 44);
this.txtPort.Mask = "99999";
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(42, 20);
this.txtPort.TabIndex = 3;
this.txtPort.Text = "50001";
//
// txtMachine
//
this.txtMachine.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtMachine.Location = new System.Drawing.Point(64, 17);
this.txtMachine.Name = "txtMachine";
this.txtMachine.Size = new System.Drawing.Size(640, 20);
this.txtMachine.TabIndex = 2;
this.txtMachine.Text = "localhost";
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox3.Controls.Add(this.btnDisconnect);
this.groupBox3.Controls.Add(this.lblDelay);
this.groupBox3.Controls.Add(this.btnConnectLRF);
this.groupBox3.Controls.Add(this.btnStartLRF);
this.groupBox3.Controls.Add(this.picLRF);
this.groupBox3.Location = new System.Drawing.Point(6, 402);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(697, 259);
this.groupBox3.TabIndex = 12;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Laser Range Finder";
//
// btnDisconnect
//
this.btnDisconnect.Enabled = false;
this.btnDisconnect.Location = new System.Drawing.Point(6, 76);
this.btnDisconnect.Name = "btnDisconnect";
this.btnDisconnect.Size = new System.Drawing.Size(75, 23);
this.btnDisconnect.TabIndex = 4;
this.btnDisconnect.Text = "Disconnect";
this.btnDisconnect.UseVisualStyleBackColor = true;
this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
//
// lblDelay
//
this.lblDelay.Font = new System.Drawing.Font("Microsoft Sans Serif", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDelay.Location = new System.Drawing.Point(6, 102);
this.lblDelay.Name = "lblDelay";
this.lblDelay.Size = new System.Drawing.Size(75, 18);
this.lblDelay.TabIndex = 3;
this.lblDelay.Text = "0";
//
// btnConnectLRF
//
this.btnConnectLRF.Enabled = false;
this.btnConnectLRF.Location = new System.Drawing.Point(6, 47);
this.btnConnectLRF.Name = "btnConnectLRF";
this.btnConnectLRF.Size = new System.Drawing.Size(75, 23);
this.btnConnectLRF.TabIndex = 2;
this.btnConnectLRF.Text = "Connect";
this.btnConnectLRF.UseVisualStyleBackColor = true;
this.btnConnectLRF.Click += new System.EventHandler(this.btnConnectLRF_Click);
//
// btnStartLRF
//
this.btnStartLRF.Enabled = false;
this.btnStartLRF.Location = new System.Drawing.Point(6, 18);
this.btnStartLRF.Name = "btnStartLRF";
this.btnStartLRF.Size = new System.Drawing.Size(75, 23);
this.btnStartLRF.TabIndex = 1;
this.btnStartLRF.Text = "Start";
this.btnStartLRF.UseVisualStyleBackColor = true;
this.btnStartLRF.Click += new System.EventHandler(this.btnStartLRF_Click);
//
// picLRF
//
this.picLRF.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.picLRF.Location = new System.Drawing.Point(87, 18);
this.picLRF.Name = "picLRF";
this.picLRF.Size = new System.Drawing.Size(604, 234);
this.picLRF.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.picLRF.TabIndex = 0;
this.picLRF.TabStop = false;
//
// groupBox4
//
this.groupBox4.Controls.Add(label10);
this.groupBox4.Controls.Add(this.lblLag);
this.groupBox4.Controls.Add(label8);
this.groupBox4.Controls.Add(this.lblMotor);
this.groupBox4.Location = new System.Drawing.Point(276, 6);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(195, 71);
this.groupBox4.TabIndex = 13;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Differential Drive";
//
// lblLag
//
this.lblLag.Location = new System.Drawing.Point(60, 34);
this.lblLag.Name = "lblLag";
this.lblLag.Size = new System.Drawing.Size(35, 13);
this.lblLag.TabIndex = 17;
this.lblLag.Text = "0";
this.lblLag.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblMotor
//
this.lblMotor.Location = new System.Drawing.Point(60, 17);
this.lblMotor.Name = "lblMotor";
this.lblMotor.Size = new System.Drawing.Size(35, 13);
this.lblMotor.TabIndex = 15;
this.lblMotor.Text = "Off";
this.lblMotor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// groupBox5
//
this.groupBox5.Controls.Add(this.btnBrowse);
this.groupBox5.Controls.Add(this.txtLogFile);
this.groupBox5.Controls.Add(this.chkLog);
this.groupBox5.Location = new System.Drawing.Point(501, 6);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(195, 71);
this.groupBox5.TabIndex = 14;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Logging";
//
// btnBrowse
//
this.btnBrowse.Location = new System.Drawing.Point(162, 42);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(27, 23);
this.btnBrowse.TabIndex = 2;
this.btnBrowse.Text = "...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// txtLogFile
//
this.txtLogFile.Location = new System.Drawing.Point(6, 43);
this.txtLogFile.Name = "txtLogFile";
this.txtLogFile.Size = new System.Drawing.Size(150, 20);
this.txtLogFile.TabIndex = 1;
//
// chkLog
//
this.chkLog.AutoSize = true;
this.chkLog.Location = new System.Drawing.Point(6, 19);
this.chkLog.Name = "chkLog";
this.chkLog.Size = new System.Drawing.Size(95, 17);
this.chkLog.TabIndex = 0;
this.chkLog.Text = "Log Messages";
this.chkLog.UseVisualStyleBackColor = true;
this.chkLog.CheckedChanged += new System.EventHandler(this.chkLog_CheckedChanged);
//
// saveFileDialog
//
this.saveFileDialog.Filter = "Xml log file|*.log;*.xml|All files|*.*";
this.saveFileDialog.Title = "Log File";
this.saveFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog_FileOk);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPageConnect);
this.tabControl1.Controls.Add(this.tabPageDrive);
this.tabControl1.Controls.Add(this.tabPageLog);
this.tabControl1.Controls.Add(this.tabPageOther);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(724, 703);
this.tabControl1.TabIndex = 15;
//
// tabPageConnect
//
this.tabPageConnect.Controls.Add(this.groupBox2);
this.tabPageConnect.Location = new System.Drawing.Point(4, 22);
this.tabPageConnect.Name = "tabPageConnect";
this.tabPageConnect.Padding = new System.Windows.Forms.Padding(3);
this.tabPageConnect.Size = new System.Drawing.Size(716, 677);
this.tabPageConnect.TabIndex = 0;
this.tabPageConnect.Text = "Connect";
this.tabPageConnect.UseVisualStyleBackColor = true;
//
// tabPageDrive
//
this.tabPageDrive.Controls.Add(this.groupBox1);
this.tabPageDrive.Controls.Add(this.groupBox3);
this.tabPageDrive.Controls.Add(this.groupBox5);
this.tabPageDrive.Controls.Add(this.groupBox4);
this.tabPageDrive.Location = new System.Drawing.Point(4, 22);
this.tabPageDrive.Name = "tabPageDrive";
this.tabPageDrive.Padding = new System.Windows.Forms.Padding(3);
this.tabPageDrive.Size = new System.Drawing.Size(716, 677);
this.tabPageDrive.TabIndex = 1;
this.tabPageDrive.Text = "Drive";
this.tabPageDrive.UseVisualStyleBackColor = true;
//
// tabPageLog
//
this.tabPageLog.Location = new System.Drawing.Point(4, 22);
this.tabPageLog.Name = "tabPageLog";
this.tabPageLog.Size = new System.Drawing.Size(716, 677);
this.tabPageLog.TabIndex = 2;
this.tabPageLog.Text = "Log";
this.tabPageLog.UseVisualStyleBackColor = true;
//
// tabPageOther
//
this.tabPageOther.Location = new System.Drawing.Point(4, 22);
this.tabPageOther.Name = "tabPageOther";
this.tabPageOther.Size = new System.Drawing.Size(716, 677);
this.tabPageOther.TabIndex = 3;
this.tabPageOther.Text = "Other";
this.tabPageOther.UseVisualStyleBackColor = true;
//
// DriveControl
//
this.AcceptButton = this.btnConnect;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(724, 703);
this.Controls.Add(this.tabControl1);
this.MinimumSize = new System.Drawing.Size(486, 580);
this.Name = "DriveControl";
this.Text = "TrackRoamer Dashboard";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.DriveControl_FormClosed);
this.Load += new System.EventHandler(this.DriveControl_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picJoystick)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.picLRF)).EndInit();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.tabControl1.ResumeLayout(false);
this.tabPageConnect.ResumeLayout(false);
this.tabPageDrive.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox cbJoystick;
private System.Windows.Forms.Label lblX;
private System.Windows.Forms.Label lblY;
private System.Windows.Forms.Label lblZ;
private System.Windows.Forms.Label lblButtons;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.ListBox listDirectory;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.MaskedTextBox txtPort;
private System.Windows.Forms.TextBox txtMachine;
private System.Windows.Forms.PictureBox picJoystick;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button btnConnectLRF;
private System.Windows.Forms.Button btnStartLRF;
private System.Windows.Forms.PictureBox picLRF;
private System.Windows.Forms.CheckBox chkStop;
private System.Windows.Forms.CheckBox chkDrive;
private System.Windows.Forms.Button btnDisconnect;
private System.Windows.Forms.Label lblDelay;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Label lblMotor;
private System.Windows.Forms.Label lblLag;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.TextBox txtLogFile;
private System.Windows.Forms.CheckBox chkLog;
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.Label lblNode;
private System.Windows.Forms.LinkLabel linkDirectory;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPageConnect;
private System.Windows.Forms.TabPage tabPageDrive;
private System.Windows.Forms.TabPage tabPageLog;
private System.Windows.Forms.TabPage tabPageOther;
}
}
| |
//
// DetailsView.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2009 Novell, Inc.
//
// 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.Linq;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Database;
using Banshee.Gui;
using Banshee.Library;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Sources;
using IA=InternetArchive;
namespace Banshee.InternetArchive
{
public class DetailsView : Gtk.HBox, Banshee.Sources.Gui.ISourceContents
{
private DetailsSource source;
private IA.Details details;
private Item item;
public DetailsView (DetailsSource source, Item item)
{
this.source = source;
this.item = item;
Spacing = 6;
source.LoadDetails ();
}
private bool gui_built;
public void UpdateDetails ()
{
details = item.Details;
if (!gui_built && details != null) {
gui_built = true;
BuildInfoBox ();
BuildFilesBox ();
ShowAll ();
}
}
#region ISourceContents
public bool SetSource (ISource source)
{
this.source = source as DetailsSource;
return this.source != null;
}
public void ResetSource ()
{
}
public ISource Source { get { return source; } }
public Widget Widget { get { return this; } }
#endregion
private Section CreateSection (string label, Widget child)
{
var section = new Section (label, child);
return section;
}
private class Section : VBox
{
public Section (string label, Widget child)
{
Spacing = 6;
Header = new SectionHeader (label, child);
PackStart (Header, false, false, 0);
PackStart (child, false, false, 0);
}
public SectionHeader Header { get; private set; }
}
private class SectionHeader : EventBox
{
Arrow arrow;
Label label;
Widget child;
public HBox Box { get; private set; }
public SectionHeader (string headerString, Widget child)
{
this.child = child;
AppPaintable = true;
CanFocus = true;
Box = new HBox ();
Box.Spacing = 6;
Box.BorderWidth = 4;
label = new Label ("<b>" + headerString + "</b>") { Xalign = 0f, UseMarkup = true };
arrow = new Arrow (ArrowType.Down, ShadowType.None);
Box.PackStart (arrow, false, false, 0);
Box.PackStart (label, true, true, 0);
State = StateType.Selected;
bool changing_style = false;
StyleSet += (o, a) => {
if (!changing_style) {
changing_style = true;
ModifyBg (StateType.Normal, Style.Background (StateType.Selected));
changing_style = false;
}
};
Child = Box;
ButtonPressEvent += (o, a) => Toggle ();
KeyPressEvent += (o, a) => {
var key = a.Event.Key;
switch (key) {
case Gdk.Key.Return:
case Gdk.Key.KP_Enter:
case Gdk.Key.space:
Toggle ();
a.RetVal = true;
break;
}
};
}
private void Toggle ()
{
Expanded = !Expanded;
}
private bool expanded = true;
private bool Expanded {
get { return expanded; }
set {
arrow.ArrowType = value ? ArrowType.Down : ArrowType.Right;
child.Visible = value;
expanded = value;
}
}
}
private void BuildInfoBox ()
{
var frame = new Hyena.Widgets.RoundedFrame ();
var vbox = new VBox ();
vbox.Spacing = 6;
vbox.BorderWidth = 2;
// Description
var desc = new Hyena.Widgets.WrapLabel () {
Markup = String.Format ("{0}", GLib.Markup.EscapeText (Hyena.StringUtil.RemoveHtml (details.Description)))
};
var desc_expander = CreateSection (Catalog.GetString ("Description"), desc);
// Details
var table = new Banshee.Gui.TrackEditor.StatisticsPage () {
ShadowType = ShadowType.None,
BorderWidth = 0
};
table.NameRenderer.Scale = Pango.Scale.Medium;
table.ValueRenderer.Scale = Pango.Scale.Medium;
// Keep the table from needing to vertically scroll
table.Child.SizeRequested += (o, a) => {
table.SetSizeRequest (a.Requisition.Width, a.Requisition.Height);
};
AddToTable (table, Catalog.GetString ("Creator:"), details.Creator);
AddToTable (table, Catalog.GetString ("Venue:"), details.Venue);
AddToTable (table, Catalog.GetString ("Location:"), details.Coverage);
if (details.DateCreated != DateTime.MinValue) {
AddToTable (table, Catalog.GetString ("Date:"), details.DateCreated);
} else {
AddToTable (table, Catalog.GetString ("Year:"), details.Year);
}
AddToTable (table, Catalog.GetString ("Publisher:"), details.Publisher);
AddToTable (table, Catalog.GetString ("Keywords:"), details.Subject);
AddToTable (table, Catalog.GetString ("License URL:"), details.LicenseUrl);
AddToTable (table, Catalog.GetString ("Language:"), details.Language);
table.AddSeparator ();
AddToTable (table, Catalog.GetString ("Downloads, overall:"), details.DownloadsAllTime);
AddToTable (table, Catalog.GetString ("Downloads, past month:"), details.DownloadsLastMonth);
AddToTable (table, Catalog.GetString ("Downloads, past week:"), details.DownloadsLastWeek);
table.AddSeparator ();
AddToTable (table, Catalog.GetString ("Added:"), details.DateAdded);
AddToTable (table, Catalog.GetString ("Added by:"), details.AddedBy);
AddToTable (table, Catalog.GetString ("Collections:"), details.Collections);
AddToTable (table, Catalog.GetString ("Source:"), details.Source);
AddToTable (table, Catalog.GetString ("Contributor:"), details.Contributor);
AddToTable (table, Catalog.GetString ("Recorded by:"),details.Taper);
AddToTable (table, Catalog.GetString ("Lineage:"), details.Lineage);
AddToTable (table, Catalog.GetString ("Transferred by:"), details.Transferer);
var details_expander = CreateSection (Catalog.GetString ("Details"), table);
// Reviews
Section reviews = null;
if (details.NumReviews > 0) {
string [] stars = {
"\u2606\u2606\u2606\u2606\u2606",
"\u2605\u2606\u2606\u2606\u2606",
"\u2605\u2605\u2606\u2606\u2606",
"\u2605\u2605\u2605\u2606\u2606",
"\u2605\u2605\u2605\u2605\u2606",
"\u2605\u2605\u2605\u2605\u2605"
};
var reviews_box = new VBox () { Spacing = 12, BorderWidth = 0 };
reviews = CreateSection (Catalog.GetString ("Reviews"), reviews_box);
var avg_label = new Label (String.Format (Catalog.GetPluralString (
// Translators: {0} is the number of reviewers, {1} is the average rating (not really relevant if there's only 1)
"{0} reviewer", "{0} reviewers, avg {1}", details.NumReviews),
details.NumReviews, stars[Math.Max (0, Math.Min (5, (int)Math.Round (details.AvgRating)))]
));
avg_label.TooltipText = String.Format ("{0:N2}", details.AvgRating);
avg_label.Xalign = 1.0f;
reviews.Header.Box.PackEnd (avg_label, false, false, 0);
var sb = new System.Text.StringBuilder ();
foreach (var review in details.Reviews) {
//sb.Append ("<small>");
var review_txt = new Hyena.Widgets.WrapLabel ();
var title = review.Title;
if (title != null) {
sb.AppendFormat ("<b>{0}</b>\n", GLib.Markup.EscapeText (title));
}
// Translators: {0} is the unicode-stars-rating, {1} is the name of a person who reviewed this item, and {1} is a date/time string
sb.AppendFormat (Catalog.GetString ("{0} by {1} on {2}"),
stars[Math.Max (0, Math.Min (5, review.Stars))],
GLib.Markup.EscapeText (review.Reviewer),
GLib.Markup.EscapeText (review.DateReviewed.ToLocalTime ().ToShortDateString ())
);
var body = review.Body;
if (body != null) {
body = body.Replace ("\r\n", "\n");
body = body.Replace ("\n\n", "\n");
sb.Append ("\n");
sb.Append (GLib.Markup.EscapeText (body));
}
//sb.Append ("</small>");
review_txt.Markup = sb.ToString ();
sb.Length = 0;
reviews_box.PackStart (review_txt, false, false, 0);
}
}
// Packing
vbox.PackStart (desc_expander, true, true, 0);
vbox.PackStart (details_expander, true, true, 0);
if (reviews != null) {
vbox.PackStart (reviews, true, true, 0);
}
string write_review_url = String.Format ("http://www.archive.org/write-review.php?identifier={0}", item.Id);
var write_review_button = new LinkButton (write_review_url, Catalog.GetString ("Write your own review"));
write_review_button.Clicked += (o, a) => Banshee.Web.Browser.Open (write_review_url);
write_review_button.Xalign = 0f;
vbox.PackStart (write_review_button, false, false, 0);
var vbox2 = new VBox ();
vbox2.PackStart (vbox, false, false, 0);
var sw = new Gtk.ScrolledWindow () { ShadowType = ShadowType.None };
sw.AddWithViewport (vbox2);
(sw.Child as Viewport).ShadowType = ShadowType.None;
frame.Child = sw;
frame.ShowAll ();
sw.Child.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
sw.Child.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
sw.Child.ModifyText (StateType.Normal, Style.Text (StateType.Normal));
StyleSet += delegate {
sw.Child.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
sw.Child.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
sw.Child.ModifyText (StateType.Normal, Style.Text (StateType.Normal));
};
PackStart (frame, true, true, 0);
}
private void AddToTable (Banshee.Gui.TrackEditor.StatisticsPage table, string label, object val)
{
if (val != null) {
if (val is long) {
table.AddItem (label, ((long)val).ToString ("N0"));
} else if (val is DateTime) {
var dt = (DateTime)val;
if (dt != DateTime.MinValue) {
var local_dt = dt.ToLocalTime ();
var str = dt.TimeOfDay == TimeSpan.Zero
? local_dt.ToShortDateString ()
: local_dt.ToString ("g");
table.AddItem (label, str);
}
} else {
table.AddItem (label, val.ToString ());
}
}
}
private void BuildFilesBox ()
{
var vbox = new VBox ();
vbox.Spacing = 6;
var file_list = new BaseTrackListView () {
HeaderVisible = true,
IsEverReorderable = false
};
var files_model = source.TrackModel as MemoryTrackListModel;
var columns = new DefaultColumnController ();
columns.TrackColumn.Title = "#";
var file_columns = new ColumnController ();
file_columns.AddRange (
columns.IndicatorColumn,
columns.TrackColumn,
columns.TitleColumn,
columns.DurationColumn,
columns.FileSizeColumn
);
foreach (var col in file_columns) {
col.Visible = true;
}
var file_sw = new Gtk.ScrolledWindow ();
file_sw.Child = file_list;
var tracks = new List<TrackInfo> ();
var files = new List<IA.DetailsFile> (details.Files);
string [] format_blacklist = new string [] { "metadata", "fingerprint", "checksums", "xml", "m3u", "dublin core", "unknown" };
var formats = new List<string> ();
foreach (var f in files) {
var track = new TrackInfo () {
Uri = new SafeUri (f.Location),
FileSize = f.Size,
TrackNumber = f.Track,
ArtistName = f.Creator ?? details.Creator,
AlbumTitle = item.Title,
TrackTitle = f.Title,
BitRate = f.BitRate,
MimeType = f.Format,
Duration = f.Length
};
// Fix up duration/track#/title
if ((f.Length == TimeSpan.Zero || f.Title == null || f.Track == 0) && !f.Location.Contains ("zip") && !f.Location.EndsWith ("m3u")) {
foreach (var b in files) {
if ((f.Title != null && f.Title == b.Title)
|| (f.OriginalFile != null && b.Location != null && b.Location.EndsWith (f.OriginalFile))
|| (f.OriginalFile != null && f.OriginalFile == b.OriginalFile)) {
if (track.Duration == TimeSpan.Zero)
track.Duration = b.Length;
if (track.TrackTitle == null)
track.TrackTitle = b.Title;
if (track.TrackNumber == 0)
track.TrackNumber = b.Track;
if (track.Duration != TimeSpan.Zero && track.TrackTitle != null && track.TrackNumber != 0)
break;
}
}
}
track.TrackTitle = track.TrackTitle ?? System.IO.Path.GetFileName (f.Location);
tracks.Add (track);
if (f.Format != null && !formats.Contains (f.Format)) {
if (!format_blacklist.Any (fmt => f.Format.ToLower ().Contains (fmt))) {
formats.Add (f.Format);
}
}
}
// Order the formats according to the preferences
string format_order = String.Format (", {0}, {1}, {2},", HomeSource.VideoTypes.Get (), HomeSource.AudioTypes.Get (), HomeSource.TextTypes.Get ()).ToLower ();
var sorted_formats = formats.Select (f => new { Format = f, Order = Math.Max (format_order.IndexOf (", " + f.ToLower () + ","), format_order.IndexOf (f.ToLower ())) })
.OrderBy (o => o.Order == -1 ? Int32.MaxValue : o.Order);
// See if all the files contain their track #
bool all_tracks_have_num_in_title = tracks.All (t => t.TrackNumber == 0 || t.TrackTitle.Contains (t.TrackNumber.ToString ()));
// Make these columns snugly fix their data
if (tracks.Count > 0) {
// Mono in openSUSE 11.0 doesn't like this
//SetWidth (columns.TrackColumn, all_tracks_have_num_in_title ? 0 : tracks.Max (f => f.TrackNumber), 0);
int max_track = 0;
long max_size = 0;
foreach (var t in tracks) {
max_track = Math.Max (max_track, t.TrackNumber);
max_size = Math.Max (max_size, t.FileSize);
}
SetWidth (columns.TrackColumn, all_tracks_have_num_in_title ? 0 : max_track, 0);
// Mono in openSUSE 11.0 doesn't like this
//SetWidth (columns.FileSizeColumn, tracks.Max (f => f.FileSize), 0);
SetWidth (columns.FileSizeColumn, max_size, 0);
SetWidth (columns.DurationColumn, tracks.Max (f => f.Duration), TimeSpan.Zero);
}
string max_title = " ";
if (tracks.Count > 0) {
var sorted_by_title = files.Where (t => !t.Location.Contains ("zip"))
.OrderBy (f => f.Title == null ? 0 : f.Title.Length)
.ToList ();
string nine_tenths = sorted_by_title[(int)Math.Floor (.90 * sorted_by_title.Count)].Title ?? "";
string max = sorted_by_title[sorted_by_title.Count - 1].Title ?? "";
max_title = ((double)max.Length >= (double)(1.6 * (double)nine_tenths.Length)) ? nine_tenths : max;
}
(columns.TitleColumn.GetCell (0) as ColumnCellText).SetMinMaxStrings (max_title);
file_list.ColumnController = file_columns;
file_list.SetModel (files_model);
var format_list = ComboBox.NewText ();
format_list.RowSeparatorFunc = (model, iter) => {
return (string)model.GetValue (iter, 0) == "---";
};
bool have_sep = false;
int active_format = 0;
foreach (var fmt in sorted_formats) {
if (fmt.Order == -1 && !have_sep) {
have_sep = true;
if (format_list.Model.IterNChildren () > 0) {
format_list.AppendText ("---");
}
}
format_list.AppendText (fmt.Format);
if (active_format == 0 && fmt.Format == item.SelectedFormat) {
active_format = format_list.Model.IterNChildren () - 1;
}
}
format_list.Changed += (o, a) => {
files_model.Clear ();
var selected_fmt = format_list.ActiveText;
foreach (var track in tracks) {
if (track.MimeType == selected_fmt) {
files_model.Add (track);
}
}
files_model.Reload ();
item.SelectedFormat = selected_fmt;
item.Save ();
};
if (formats.Count > 0) {
format_list.Active = active_format;
}
vbox.PackStart (file_sw, true, true, 0);
vbox.PackStart (format_list, false, false, 0);
file_list.SizeAllocated += (o, a) => {
int target_list_width = file_list.MaxWidth;
if (file_sw.VScrollbar != null && file_sw.VScrollbar.IsMapped) {
target_list_width += file_sw.VScrollbar.Allocation.Width + 2;
}
// Don't let the track list be too wide
target_list_width = Math.Min (target_list_width, (int) (0.5 * (double)Allocation.Width));
if (a.Allocation.Width != target_list_width && target_list_width > 0) {
file_sw.SetSizeRequest (target_list_width, -1);
}
};
PackStart (vbox, false, false, 0);
}
private void SetWidth<T> (Column col, T max, T zero)
{
(col.GetCell (0) as ColumnCellText).SetMinMaxStrings (max, max);
if (zero.Equals (max)) {
col.Visible = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Xml.XPath;
using System.Xml.Xsl.Runtime;
using MS.Internal.Xml.XPath;
using System.Reflection;
using System.Security;
using System.Runtime.Versioning;
internal class XsltCompileContext : XsltContext
{
private InputScopeManager _manager;
private Processor _processor;
// storage for the functions
private static readonly Hashtable s_FunctionTable = CreateFunctionTable();
private static readonly IXsltContextFunction s_FuncNodeSet = new FuncNodeSet();
private const string f_NodeSet = "node-set";
internal XsltCompileContext(InputScopeManager manager, Processor processor) : base(/*dummy*/false)
{
_manager = manager;
_processor = processor;
}
internal XsltCompileContext() : base(/*dummy*/ false) { }
internal void Recycle()
{
_manager = null;
_processor = null;
}
internal void Reinitialize(InputScopeManager manager, Processor processor)
{
_manager = manager;
_processor = processor;
}
public override int CompareDocument(string baseUri, string nextbaseUri)
{
return string.Compare(baseUri, nextbaseUri, StringComparison.Ordinal);
}
// Namespace support
public override string DefaultNamespace
{
get { return string.Empty; }
}
public override string LookupNamespace(string prefix)
{
return _manager.ResolveXPathNamespace(prefix);
}
// --------------------------- XsltContext -------------------
// Resolving variables and functions
public override IXsltContextVariable ResolveVariable(string prefix, string name)
{
string namespaceURI = this.LookupNamespace(prefix);
XmlQualifiedName qname = new XmlQualifiedName(name, namespaceURI);
IXsltContextVariable variable = _manager.VariableScope.ResolveVariable(qname);
if (variable == null)
{
throw XsltException.Create(SR.Xslt_InvalidVariable, qname.ToString());
}
return variable;
}
internal object EvaluateVariable(VariableAction variable)
{
object result = _processor.GetVariableValue(variable);
if (result == null && !variable.IsGlobal)
{
// This was uninitialized local variable. May be we have sutable global var too?
VariableAction global = _manager.VariableScope.ResolveGlobalVariable(variable.Name);
if (global != null)
{
result = _processor.GetVariableValue(global);
}
}
if (result == null)
{
throw XsltException.Create(SR.Xslt_InvalidVariable, variable.Name.ToString());
}
return result;
}
// Whitespace stripping support
public override bool Whitespace
{
get { return _processor.Stylesheet.Whitespace; }
}
public override bool PreserveWhitespace(XPathNavigator node)
{
node = node.Clone();
node.MoveToParent();
return _processor.Stylesheet.PreserveWhiteSpace(_processor, node);
}
private MethodInfo FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[] argTypes)
{
int length = methods.Length;
int free = 0;
// restrict search to methods with the same name and requiested protection attribute
for (int i = 0; i < length; i++)
{
if (string.Equals(name, methods[i].Name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
if (!publicOnly || methods[i].GetBaseDefinition().IsPublic)
{
methods[free++] = methods[i];
}
}
}
length = free;
if (length == 0)
{
// this is the only place we returning null in this function
return null;
}
if (argTypes == null)
{
// without arg types we can't do more detailed search
return methods[0];
}
// restrict search by number of parameters
free = 0;
for (int i = 0; i < length; i++)
{
if (methods[i].GetParameters().Length == argTypes.Length)
{
methods[free++] = methods[i];
}
}
length = free;
if (length <= 1)
{
// 0 -- not method found. We have to return non-null and let it fail with correct exception on call.
// 1 -- no reason to continue search anyway.
return methods[0];
}
// restrict search by parameters type
free = 0;
for (int i = 0; i < length; i++)
{
bool match = true;
ParameterInfo[] parameters = methods[i].GetParameters();
for (int par = 0; par < parameters.Length; par++)
{
XPathResultType required = argTypes[par];
if (required == XPathResultType.Any)
{
continue; // Any means we don't know type and can't discriminate by it
}
XPathResultType actual = GetXPathType(parameters[par].ParameterType);
if (
actual != required &&
actual != XPathResultType.Any // actual arg is object and we can pass everithing here.
)
{
match = false;
break;
}
}
if (match)
{
methods[free++] = methods[i];
}
}
length = free;
return methods[0];
}
private const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
private IXsltContextFunction GetExtentionMethod(string ns, string name, XPathResultType[] argTypes, out object extension)
{
FuncExtension result = null;
extension = _processor.GetScriptObject(ns);
if (extension != null)
{
MethodInfo method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/true, /*publicOnly:*/false, name, argTypes);
if (method != null)
{
result = new FuncExtension(extension, method);
}
return result;
}
extension = _processor.GetExtensionObject(ns);
if (extension != null)
{
MethodInfo method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/false, /*publicOnly:*/true, name, argTypes);
if (method != null)
{
result = new FuncExtension(extension, method);
}
return result;
}
return null;
}
public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] argTypes)
{
IXsltContextFunction func = null;
if (prefix.Length == 0)
{
func = s_FunctionTable[name] as IXsltContextFunction;
}
else
{
string ns = this.LookupNamespace(prefix);
if (ns == XmlReservedNs.NsMsxsl && name == f_NodeSet)
{
func = s_FuncNodeSet;
}
else
{
object extension;
func = GetExtentionMethod(ns, name, argTypes, out extension);
if (extension == null)
{
throw XsltException.Create(SR.Xslt_ScriptInvalidPrefix, prefix); // BugBug: It's better to say that method 'name' not found
}
}
}
if (func == null)
{
throw XsltException.Create(SR.Xslt_UnknownXsltFunction, name);
}
if (argTypes.Length < func.Minargs || func.Maxargs < argTypes.Length)
{
throw XsltException.Create(SR.Xslt_WrongNumberArgs, name, argTypes.Length.ToString(CultureInfo.InvariantCulture));
}
return func;
}
//
// Xslt Function Extensions to XPath
//
private Uri ComposeUri(string thisUri, string baseUri)
{
Debug.Assert(thisUri != null && baseUri != null);
XmlResolver resolver = _processor.Resolver;
Uri uriBase = null;
if (baseUri.Length != 0)
{
uriBase = resolver.ResolveUri(null, baseUri);
}
return resolver.ResolveUri(uriBase, thisUri);
}
private XPathNodeIterator Document(object arg0, string baseUri)
{
XPathNodeIterator it = arg0 as XPathNodeIterator;
if (it != null)
{
ArrayList list = new ArrayList();
Hashtable documents = new Hashtable();
while (it.MoveNext())
{
Uri uri = ComposeUri(it.Current.Value, baseUri ?? it.Current.BaseURI);
if (!documents.ContainsKey(uri))
{
documents.Add(uri, null);
list.Add(_processor.GetNavigator(uri));
}
}
return new XPathArrayIterator(list);
}
else
{
return new XPathSingletonIterator(
_processor.GetNavigator(
ComposeUri(XmlConvert.ToXPathString(arg0), baseUri ?? _manager.Navigator.BaseURI)
)
);
}
}
private Hashtable BuildKeyTable(Key key, XPathNavigator root)
{
Hashtable keyTable = new Hashtable();
string matchStr = _processor.GetQueryExpression(key.MatchKey);
Query matchExpr = _processor.GetCompiledQuery(key.MatchKey);
Query useExpr = _processor.GetCompiledQuery(key.UseKey);
XPathNodeIterator sel = root.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ false);
while (sel.MoveNext())
{
XPathNavigator node = sel.Current;
EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable);
if (node.MoveToFirstAttribute())
{
do
{
EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable);
} while (node.MoveToNextAttribute());
node.MoveToParent();
}
}
return keyTable;
}
private static void AddKeyValue(Hashtable keyTable, string key, XPathNavigator value, bool checkDuplicates)
{
ArrayList list = (ArrayList)keyTable[key];
if (list == null)
{
list = new ArrayList();
keyTable.Add(key, list);
}
else
{
Debug.Assert(
value.ComparePosition((XPathNavigator)list[list.Count - 1]) != XmlNodeOrder.Before,
"The way we traversing nodes should garantees node-order"
);
if (checkDuplicates)
{
// it's posible that this value already was assosiated with current node
// but if this happened the node is last in the list of values.
if (value.ComparePosition((XPathNavigator)list[list.Count - 1]) == XmlNodeOrder.Same)
{
return;
}
}
else
{
Debug.Assert(
value.ComparePosition((XPathNavigator)list[list.Count - 1]) != XmlNodeOrder.Same,
"checkDuplicates == false : We can't have duplicates"
);
}
}
list.Add(value.Clone());
}
private static void EvaluateKey(XPathNavigator node, Query matchExpr, string matchStr, Query useExpr, Hashtable keyTable)
{
try
{
if (matchExpr.MatchNode(node) == null)
{
return;
}
}
catch (XPathException)
{
throw XsltException.Create(SR.Xslt_InvalidPattern, matchStr);
}
object result = useExpr.Evaluate(new XPathSingletonIterator(node, /*moved:*/true));
XPathNodeIterator it = result as XPathNodeIterator;
if (it != null)
{
bool checkDuplicates = false;
while (it.MoveNext())
{
AddKeyValue(keyTable, /*key:*/it.Current.Value, /*value:*/node, checkDuplicates);
checkDuplicates = true;
}
}
else
{
string key = XmlConvert.ToXPathString(result);
AddKeyValue(keyTable, key, /*value:*/node, /*checkDuplicates:*/ false);
}
}
private DecimalFormat ResolveFormatName(string formatName)
{
string ns = string.Empty, local = string.Empty;
if (formatName != null)
{
string prefix;
PrefixQName.ParseQualifiedName(formatName, out prefix, out local);
ns = LookupNamespace(prefix);
}
DecimalFormat formatInfo = _processor.RootAction.GetDecimalFormat(new XmlQualifiedName(local, ns));
if (formatInfo == null)
{
if (formatName != null)
{
throw XsltException.Create(SR.Xslt_NoDecimalFormat, formatName);
}
formatInfo = new DecimalFormat(new NumberFormatInfo(), '#', '0', ';');
}
return formatInfo;
}
// see http://www.w3.org/TR/xslt#function-element-available
private bool ElementAvailable(string qname)
{
string name, prefix;
PrefixQName.ParseQualifiedName(qname, out prefix, out name);
string ns = _manager.ResolveXmlNamespace(prefix);
// msxsl:script - is not an "instruction" so we return false for it.
if (ns == XmlReservedNs.NsXslt)
{
return (
name == "apply-imports" ||
name == "apply-templates" ||
name == "attribute" ||
name == "call-template" ||
name == "choose" ||
name == "comment" ||
name == "copy" ||
name == "copy-of" ||
name == "element" ||
name == "fallback" ||
name == "for-each" ||
name == "if" ||
name == "message" ||
name == "number" ||
name == "processing-instruction" ||
name == "text" ||
name == "value-of" ||
name == "variable"
);
}
return false;
}
// see: http://www.w3.org/TR/xslt#function-function-available
private bool FunctionAvailable(string qname)
{
string name, prefix;
PrefixQName.ParseQualifiedName(qname, out prefix, out name);
string ns = LookupNamespace(prefix);
if (ns == XmlReservedNs.NsMsxsl)
{
return name == f_NodeSet;
}
else if (ns.Length == 0)
{
return (
// It'll be better to get this information from XPath
name == "last" ||
name == "position" ||
name == "name" ||
name == "namespace-uri" ||
name == "local-name" ||
name == "count" ||
name == "id" ||
name == "string" ||
name == "concat" ||
name == "starts-with" ||
name == "contains" ||
name == "substring-before" ||
name == "substring-after" ||
name == "substring" ||
name == "string-length" ||
name == "normalize-space" ||
name == "translate" ||
name == "boolean" ||
name == "not" ||
name == "true" ||
name == "false" ||
name == "lang" ||
name == "number" ||
name == "sum" ||
name == "floor" ||
name == "ceiling" ||
name == "round" ||
// XSLT functions:
(s_FunctionTable[name] != null && name != "unparsed-entity-uri")
);
}
else
{
// Is this script or extention function?
object extension;
return GetExtentionMethod(ns, name, /*argTypes*/null, out extension) != null;
}
}
private XPathNodeIterator Current()
{
XPathNavigator nav = _processor.Current;
if (nav != null)
{
return new XPathSingletonIterator(nav.Clone());
}
return XPathEmptyIterator.Instance;
}
private string SystemProperty(string qname)
{
string result = string.Empty;
string prefix;
string local;
PrefixQName.ParseQualifiedName(qname, out prefix, out local);
// verify the prefix corresponds to the Xslt namespace
string urn = LookupNamespace(prefix);
if (urn == XmlReservedNs.NsXslt)
{
if (local == "version")
{
result = "1";
}
else if (local == "vendor")
{
result = "Microsoft";
}
else if (local == "vendor-url")
{
result = "http://www.microsoft.com";
}
}
else
{
if (urn == null && prefix != null)
{
// if prefix exist it has to be mapped to namespace.
// Can it be "" here ?
throw XsltException.Create(SR.Xslt_InvalidPrefix, prefix);
}
return string.Empty;
}
return result;
}
public static XPathResultType GetXPathType(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
return XPathResultType.String;
case TypeCode.Boolean:
return XPathResultType.Boolean;
case TypeCode.Object:
if (typeof(XPathNavigator).IsAssignableFrom(type) || typeof(IXPathNavigable).IsAssignableFrom(type))
{
return XPathResultType.Navigator;
}
if (typeof(XPathNodeIterator).IsAssignableFrom(type))
{
return XPathResultType.NodeSet;
}
// sdub: It be better to check that type is realy object and otherwise return XPathResultType.Error
return XPathResultType.Any;
case TypeCode.DateTime:
return XPathResultType.Error;
default: /* all numeric types */
return XPathResultType.Number;
}
}
// ---------------- Xslt Function Implementations -------------------
//
private static Hashtable CreateFunctionTable()
{
Hashtable ft = new Hashtable(10);
{
ft["current"] = new FuncCurrent();
ft["unparsed-entity-uri"] = new FuncUnEntityUri();
ft["generate-id"] = new FuncGenerateId();
ft["system-property"] = new FuncSystemProp();
ft["element-available"] = new FuncElementAvailable();
ft["function-available"] = new FuncFunctionAvailable();
ft["document"] = new FuncDocument();
ft["key"] = new FuncKey();
ft["format-number"] = new FuncFormatNumber();
}
return ft;
}
// + IXsltContextFunction
// + XsltFunctionImpl func. name, min/max args, return type args types
// FuncCurrent "current" 0 0 XPathResultType.NodeSet { }
// FuncUnEntityUri "unparsed-entity-uri" 1 1 XPathResultType.String { XPathResultType.String }
// FuncGenerateId "generate-id" 0 1 XPathResultType.String { XPathResultType.NodeSet }
// FuncSystemProp "system-property" 1 1 XPathResultType.String { XPathResultType.String }
// FuncElementAvailable "element-available" 1 1 XPathResultType.Boolean { XPathResultType.String }
// FuncFunctionAvailable "function-available" 1 1 XPathResultType.Boolean { XPathResultType.String }
// FuncDocument "document" 1 2 XPathResultType.NodeSet { XPathResultType.Any , XPathResultType.NodeSet }
// FuncKey "key" 2 2 XPathResultType.NodeSet { XPathResultType.String , XPathResultType.Any }
// FuncFormatNumber "format-number" 2 3 XPathResultType.String { XPathResultType.Number , XPathResultType.String, XPathResultType.String }
// FuncNodeSet "msxsl:node-set" 1 1 XPathResultType.NodeSet { XPathResultType.Navigator }
// FuncExtension
//
private abstract class XsltFunctionImpl : IXsltContextFunction
{
private int _minargs;
private int _maxargs;
private XPathResultType _returnType;
private XPathResultType[] _argTypes;
public XsltFunctionImpl() { }
public XsltFunctionImpl(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes)
{
this.Init(minArgs, maxArgs, returnType, argTypes);
}
protected void Init(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes)
{
_minargs = minArgs;
_maxargs = maxArgs;
_returnType = returnType;
_argTypes = argTypes;
}
public int Minargs { get { return _minargs; } }
public int Maxargs { get { return _maxargs; } }
public XPathResultType ReturnType { get { return _returnType; } }
public XPathResultType[] ArgTypes { get { return _argTypes; } }
public abstract object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext);
// static helper methods:
public static XPathNodeIterator ToIterator(object argument)
{
XPathNodeIterator it = argument as XPathNodeIterator;
if (it == null)
{
throw XsltException.Create(SR.Xslt_NoNodeSetConversion);
}
return it;
}
public static XPathNavigator ToNavigator(object argument)
{
XPathNavigator nav = argument as XPathNavigator;
if (nav == null)
{
throw XsltException.Create(SR.Xslt_NoNavigatorConversion);
}
return nav;
}
private static string IteratorToString(XPathNodeIterator it)
{
Debug.Assert(it != null);
if (it.MoveNext())
{
return it.Current.Value;
}
return string.Empty;
}
public static string ToString(object argument)
{
XPathNodeIterator it = argument as XPathNodeIterator;
if (it != null)
{
return IteratorToString(it);
}
else
{
return XmlConvert.ToXPathString(argument);
}
}
public static bool ToBoolean(object argument)
{
XPathNodeIterator it = argument as XPathNodeIterator;
if (it != null)
{
return Convert.ToBoolean(IteratorToString(it), CultureInfo.InvariantCulture);
}
XPathNavigator nav = argument as XPathNavigator;
if (nav != null)
{
return Convert.ToBoolean(nav.ToString(), CultureInfo.InvariantCulture);
}
return Convert.ToBoolean(argument, CultureInfo.InvariantCulture);
}
public static double ToNumber(object argument)
{
XPathNodeIterator it = argument as XPathNodeIterator;
if (it != null)
{
return XmlConvert.ToXPathDouble(IteratorToString(it));
}
XPathNavigator nav = argument as XPathNavigator;
if (nav != null)
{
return XmlConvert.ToXPathDouble(nav.ToString());
}
return XmlConvert.ToXPathDouble(argument);
}
private static object ToNumeric(object argument, Type type)
{
return Convert.ChangeType(ToNumber(argument), type, CultureInfo.InvariantCulture);
}
public static object ConvertToXPathType(object val, XPathResultType xt, Type type)
{
switch (xt)
{
case XPathResultType.String:
// Unfortunetely XPathResultType.String == XPathResultType.Navigator (This is wrong but cant be changed in Everett)
// Fortunetely we have typeCode hare so let's discriminate by typeCode
if (type == typeof(string))
{
return ToString(val);
}
else
{
return ToNavigator(val);
}
case XPathResultType.Number: return ToNumeric(val, type);
case XPathResultType.Boolean: return ToBoolean(val);
case XPathResultType.NodeSet: return ToIterator(val);
// case XPathResultType.Navigator : return ToNavigator(val);
case XPathResultType.Any:
case XPathResultType.Error:
return val;
default:
Debug.Fail("unexpected XPath type");
return val;
}
}
}
private class FuncCurrent : XsltFunctionImpl
{
public FuncCurrent() : base(0, 0, XPathResultType.NodeSet, Array.Empty<XPathResultType>()) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
return ((XsltCompileContext)xsltContext).Current();
}
}
private class FuncUnEntityUri : XsltFunctionImpl
{
public FuncUnEntityUri() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
throw XsltException.Create(SR.Xslt_UnsuppFunction, "unparsed-entity-uri");
}
}
private class FuncGenerateId : XsltFunctionImpl
{
public FuncGenerateId() : base(0, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.NodeSet }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
if (args.Length > 0)
{
XPathNodeIterator it = ToIterator(args[0]);
if (it.MoveNext())
{
return it.Current.UniqueId;
}
else
{
// if empty nodeset, return empty string, otherwise return generated id
return string.Empty;
}
}
else
{
return docContext.UniqueId;
}
}
}
private class FuncSystemProp : XsltFunctionImpl
{
public FuncSystemProp() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
return ((XsltCompileContext)xsltContext).SystemProperty(ToString(args[0]));
}
}
// see http://www.w3.org/TR/xslt#function-element-available
private class FuncElementAvailable : XsltFunctionImpl
{
public FuncElementAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
return ((XsltCompileContext)xsltContext).ElementAvailable(ToString(args[0]));
}
}
// see: http://www.w3.org/TR/xslt#function-function-available
private class FuncFunctionAvailable : XsltFunctionImpl
{
public FuncFunctionAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
return ((XsltCompileContext)xsltContext).FunctionAvailable(ToString(args[0]));
}
}
private class FuncDocument : XsltFunctionImpl
{
public FuncDocument() : base(1, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Any, XPathResultType.NodeSet }) { }
// SxS: This method uses resource names read from source document and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
string baseUri = null;
if (args.Length == 2)
{
XPathNodeIterator it = ToIterator(args[1]);
if (it.MoveNext())
{
baseUri = it.Current.BaseURI;
}
else
{
// http://www.w3.org/1999/11/REC-xslt-19991116-errata (E14):
// It is an error if the second argument node-set is empty and the URI reference is relative; the XSLT processor may signal the error;
// if it does not signal an error, it must recover by returning an empty node-set.
baseUri = string.Empty; // call to Document will fail if args[0] is reletive.
}
}
try
{
return ((XsltCompileContext)xsltContext).Document(args[0], baseUri);
}
catch (Exception e)
{
if (!XmlException.IsCatchableException(e))
{
throw;
}
return XPathEmptyIterator.Instance;
}
}
}
private class FuncKey : XsltFunctionImpl
{
public FuncKey() : base(2, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.String, XPathResultType.Any }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
XsltCompileContext xsltCompileContext = (XsltCompileContext)xsltContext;
string local, prefix;
PrefixQName.ParseQualifiedName(ToString(args[0]), out prefix, out local);
string ns = xsltContext.LookupNamespace(prefix);
XmlQualifiedName keyName = new XmlQualifiedName(local, ns);
XPathNavigator root = docContext.Clone();
root.MoveToRoot();
ArrayList resultCollection = null;
foreach (Key key in xsltCompileContext._processor.KeyList)
{
if (key.Name == keyName)
{
Hashtable keyTable = key.GetKeys(root);
if (keyTable == null)
{
keyTable = xsltCompileContext.BuildKeyTable(key, root);
key.AddKey(root, keyTable);
}
XPathNodeIterator it = args[1] as XPathNodeIterator;
if (it != null)
{
it = it.Clone();
while (it.MoveNext())
{
resultCollection = AddToList(resultCollection, (ArrayList)keyTable[it.Current.Value]);
}
}
else
{
resultCollection = AddToList(resultCollection, (ArrayList)keyTable[ToString(args[1])]);
}
}
}
if (resultCollection == null)
{
return XPathEmptyIterator.Instance;
}
else if (resultCollection[0] is XPathNavigator)
{
return new XPathArrayIterator(resultCollection);
}
else
{
return new XPathMultyIterator(resultCollection);
}
}
private static ArrayList AddToList(ArrayList resultCollection, ArrayList newList)
{
if (newList == null)
{
return resultCollection;
}
if (resultCollection == null)
{
return newList;
}
Debug.Assert(resultCollection.Count != 0);
Debug.Assert(newList.Count != 0);
if (!(resultCollection[0] is ArrayList))
{
// Transform resultCollection from ArrayList(XPathNavigator) to ArrayList(ArrayList(XPathNavigator))
Debug.Assert(resultCollection[0] is XPathNavigator);
ArrayList firstList = resultCollection;
resultCollection = new ArrayList();
resultCollection.Add(firstList);
}
resultCollection.Add(newList);
return resultCollection;
}
}
private class FuncFormatNumber : XsltFunctionImpl
{
public FuncFormatNumber() : base(2, 3, XPathResultType.String, new XPathResultType[] { XPathResultType.Number, XPathResultType.String, XPathResultType.String }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
DecimalFormat formatInfo = ((XsltCompileContext)xsltContext).ResolveFormatName(args.Length == 3 ? ToString(args[2]) : null);
return DecimalFormatter.Format(ToNumber(args[0]), ToString(args[1]), formatInfo);
}
}
private class FuncNodeSet : XsltFunctionImpl
{
public FuncNodeSet() : base(1, 1, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Navigator }) { }
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
return new XPathSingletonIterator(ToNavigator(args[0]));
}
}
private class FuncExtension : XsltFunctionImpl
{
private readonly object _extension;
private readonly MethodInfo _method;
private readonly Type[] _types;
public FuncExtension(object extension, MethodInfo method)
{
Debug.Assert(extension != null);
Debug.Assert(method != null);
_extension = extension;
_method = method;
XPathResultType returnType = GetXPathType(method.ReturnType);
ParameterInfo[] parameters = method.GetParameters();
int minArgs = parameters.Length;
int maxArgs = parameters.Length;
_types = new Type[parameters.Length];
XPathResultType[] argTypes = new XPathResultType[parameters.Length];
bool optionalParams = true; // we allow only last params be optional. Set false on the first non optional.
for (int i = parameters.Length - 1; 0 <= i; i--)
{ // Revers order is essential: counting optional parameters
_types[i] = parameters[i].ParameterType;
argTypes[i] = GetXPathType(parameters[i].ParameterType);
if (optionalParams)
{
if (parameters[i].IsOptional)
{
minArgs--;
}
else
{
optionalParams = false;
}
}
}
base.Init(minArgs, maxArgs, returnType, argTypes);
}
public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
{
Debug.Assert(args.Length <= this.Minargs, "We cheking this on resolve time");
for (int i = args.Length - 1; 0 <= i; i--)
{
args[i] = ConvertToXPathType(args[i], this.ArgTypes[i], _types[i]);
}
return _method.Invoke(_extension, args);
}
}
}
}
| |
using System;
using UnityEditor.Rendering;
using UnityEngine;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// TODO: Should be cleaned up and put into CoreRP/Editor
sealed class TrackballUIDrawer
{
static readonly int s_ThumbHash = "colorWheelThumb".GetHashCode();
static GUIStyle s_WheelThumb;
static Vector2 s_WheelThumbSize;
static Material s_Material;
Func<Vector4, Vector3> m_ComputeFunc;
bool m_ResetState;
Vector2 m_CursorPos;
static TrackballUIDrawer()
{
if (s_Material == null)
s_Material = new Material(Shader.Find("Hidden/HD PostProcessing/Editor/Trackball")) { hideFlags = HideFlags.HideAndDontSave };
}
public void OnGUI(SerializedProperty property, SerializedProperty overrideState, GUIContent title, Func<Vector4, Vector3> computeFunc)
{
if (property.propertyType != SerializedPropertyType.Vector4)
{
Debug.LogWarning("TrackballUIDrawer requires a Vector4 property");
return;
}
m_ComputeFunc = computeFunc;
var value = property.vector4Value;
using (new EditorGUILayout.VerticalScope())
{
using (new EditorGUI.DisabledScope(!overrideState.boolValue))
DrawWheel(ref value, overrideState.boolValue);
DrawLabelAndOverride(title, overrideState);
}
if (m_ResetState)
{
value = new Vector4(1f, 1f, 1f, 0f);
m_ResetState = false;
}
property.vector4Value = value;
}
void DrawWheel(ref Vector4 value, bool overrideState)
{
var wheelRect = GUILayoutUtility.GetAspectRect(1f);
float size = wheelRect.width;
float hsize = size / 2f;
float radius = 0.38f * size;
Vector3 hsv;
Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z);
float offset = value.w;
// Thumb
var thumbPos = Vector2.zero;
float theta = hsv.x * (Mathf.PI * 2f);
thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f));
thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f));
thumbPos *= hsv.y * radius;
// Draw the wheel
if (Event.current.type == EventType.Repaint)
{
// Style init
if (s_WheelThumb == null)
{
s_WheelThumb = new GUIStyle("ColorPicker2DThumb");
s_WheelThumbSize = new Vector2(
!Mathf.Approximately(s_WheelThumb.fixedWidth, 0f) ? s_WheelThumb.fixedWidth : s_WheelThumb.padding.horizontal,
!Mathf.Approximately(s_WheelThumb.fixedHeight, 0f) ? s_WheelThumb.fixedHeight : s_WheelThumb.padding.vertical
);
}
// Retina support
float scale = EditorGUIUtility.pixelsPerPoint;
// Wheel texture
var oldRT = RenderTexture.active;
var rt = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
s_Material.SetFloat("_Offset", offset);
s_Material.SetFloat("_DisabledState", overrideState && GUI.enabled ? 1f : 0.5f);
s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f));
Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1);
RenderTexture.active = oldRT;
GUI.DrawTexture(wheelRect, rt);
RenderTexture.ReleaseTemporary(rt);
var thumbSize = s_WheelThumbSize;
var thumbSizeH = thumbSize / 2f;
s_WheelThumb.Draw(new Rect(wheelRect.x + hsize + thumbPos.x - thumbSizeH.x, wheelRect.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
}
// Input
var bounds = wheelRect;
bounds.x += hsize - radius;
bounds.y += hsize - radius;
bounds.width = bounds.height = radius * 2f;
hsv = GetInput(bounds, hsv, thumbPos, radius);
value = Color.HSVToRGB(hsv.x, hsv.y, 1f);
value.w = offset;
// Offset
var sliderRect = GUILayoutUtility.GetRect(1f, 17f);
float padding = sliderRect.width * 0.05f; // 5% padding
sliderRect.xMin += padding;
sliderRect.xMax -= padding;
value.w = GUI.HorizontalSlider(sliderRect, value.w, -1f, 1f);
if (m_ComputeFunc == null)
return;
// Values
var displayValue = m_ComputeFunc(value);
using (new EditorGUI.DisabledGroupScope(true))
{
var valuesRect = GUILayoutUtility.GetRect(1f, 17f);
valuesRect.width /= 3f;
GUI.Label(valuesRect, displayValue.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
GUI.Label(valuesRect, displayValue.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
GUI.Label(valuesRect, displayValue.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
}
}
void DrawLabelAndOverride(GUIContent title, SerializedProperty overrideState)
{
// Title
var areaRect = GUILayoutUtility.GetRect(1f, 17f);
var labelSize = EditorStyles.miniLabel.CalcSize(title);
var labelRect = new Rect(areaRect.x + areaRect.width / 2 - labelSize.x / 2, areaRect.y, labelSize.x, labelSize.y);
GUI.Label(labelRect, title, EditorStyles.miniLabel);
// Override checkbox
var overrideRect = new Rect(labelRect.x - 17, labelRect.y + 3, 17f, 17f);
overrideState.boolValue = GUI.Toggle(overrideRect, overrideState.boolValue, EditorGUIUtility.TrTextContent("", "Override this setting for this volume."), CoreEditorStyles.smallTickbox);
}
Vector3 GetInput(Rect bounds, Vector3 hsv, Vector2 thumbPos, float radius)
{
var e = Event.current;
var id = GUIUtility.GetControlID(s_ThumbHash, FocusType.Passive, bounds);
var mousePos = e.mousePosition;
if (e.type == EventType.MouseDown && GUIUtility.hotControl == 0 && bounds.Contains(mousePos))
{
if (e.button == 0)
{
var center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
m_CursorPos = new Vector2(thumbPos.x + radius, thumbPos.y + radius);
GUIUtility.hotControl = id;
GUI.changed = true;
}
}
else if (e.button == 1)
{
e.Use();
GUI.changed = true;
m_ResetState = true;
}
}
else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUI.changed = true;
m_CursorPos += e.delta * 0.2f; // Sensitivity
GetWheelHueSaturation(m_CursorPos.x, m_CursorPos.y, radius, out hsv.x, out hsv.y);
}
else if (e.rawType == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUIUtility.hotControl = 0;
}
return hsv;
}
void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation)
{
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
hue = Mathf.Atan2(dx, -dy);
hue = 1f - ((hue > 0) ? hue : (Mathf.PI * 2f) + hue) / (Mathf.PI * 2f);
saturation = Mathf.Clamp01(d);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using Newtonsoft.Json;
using System.Threading;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Logging;
using System.Threading.Tasks;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Represents the base Brokerage implementation. This provides logging on brokerage events.
/// </summary>
public abstract class Brokerage : IBrokerage
{
// 7:45 AM (New York time zone)
private static readonly TimeSpan LiveBrokerageCashSyncTime = new TimeSpan(7, 45, 0);
private readonly object _performCashSyncReentranceGuard = new object();
private bool _syncedLiveBrokerageCashToday = true;
private long _lastSyncTimeTicks = DateTime.UtcNow.Ticks;
/// <summary>
/// Event that fires each time an order is filled
/// </summary>
public event EventHandler<OrderEvent> OrderStatusChanged;
/// <summary>
/// Event that fires each time a short option position is assigned
/// </summary>
public event EventHandler<OrderEvent> OptionPositionAssigned;
/// <summary>
/// Event that fires each time an option position has changed
/// </summary>
public event EventHandler<OptionNotificationEventArgs> OptionNotification;
/// <summary>
/// Event that fires each time a delisting occurs
/// </summary>
public event EventHandler<DelistingNotificationEventArgs> DelistingNotification;
/// <summary>
/// Event that fires each time a user's brokerage account is changed
/// </summary>
public event EventHandler<AccountEvent> AccountChanged;
/// <summary>
/// Event that fires when an error is encountered in the brokerage
/// </summary>
public event EventHandler<BrokerageMessageEvent> Message;
/// <summary>
/// Gets the name of the brokerage
/// </summary>
public string Name { get; }
/// <summary>
/// Returns true if we're currently connected to the broker
/// </summary>
public abstract bool IsConnected { get; }
/// <summary>
/// Creates a new Brokerage instance with the specified name
/// </summary>
/// <param name="name">The name of the brokerage</param>
protected Brokerage(string name)
{
Name = name;
}
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
public abstract bool PlaceOrder(Order order);
/// <summary>
/// Updates the order with the same id
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
public abstract bool UpdateOrder(Order order);
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was made for the order to be canceled, false otherwise</returns>
public abstract bool CancelOrder(Order order);
/// <summary>
/// Connects the client to the broker's remote servers
/// </summary>
public abstract void Connect();
/// <summary>
/// Disconnects the client from the broker's remote servers
/// </summary>
public abstract void Disconnect();
/// <summary>
/// Dispose of the brokerage instance
/// </summary>
public virtual void Dispose()
{
// NOP
}
/// <summary>
/// Event invocator for the OrderFilled event
/// </summary>
/// <param name="e">The OrderEvent</param>
protected virtual void OnOrderEvent(OrderEvent e)
{
try
{
OrderStatusChanged?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the OptionPositionAssigned event
/// </summary>
/// <param name="e">The OrderEvent</param>
protected virtual void OnOptionPositionAssigned(OrderEvent e)
{
try
{
Log.Debug("Brokerage.OptionPositionAssigned(): " + e);
OptionPositionAssigned?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the OptionNotification event
/// </summary>
/// <param name="e">The OptionNotification event arguments</param>
protected virtual void OnOptionNotification(OptionNotificationEventArgs e)
{
try
{
Log.Debug("Brokerage.OnOptionNotification(): " + e);
OptionNotification?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the DelistingNotification event
/// </summary>
/// <param name="e">The DelistingNotification event arguments</param>
protected virtual void OnDelistingNotification(DelistingNotificationEventArgs e)
{
try
{
Log.Debug("Brokerage.OnDelistingNotification(): " + e);
DelistingNotification?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the AccountChanged event
/// </summary>
/// <param name="e">The AccountEvent</param>
protected virtual void OnAccountChanged(AccountEvent e)
{
try
{
Log.Trace($"Brokerage.OnAccountChanged(): {e}");
AccountChanged?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the Message event
/// </summary>
/// <param name="e">The error</param>
protected virtual void OnMessage(BrokerageMessageEvent e)
{
try
{
if (e.Type == BrokerageMessageType.Error)
{
Log.Error("Brokerage.OnMessage(): " + e);
}
else
{
Log.Trace("Brokerage.OnMessage(): " + e);
}
Message?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Helper method that will try to get the live holdings from the provided brokerage data collection else will default to the algorithm state
/// </summary>
/// <remarks>Holdings will removed from the provided collection on the first call, since this method is expected to be called only
/// once on initialize, after which the algorithm should use Lean accounting</remarks>
protected virtual List<Holding> GetAccountHoldings(Dictionary<string, string> brokerageData, IEnumerable<Security> securities)
{
if (Log.DebuggingEnabled)
{
Log.Debug("Brokerage.GetAccountHoldings(): starting...");
}
if (brokerageData != null && brokerageData.Remove("live-holdings", out var value) && !string.IsNullOrEmpty(value))
{
// remove the key, we really only want to return the cached value on the first request
var result = JsonConvert.DeserializeObject<List<Holding>>(value);
if (result == null)
{
return new List<Holding>();
}
Log.Trace($"Brokerage.GetAccountHoldings(): sourcing holdings from provided brokerage data, found {result.Count} entries");
return result;
}
return securities?.Where(security => security.Holdings.AbsoluteQuantity > 0)
.OrderBy(security => security.Symbol)
.Select(security => new Holding(security)).ToList() ?? new List<Holding>();
}
/// <summary>
/// Helper method that will try to get the live cash balance from the provided brokerage data collection else will default to the algorithm state
/// </summary>
/// <remarks>Cash balance will removed from the provided collection on the first call, since this method is expected to be called only
/// once on initialize, after which the algorithm should use Lean accounting</remarks>
protected virtual List<CashAmount> GetCashBalance(Dictionary<string, string> brokerageData, CashBook cashBook)
{
if (Log.DebuggingEnabled)
{
Log.Debug("Brokerage.GetCashBalance(): starting...");
}
if (brokerageData != null && brokerageData.Remove("live-cash-balance", out var value) && !string.IsNullOrEmpty(value))
{
// remove the key, we really only want to return the cached value on the first request
var result = JsonConvert.DeserializeObject<List<CashAmount>>(value);
if (result == null)
{
return new List<CashAmount>();
}
Log.Trace($"Brokerage.GetCashBalance(): sourcing cash balance from provided brokerage data, found {result.Count} entries");
return result;
}
return cashBook?.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList() ?? new List<CashAmount>();
}
/// <summary>
/// Gets all open orders on the account.
/// NOTE: The order objects returned do not have QC order IDs.
/// </summary>
/// <returns>The open orders returned from IB</returns>
public abstract List<Order> GetOpenOrders();
/// <summary>
/// Gets all holdings for the account
/// </summary>
/// <returns>The current holdings from the account</returns>
public abstract List<Holding> GetAccountHoldings();
/// <summary>
/// Gets the current cash balance for each currency held in the brokerage account
/// </summary>
/// <returns>The current cash balance for each currency available for trading</returns>
public abstract List<CashAmount> GetCashBalance();
/// <summary>
/// Specifies whether the brokerage will instantly update account balances
/// </summary>
public virtual bool AccountInstantlyUpdated => false;
/// <summary>
/// Returns the brokerage account's base currency
/// </summary>
public virtual string AccountBaseCurrency { get; protected set; }
/// <summary>
/// Gets the history for the requested security
/// </summary>
/// <param name="request">The historical data request</param>
/// <returns>An enumerable of bars covering the span specified in the request</returns>
public virtual IEnumerable<BaseData> GetHistory(HistoryRequest request)
{
return Enumerable.Empty<BaseData>();
}
#region IBrokerageCashSynchronizer implementation
/// <summary>
/// Gets the date of the last sync (New York time zone)
/// </summary>
protected DateTime LastSyncDate => LastSyncDateTimeUtc.ConvertFromUtc(TimeZones.NewYork).Date;
/// <summary>
/// Gets the datetime of the last sync (UTC)
/// </summary>
public DateTime LastSyncDateTimeUtc => new DateTime(Interlocked.Read(ref _lastSyncTimeTicks));
/// <summary>
/// Returns whether the brokerage should perform the cash synchronization
/// </summary>
/// <param name="currentTimeUtc">The current time (UTC)</param>
/// <returns>True if the cash sync should be performed</returns>
public virtual bool ShouldPerformCashSync(DateTime currentTimeUtc)
{
// every morning flip this switch back
var currentTimeNewYork = currentTimeUtc.ConvertFromUtc(TimeZones.NewYork);
if (_syncedLiveBrokerageCashToday && currentTimeNewYork.Date != LastSyncDate)
{
_syncedLiveBrokerageCashToday = false;
}
return !_syncedLiveBrokerageCashToday && currentTimeNewYork.TimeOfDay >= LiveBrokerageCashSyncTime;
}
/// <summary>
/// Synchronizes the cashbook with the brokerage account
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="currentTimeUtc">The current time (UTC)</param>
/// <param name="getTimeSinceLastFill">A function which returns the time elapsed since the last fill</param>
/// <returns>True if the cash sync was performed successfully</returns>
public virtual bool PerformCashSync(IAlgorithm algorithm, DateTime currentTimeUtc, Func<TimeSpan> getTimeSinceLastFill)
{
try
{
// prevent reentrance in this method
if (!Monitor.TryEnter(_performCashSyncReentranceGuard))
{
Log.Trace("Brokerage.PerformCashSync(): Reentrant call, cash sync not performed");
return false;
}
Log.Trace("Brokerage.PerformCashSync(): Sync cash balance");
var balances = new List<CashAmount>();
try
{
balances = GetCashBalance();
}
catch (Exception err)
{
Log.Error(err, "Error in GetCashBalance:");
}
if (balances.Count == 0)
{
Log.Trace("Brokerage.PerformCashSync(): No cash balances available, cash sync not performed");
return false;
}
// Adds currency to the cashbook that the user might have deposited
foreach (var balance in balances)
{
if (!algorithm.Portfolio.CashBook.ContainsKey(balance.Currency))
{
Log.Trace($"Brokerage.PerformCashSync(): Unexpected cash found {balance.Currency} {balance.Amount}", true);
algorithm.Portfolio.SetCash(balance.Currency, balance.Amount, 0);
}
}
// if we were returned our balances, update everything and flip our flag as having performed sync today
foreach (var kvp in algorithm.Portfolio.CashBook)
{
var cash = kvp.Value;
//update the cash if the entry if found in the balances
var balanceCash = balances.Find(balance => balance.Currency == cash.Symbol);
if (balanceCash != default(CashAmount))
{
// compare in account currency
var delta = cash.Amount - balanceCash.Amount;
if (Math.Abs(algorithm.Portfolio.CashBook.ConvertToAccountCurrency(delta, cash.Symbol)) > 5)
{
// log the delta between
Log.Trace($"Brokerage.PerformCashSync(): {balanceCash.Currency} Delta: {delta:0.00}", true);
}
algorithm.Portfolio.CashBook[cash.Symbol].SetAmount(balanceCash.Amount);
}
else
{
//Set the cash amount to zero if cash entry not found in the balances
Log.Trace($"Brokerage.PerformCashSync(): {cash.Symbol} was not found in brokerage cash balance, setting the amount to 0", true);
algorithm.Portfolio.CashBook[cash.Symbol].SetAmount(0);
}
}
_syncedLiveBrokerageCashToday = true;
_lastSyncTimeTicks = currentTimeUtc.Ticks;
}
finally
{
Monitor.Exit(_performCashSyncReentranceGuard);
}
// fire off this task to check if we've had recent fills, if we have then we'll invalidate the cash sync
// and do it again until we're confident in it
Task.Delay(TimeSpan.FromSeconds(10)).ContinueWith(_ =>
{
// we want to make sure this is a good value, so check for any recent fills
if (getTimeSinceLastFill() <= TimeSpan.FromSeconds(20))
{
// this will cause us to come back in and reset cash again until we
// haven't processed a fill for +- 10 seconds of the set cash time
_syncedLiveBrokerageCashToday = false;
//_failedCashSyncAttempts = 0;
Log.Trace("Brokerage.PerformCashSync(): Unverified cash sync - resync required.");
}
else
{
Log.Trace("Brokerage.PerformCashSync(): Verified cash sync.");
algorithm.Portfolio.LogMarginInformation();
}
});
return true;
}
#endregion
}
}
| |
using System.Windows.Forms;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI.Native;
using DevExpress.Utils;
using DevExpress.Internal;
using DevExpress.Xpf.Core.Native;
using System.Windows.Interop;
using DxFileCustomPlaces = System.Windows.Forms.FileDialogCustomPlacesCollection;
using DxDialogResult = System.Windows.Forms.DialogResult;
namespace DevExpress.Mvvm.UI.Native {
public class Win32WindowWrapper : System.Windows.Forms.IWin32Window {
public IntPtr Handle { get; private set; }
public Win32WindowWrapper(IntPtr handle) {
Handle = handle;
}
public Win32WindowWrapper(Window window) {
if(window.IsLoaded)
Handle = new WindowInteropHelper(window).Handle;
}
}
public interface ICommonDialog : IDisposable {
event EventHandler HelpRequest;
DialogResult ShowDialog();
DialogResult ShowDialog(object owner);
void Reset();
}
public interface IFileDialog : ICommonDialog {
bool AddExtension { get; set; }
bool CheckFileExists { get; set; }
bool CheckPathExists { get; set; }
FileDialogCustomPlacesCollection CustomPlaces { get; }
string DefaultExt { get; set; }
bool DereferenceLinks { get; set; }
string FileName { get; set; }
string[] FileNames { get; }
string Filter { get; set; }
int FilterIndex { get; set; }
string InitialDirectory { get; set; }
bool RestoreDirectory { get; set; }
bool ShowHelp { get; set; }
bool SupportMultiDottedExtensions { get; set; }
string Title { get; set; }
bool ValidateNames { get; set; }
event CancelEventHandler FileOk;
}
}
namespace DevExpress.Mvvm.UI {
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public abstract class FileDialogServiceBase : WindowAwareServiceBase, IFileDialogServiceBase {
protected abstract class FileDialogAdapter<TFileDialog> : IFileDialog where TFileDialog : FileDialog {
protected readonly TFileDialog fileDialog;
public event CancelEventHandler FileOk;
public event EventHandler HelpRequest;
public FileDialogAdapter(TFileDialog fileDialog) {
this.fileDialog = fileDialog;
this.fileDialog.FileOk += OnDialogFileOk;
this.fileDialog.HelpRequest += OnDialogHelpRequest;
}
bool IFileDialog.CheckPathExists {
get { return fileDialog.CheckPathExists; }
set { fileDialog.CheckPathExists = value; }
}
bool IFileDialog.CheckFileExists {
get { return fileDialog.CheckFileExists; }
set { fileDialog.CheckFileExists = value; }
}
bool IFileDialog.AddExtension {
get { return fileDialog.AddExtension; }
set { fileDialog.AddExtension = value; }
}
bool IFileDialog.DereferenceLinks {
get { return fileDialog.DereferenceLinks; }
set { fileDialog.DereferenceLinks = value; }
}
bool IFileDialog.RestoreDirectory {
get { return fileDialog.RestoreDirectory; }
set { fileDialog.RestoreDirectory = value; }
}
bool IFileDialog.ShowHelp {
get { return fileDialog.ShowHelp; }
set { fileDialog.ShowHelp = value; }
}
bool IFileDialog.SupportMultiDottedExtensions {
get { return fileDialog.SupportMultiDottedExtensions; }
set { fileDialog.SupportMultiDottedExtensions = value; }
}
bool IFileDialog.ValidateNames {
get { return fileDialog.ValidateNames; }
set { fileDialog.ValidateNames = value; }
}
string IFileDialog.InitialDirectory {
get { return fileDialog.InitialDirectory; }
set { fileDialog.InitialDirectory = value; }
}
string IFileDialog.Title {
get { return fileDialog.Title; }
set { fileDialog.Title = value; }
}
string[] IFileDialog.FileNames { get { return fileDialog.FileNames; } }
string IFileDialog.Filter {
get { return fileDialog.Filter; }
set { fileDialog.Filter = value; }
}
int IFileDialog.FilterIndex {
get { return fileDialog.FilterIndex; }
set { fileDialog.FilterIndex = value; }
}
string IFileDialog.FileName {
get { return fileDialog.FileName; }
set { fileDialog.FileName = value; }
}
string IFileDialog.DefaultExt {
get { return fileDialog.DefaultExt; }
set { fileDialog.DefaultExt = value; }
}
DxFileCustomPlaces IFileDialog.CustomPlaces {
get {
return fileDialog.CustomPlaces;
}
}
void ICommonDialog.Reset() {
fileDialog.Reset();
}
public DialogResult ShowDialog() {
return fileDialog.ShowDialog();
}
public DialogResult ShowDialog(Window ownerWindow) {
return fileDialog.ShowDialog(new Win32WindowWrapper(ownerWindow));
}
DxDialogResult ICommonDialog.ShowDialog(object ownerWindow) {
var window = ownerWindow as Window;
var dialogResult = window == null ? ShowDialog() : ShowDialog(window);
return Convert(dialogResult);
}
DxDialogResult ICommonDialog.ShowDialog() {
var dialogResult = ShowDialog();
return Convert(dialogResult);
}
void OnDialogFileOk(object sender, CancelEventArgs e) {
if(FileOk != null)
FileOk(sender, e);
}
void OnDialogHelpRequest(object sender, EventArgs e) {
if(HelpRequest != null)
HelpRequest(sender, e);
}
void IDisposable.Dispose() {
fileDialog.Dispose();
}
static DxDialogResult Convert(DialogResult result) {
switch (result) {
case DialogResult.OK:
return DxDialogResult.OK;
case DialogResult.Cancel:
return DxDialogResult.Cancel;
case DialogResult.Abort:
return DxDialogResult.Abort;
case DialogResult.Retry:
return DxDialogResult.Retry;
case DialogResult.Ignore:
return DxDialogResult.Ignore;
case DialogResult.Yes:
return DxDialogResult.Yes;
case DialogResult.No:
return DxDialogResult.No;
default:
return DxDialogResult.None;
}
}
}
public static readonly DependencyProperty CheckFileExistsProperty =
DependencyProperty.Register("CheckFileExists", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false));
public static readonly DependencyProperty AddExtensionProperty =
DependencyProperty.Register("AddExtension", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty AutoUpgradeEnabledProperty =
DependencyProperty.Register("AutoUpgradeEnabled", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty CheckPathExistsProperty =
DependencyProperty.Register("CheckPathExists", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty DereferenceLinksProperty =
DependencyProperty.Register("DereferenceLinks", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty InitialDirectoryProperty =
DependencyProperty.Register("InitialDirectory", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty DefaultFileNameProperty =
DependencyProperty.Register("DefaultFileName", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty RestoreDirectoryProperty =
DependencyProperty.Register("RestoreDirectory", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false));
public static readonly DependencyProperty ShowHelpProperty =
DependencyProperty.Register("ShowHelp", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false));
public static readonly DependencyProperty SupportMultiDottedExtensionsProperty =
DependencyProperty.Register("SupportMultiDottedExtensions", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false));
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty ValidateNamesProperty =
DependencyProperty.Register("ValidateNames", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty RestorePreviouslySelectedDirectoryProperty =
DependencyProperty.Register("RestorePreviouslySelectedDirectory", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true));
public static readonly DependencyProperty HelpRequestCommandProperty =
DependencyProperty.Register("HelpRequestCommand", typeof(ICommand), typeof(FileDialogServiceBase), new PropertyMetadata(null));
public static readonly DependencyProperty FilterProperty =
DependencyProperty.Register("Filter", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty FilterIndexProperty =
DependencyProperty.Register("FilterIndex", typeof(int), typeof(FileDialogServiceBase), new PropertyMetadata(1));
public bool CheckFileExists {
get { return (bool)GetValue(CheckFileExistsProperty); }
set { SetValue(CheckFileExistsProperty, value); }
}
public bool AddExtension {
get { return (bool)GetValue(AddExtensionProperty); }
set { SetValue(AddExtensionProperty, value); }
}
public bool AutoUpgradeEnabled {
get { return (bool)GetValue(AutoUpgradeEnabledProperty); }
set { SetValue(AutoUpgradeEnabledProperty, value); }
}
public bool CheckPathExists {
get { return (bool)GetValue(CheckPathExistsProperty); }
set { SetValue(CheckPathExistsProperty, value); }
}
public bool DereferenceLinks {
get { return (bool)GetValue(DereferenceLinksProperty); }
set { SetValue(DereferenceLinksProperty, value); }
}
public string InitialDirectory {
get { return (string)GetValue(InitialDirectoryProperty); }
set { SetValue(InitialDirectoryProperty, value); }
}
public string DefaultFileName {
get { return (string)GetValue(DefaultFileNameProperty); }
set { SetValue(DefaultFileNameProperty, value); }
}
public bool RestoreDirectory {
get { return (bool)GetValue(RestoreDirectoryProperty); }
set { SetValue(RestoreDirectoryProperty, value); }
}
public bool ShowHelp {
get { return (bool)GetValue(ShowHelpProperty); }
set { SetValue(ShowHelpProperty, value); }
}
public bool SupportMultiDottedExtensions {
get { return (bool)GetValue(SupportMultiDottedExtensionsProperty); }
set { SetValue(SupportMultiDottedExtensionsProperty, value); }
}
public string Title {
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public bool ValidateNames {
get { return (bool)GetValue(ValidateNamesProperty); }
set { SetValue(ValidateNamesProperty, value); }
}
public bool RestorePreviouslySelectedDirectory {
get { return (bool)GetValue(RestorePreviouslySelectedDirectoryProperty); }
set { SetValue(RestorePreviouslySelectedDirectoryProperty, value); }
}
public string Filter {
get { return (string)GetValue(FilterProperty); }
set { SetValue(FilterProperty, value); }
}
public int FilterIndex {
get { return (int)GetValue(FilterIndexProperty); }
set { SetValue(FilterIndexProperty, value); }
}
public ICommand HelpRequestCommand {
get { return (ICommand)GetValue(HelpRequestCommandProperty); }
set { SetValue(HelpRequestCommandProperty, value); }
}
public event EventHandler HelpRequest;
public static readonly DependencyProperty FileOkCommandProperty =
DependencyProperty.Register("FileOkCommand", typeof(ICommand), typeof(FileDialogServiceBase), new PropertyMetadata(null));
public ICommand FileOkCommand {
get { return (ICommand)GetValue(FileOkCommandProperty); }
set { SetValue(FileOkCommandProperty, value); }
}
public event CancelEventHandler FileOk;
IFileDialog FileDialog;
IEnumerable<object> FilesCore;
Action<CancelEventArgs> fileOK;
public FileDialogServiceBase() {
FileDialog = CreateFileDialogAdapter();
FilesCore = new List<object>();
FileDialog.FileOk += OnDialogFileOk;
FileDialog.HelpRequest += OnDialogHelpRequest;
}
void OnDialogFileOk(object sender, CancelEventArgs e) {
UpdateFiles();
FileOk.Do(x => x(sender, e));
FileOkCommand.If(x => x.CanExecute(e)).Do(x => x.Execute(e));
fileOK.Do(x => x(e));
}
void OnDialogHelpRequest(object sender, EventArgs e) {
HelpRequest.Do(x => x(sender, e));
HelpRequestCommand.If(x => x.CanExecute(e)).Do(x => x.Execute(e));
}
protected abstract IFileDialog CreateFileDialogAdapter();
protected abstract void InitFileDialog();
protected abstract List<object> GetFileInfos();
void InitFileDialogCore() {
FileDialog.CheckFileExists = CheckFileExists;
FileDialog.AddExtension = AddExtension;
FileDialog.CheckPathExists = CheckPathExists;
FileDialog.DereferenceLinks = DereferenceLinks;
FileDialog.InitialDirectory = InitialDirectory;
FileDialog.FileName = DefaultFileName;
FileDialog.RestoreDirectory = RestoreDirectory;
FileDialog.ShowHelp = ShowHelp;
FileDialog.SupportMultiDottedExtensions = SupportMultiDottedExtensions;
FileDialog.Title = Title;
FileDialog.ValidateNames = ValidateNames;
if(RestorePreviouslySelectedDirectory && FilesCore.Count() > 0)
FileDialog.InitialDirectory = GetPreviouslySelectedDirectory();
else
FileDialog.InitialDirectory = InitialDirectory;
}
string GetPreviouslySelectedDirectory() {
if(FilesCore.First() is IFileInfo)
return ((IFileInfo)FilesCore.First()).DirectoryName;
if(FilesCore.First() is IFolderInfo)
return ((IFolderInfo)FilesCore.First()).DirectoryName;
return null;
}
void UpdateFiles() {
var fileInfos = GetFileInfos();
IList filesCore = (IList)FilesCore;
filesCore.Clear();
foreach(var fileInfo in fileInfos)
filesCore.Add(fileInfo);
}
bool ConvertDialogResultToBoolean(DialogResult result) {
if(result == DialogResult.OK)
return true;
if(result == DialogResult.Cancel)
return false;
throw new InvalidOperationException("The Dialog has returned a not supported value");
}
protected object GetFileDialog() {
return FileDialog;
}
protected IEnumerable<object> GetFiles() {
return FilesCore;
}
protected bool Show(Action<CancelEventArgs> fileOK) {
this.fileOK = fileOK;
InitFileDialogCore();
InitFileDialog();
((IList)FilesCore).Clear();
bool res = ShowCore();
return res;
}
bool ShowCore() {
DxDialogResult result = ActualWindow == null ? FileDialog.ShowDialog() : FileDialog.ShowDialog(new Win32WindowWrapper(ActualWindow));
if(result == DxDialogResult.OK)
return true;
if(result == DxDialogResult.Cancel)
return false;
throw new InvalidOperationException("The Dialog has returned a not supported value");
}
void IFileDialogServiceBase.Reset() {
FileDialog.Reset();
}
protected override void OnActualWindowChanged(Window oldWindow) { }
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public class FileInfoWrapper : IFileInfo {
public static FileInfoWrapper CreateDirectoryWrapper(string directoryPath) {
return new FileInfoWrapper(new DirectoryInfo(directoryPath));
}
public static FileInfoWrapper Create(string fileName) {
return new FileInfoWrapper(new FileInfo(fileName));
}
public FileSystemInfo FileSystemInfo { get; }
public FileInfo FileInfo { get { return FileSystemInfo as FileInfo; } }
DirectoryInfo DirectoryInfo { get { return FileSystemInfo as DirectoryInfo; } }
public FileInfoWrapper(FileInfo fileInfo) {
FileSystemInfo = fileInfo;
}
FileInfoWrapper(DirectoryInfo directoryInfo) {
FileSystemInfo = directoryInfo;
}
StreamWriter IFileInfo.AppendText() {
return Match(() => FileInfo.AppendText());
}
FileInfo IFileInfo.CopyTo(string destFileName, bool overwrite) {
return Match(() => FileInfo.CopyTo(destFileName, overwrite));
}
FileStream IFileInfo.Create() {
return Match(() => FileInfo.Create());
}
StreamWriter IFileInfo.CreateText() {
return Match(() => FileInfo.CreateText());
}
void IFileSystemInfo.Delete() {
FileSystemInfo.Delete();
}
string IFileSystemInfo.DirectoryName {
get { return Match(() => FileInfo.DirectoryName, () => DirectoryInfo.Parent.FullName); }
}
bool IFileSystemInfo.Exists {
get { return FileSystemInfo.Exists; }
}
long IFileInfo.Length {
get { return FileInfo.Return(x => x.Length, () => 0); }
}
void IFileSystemInfo.MoveTo(string destFileName) {
FileInfo.Do(x => x.MoveTo(destFileName));
}
string IFileSystemInfo.Name {
get { return FileSystemInfo.Name; }
}
FileStream IFileInfo.Open(FileMode mode, FileAccess access, FileShare share) {
return Match(() => FileInfo.Open(mode, access, share));
}
FileStream IFileInfo.OpenRead() {
return Match(() => FileInfo.OpenRead());
}
StreamReader IFileInfo.OpenText() {
return Match(() => FileInfo.OpenText());
}
FileStream IFileInfo.OpenWrite() {
return Match(() => FileInfo.OpenWrite());
}
FileAttributes IFileSystemInfo.Attributes {
get { return FileSystemInfo.Attributes; }
set { FileSystemInfo.Attributes = value; }
}
T Match<T>(Func<T> file, Func<T> directory = null) where T: class {
return FileInfo.Return(_ => file(), () => directory?.Invoke());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.