content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using UnityEngine;
using System.Collections;
public class FpsHudStats : MonoBehaviour
{
[SerializeField]
Transform healthIcon;
[SerializeField]
Transform shieldIcon;
void Start()
{
healthIcon = transform.Find("HealthIcon");
shieldIcon = transform.Find("ShieldIcon");
// Set colors
healthIcon.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.IconColor);
shieldIcon.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.IconColor);
}
} | 24.761905 | 89 | 0.694231 | [
"Unlicense",
"MIT"
] | Amitkapadi/unityassets | FpsHud3D/Assets/FpsHud/Scripts/FpsHudStats.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using HRM.BOL;
using HRM.DAL;
namespace HRM.BAL
{
public class TerminationBAL
{
public int Save(TerminationBOL objTerm)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.Save(objTerm);
}
public int Approve(TerminationBOL objTerm)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.Approve(objTerm);
}
public int Delete(int nTID)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.Delete(nTID);
}
public int Update_Interview_Closed(TerminationBOL objTerm)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.Update_Interview_Closed( objTerm);
}
public DataTable SelectAll(TerminationBOL objTerm)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.SelectAll(objTerm);
}
public TerminationBOL SelectByID(int TID)
{
TerminationDAL objDAL = new TerminationDAL();
return objDAL.SelectByID(TID);
}
}
}
| 26.55102 | 67 | 0.581091 | [
"MIT"
] | jencyraj/HumanResourceManagementProject | src/HRM.BAL/TerminationBAL.cs | 1,303 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace lindaniDS.Models
{
public class Mail
{
public int MailID { get; set; }
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
} | 21 | 43 | 0.610644 | [
"Unlicense"
] | LawrenceAmo/LindaniDS | Models/Mail.cs | 359 | C# |
/*
Copyright 2006 - 2010 Intel 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.Xml;
using System.Text;
using OpenSource.UPnP;
using System.Reflection;
using System.Collections;
using OpenSource.Utilities;
using System.Globalization;
using System.Runtime.Serialization;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// Class can represent any ContentDirectory approved
/// upnp or dublin-core metadata elements that are
/// simple DateTime values without any attributes.
/// </summary>
[Serializable()]
public sealed class PropertyDate : ICdsElement, IToXmlData, IDeserializationCallback
{
/// <summary>
/// Returns same value as StringValue
/// </summary>
/// <returns></returns>
public override string ToString() { return this.StringValue; }
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public static IList GetPossibleAttributes()
{
return new object[0];
}
/// <summary>
/// Returns an empty list.
/// </summary>
public IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// Returns an empty list.
/// </summary>
public IList ValidAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// No attributes, so always returns null
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public IComparable ExtractAttribute(string attribute) { return null; }
/// <summary>
/// Returns the underlying DateTime value.
/// </summary>
public IComparable ComparableValue { get { return m_value; } }
/// <summary>
/// Returns the underlying DateTime value.
/// </summary>
public object Value { get { return m_value; } }
/// <summary>
/// Returns the string representation of the date,
/// formatted to ContentDirectory conventions.
/// </summary>
public string StringValue
{
get
{
InitFormatInfo();
return this.m_value.ToString(FormatInfo.ShortDatePattern);
}
}
/// <summary>
/// Prints the XML representation of the metadata element.
/// <para>
/// Implementation calls the <see cref="ToXmlData.ToXml"/>
/// method for its implementation.
/// </para>
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public void ToXml (ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData.ToXml(this, formatter, (ToXmlData) data, xmlWriter);
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement(this.ns_tag);
}
/// <summary>
/// Instructs the "xmlWriter" argument to write the value of
/// the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteValue(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteString(this.StringValue);
}
/// <summary>
/// Instructs the "xmlWriter" argument to close the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void EndElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteEndElement();
}
/// <summary>
/// Empty - this element has no child xml elements.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteInnerXml(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
}
/// <summary>
/// Attempts to case compareToThis as an DateTime
/// to do the comparison. If the cast
/// fails, then it compares the current
/// value against DateTime.MinValue.
/// </summary>
/// <param name="compareToThis"></param>
/// <returns></returns>
public int CompareTo (object compareToThis)
{
System.Type type = compareToThis.GetType();
DateTime compareTo = DateTime.MinValue;
try
{
if (type == typeof(PropertyDate))
{
compareTo = ((PropertyDate)compareToThis).m_value;
}
else if (type == typeof(string))
{
compareTo = PropertyDate.ParseIso8601((string)compareToThis);
}
else
{
compareTo = (DateTime) compareToThis;
}
}
catch
{
compareTo = DateTime.MinValue;
}
return this.m_value.CompareTo(compareTo);
}
/// <summary>
/// Extracts the Name of the element and uses
/// the InnerText as the value.
/// </summary>
/// <param name="element"></param>
public PropertyDate(XmlElement element)
{
this.m_value = EnsureNoTime (ParseIso8601(element.InnerText));
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(element.Name);
}
/// <summary>
/// Instantiates a new property that can represent an xml element with
/// a DateTime as its value.
/// </summary>
/// <param name="namespace_tag">property obtained from Tags[CommonPropertyNames.value]</param>
/// <param name="val"></param>
public PropertyDate (string namespace_tag, DateTime val)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(namespace_tag);
this.m_value = EnsureNoTime (val);
}
/// <summary>
/// Assume the name has been read.
/// </summary>
/// <param name="reader"></param>
public PropertyDate(XmlReader reader)
{
this.m_value = EnsureNoTime( ParseIso8601(reader.Value) );
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(reader.Name);
}
/// <summary>
/// Sets the formatting info to match ContentDirectory speicification.
/// </summary>
private static void InitFormatInfo()
{
if (FormatInfo == null)
{
FormatInfo = new System.Globalization.DateTimeFormatInfo();
FormatInfo.ShortDatePattern = "yyyy-MM-dd";
}
}
/// <summary>
/// Parses the date string as an ISO8601 form.
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private static DateTime ParseIso8601(string date)
{
InitFormatInfo();
string[] formats = { FormatInfo.ShortDatePattern };
DateTime newDate = DateTime.ParseExact(date, formats, FormatInfo, DateTimeStyles.None);
return newDate;
}
/// <summary>
/// Ensures that no time component exists for the date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime EnsureNoTime(DateTime dt)
{
DateTime dateOnly = new DateTime(0);
dateOnly = dateOnly.AddYears(dt.Year-1);
dateOnly = dateOnly.AddMonths(dt.Month-1);
dateOnly = dateOnly.AddDays(dt.Day-1);
//return dt.Subtract(new TimeSpan(0, dt.Hour, dt.Minute, dt.Second, dt.Millisecond));
return dateOnly;
}
/// <summary>
/// Share the same formatting info for all instances.
/// </summary>
private static DateTimeFormatInfo FormatInfo = null;
/// <summary>
/// Returns the cloned formatting info if its desired.
/// </summary>
/// <returns></returns>
public static DateTimeFormatInfo GetFormatInfo()
{
InitFormatInfo();
return (DateTimeFormatInfo) FormatInfo.Clone();
}
/// <summary>
/// Underlying DateTime value.
/// </summary>
public DateTime _Value { get { return this.m_value; } }
internal DateTime m_value;
/// <summary>
/// the namespace and element name to represent
/// </summary>
private string ns_tag;
public void OnDeserialization(object sender)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(this.ns_tag);
}
}
}
| 28.361186 | 96 | 0.668884 | [
"Apache-2.0"
] | Erikhht/DeveloperToolsForUPnP-Tools | DeveloperToolsForUPnP/Global/UPNPAVCDSML/PropertyDate.cs | 10,522 | C# |
// 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.Immutable;
using System.Diagnostics;
using AnalyzerOptions = System.Collections.Immutable.ImmutableDictionary<string, string>;
using TreeOptions = System.Collections.Immutable.ImmutableDictionary<
string,
Microsoft.CodeAnalysis.ReportDiagnostic
>;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Holds results from <see cref="AnalyzerConfigSet.GetOptionsForSourcePath(string)"/>.
/// </summary>
public readonly struct AnalyzerConfigOptionsResult
{
/// <summary>
/// Options that customize diagnostic severity as reported by the compiler.
/// </summary>
public TreeOptions TreeOptions { get; }
/// <summary>
/// Options that do not have any special compiler behavior and are passed to analyzers as-is.
/// </summary>
public AnalyzerOptions AnalyzerOptions { get; }
/// <summary>
/// Any produced diagnostics while applying analyzer configuration.
/// </summary>
public ImmutableArray<Diagnostic> Diagnostics { get; }
internal AnalyzerConfigOptionsResult(
TreeOptions treeOptions,
AnalyzerOptions analyzerOptions,
ImmutableArray<Diagnostic> diagnostics
)
{
Debug.Assert(treeOptions != null);
Debug.Assert(analyzerOptions != null);
TreeOptions = treeOptions;
AnalyzerOptions = analyzerOptions;
Diagnostics = diagnostics;
}
}
}
| 34.4 | 101 | 0.667442 | [
"MIT"
] | belav/roslyn | src/Compilers/Core/Portable/CommandLine/AnalyzerConfigOptionsResult.cs | 1,722 | C# |
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Maps;
namespace CustomRenderer
{
public class CustomMap : Map
{
public static readonly BindableProperty CustomPinsProperty =
BindableProperty.Create(nameof(CustomPins),
typeof(IList<CustomPin>),
typeof(CustomMap),
null,
BindingMode.TwoWay, null, OnCustomPinsPropertyChanged);
private static void OnCustomPinsPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var control = (CustomMap)bindable;
if (control != null)
{
if (newvalue is IList<CustomPin> customPins)
{
customPins.ForEach(p => control.Pins.Add(p));
}
}
}
public IList<CustomPin> CustomPins
{
get => (IList<CustomPin>)GetValue(CustomPinsProperty);
set => SetValue(CustomPinsProperty, value);
}
}
}
| 29.944444 | 114 | 0.58256 | [
"Apache-2.0"
] | fperez2511/xamarin-forms-samples | CustomRenderers/Map/Pin/CustomRenderer/CustomMap.cs | 1,080 | C# |
/*
* Copyright 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.
*/
/*
* Do not modify this file. This file is generated from the wafv2-2019-07-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetWebACLForResource Request Marshaller
/// </summary>
public class GetWebACLForResourceRequestMarshaller : IMarshaller<IRequest, GetWebACLForResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetWebACLForResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetWebACLForResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.WAFV2");
string target = "AWSWAF_20190729.GetWebACLForResource";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-07-29";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetResourceArn())
{
context.Writer.WritePropertyName("ResourceArn");
context.Writer.Write(publicRequest.ResourceArn);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static GetWebACLForResourceRequestMarshaller _instance = new GetWebACLForResourceRequestMarshaller();
internal static GetWebACLForResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetWebACLForResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.543689 | 155 | 0.637804 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/WAFV2/Generated/Model/Internal/MarshallTransformations/GetWebACLForResourceRequestMarshaller.cs | 3,661 | C# |
using Lunr;
using Xunit;
namespace LunrCoreTests
{
public class TrimmerTests
{
[Theory]
[InlineData("hello", "hello")] // word
[InlineData("hello.", "hello")] // full stop
[InlineData("it's", "it's")] // inner apostrophe
[InlineData("james'", "james")] // trailing apostrophe
[InlineData("stop!'", "stop")] // exclamation mark
[InlineData("first,'", "first")] // comma
[InlineData("[tag]'", "tag")] // brackets
public void CheckTrim(string str, string expected)
{
Assert.Equal(expected, new Trimmer().Trim(str));
}
}
}
| 28.772727 | 62 | 0.554502 | [
"MIT"
] | SVemulapalli/lunr-core | LunrCoreTests/TrimmerTests.cs | 635 | C# |
using BlazorDesk.AppModels;
using BlazorDesk.AppModels.View;
using BlazorDesk.Data.Models.Requests;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace BlazorDesk.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CategoriesController : ControllerBase
{
ICollection<RequestCategory> fakeCategories = new List<RequestCategory>
{
new RequestCategory
{
Id= 1,
Name = "First Category"
},
new RequestCategory
{
Id=2,
Name = "Second Category"
}
};
[HttpGet("{id}")]
public CategoryViewModel Get(int id)
{
return this.GetViewModel(fakeCategories).FirstOrDefault();
}
[HttpGet]
public IEnumerable<CategoryViewModel> Get()
{
return this.GetViewModel(fakeCategories);
}
private IEnumerable<CategoryViewModel> GetViewModel(IEnumerable<RequestCategory> collection)
{
return collection.Select(c =>
new CategoryViewModel
{
Id = c.Id,
Name = c.Name
});
}
}
} | 26.2 | 100 | 0.547328 | [
"MIT"
] | LyuboslavKrastev/BlazorDesk | BlazorDesk/Server/Controllers/CategoriesController.cs | 1,312 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Ikngtty.MyLibrary.Collections;
using Ikngtty.MyLibrary.Utility;
namespace Ikngtty.MyLibraryTest.Utility
{
[TestFixture]
public class CollectionUtilityTest
{
[Test]
public void ToHashSetTest()
{
{
string[] source = new string[0];
HashSet<string> result = source.ToHashSet();
Assert.AreEqual(0, result.Count);
}
{
string[] source = new string[] { "a", "a", "b", "a", "b" };
HashSet<string> result = source.ToHashSet();
Assert.AreEqual(2, result.Count);
Assert.True(result.Contains("a"));
Assert.True(result.Contains("b"));
}
}
[Test]
public void GroupByAdjacentlyTest()
{
{
string[] source = new string[0];
List<Grouping<string, string>> result = source.GroupByAdjacently(item => item);
Assert.AreEqual(0, result.Count);
}
{
string[] source = new string[] { "abc" };
List<Grouping<int, string>> result = source.GroupByAdjacently(item => item.Length);
Assert.AreEqual(1, result.Count);
{
Grouping<int, string> resultItem = result[0];
Assert.AreEqual(3, resultItem.Key);
Assert.AreEqual(1, resultItem.Elements.Count);
Assert.AreEqual("abc", resultItem[0]);
}
}
{
string[] source = new string[] { "a", "b", "b", "c", "c", "c", "b", "b", null, null, "a" };
List<Grouping<string, string>> result = source.GroupByAdjacently(item => item);
Assert.AreEqual(6, result.Count);
{
Grouping<string, string> resultItem = result[0];
Assert.AreEqual("a", resultItem.Key);
Assert.AreEqual(1, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == "a"));
}
{
Grouping<string, string> resultItem = result[1];
Assert.AreEqual("b", resultItem.Key);
Assert.AreEqual(2, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == "b"));
}
{
Grouping<string, string> resultItem = result[2];
Assert.AreEqual("c", resultItem.Key);
Assert.AreEqual(3, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == "c"));
}
{
Grouping<string, string> resultItem = result[3];
Assert.AreEqual("b", resultItem.Key);
Assert.AreEqual(2, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == "b"));
}
{
Grouping<string, string> resultItem = result[4];
Assert.AreEqual(null, resultItem.Key);
Assert.AreEqual(2, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == null));
}
{
Grouping<string, string> resultItem = result[5];
Assert.AreEqual("a", resultItem.Key);
Assert.AreEqual(1, resultItem.Elements.Count);
Assert.True(resultItem.Elements.All(e => e == "a"));
}
}
}
}
}
| 29.936842 | 95 | 0.631857 | [
"MIT"
] | ikngtty/MyLibrary | src/MyLibraryTest/Utility/CollectionUtilityTest.cs | 2,846 | C# |
using System;
using System.Collections;
// ReSharper disable once CheckNamespace
namespace Cosmos.Collections
{
public static partial class CollectionExtensions
{
/// <summary>
/// Binary Search
/// </summary>
/// <param name="array"></param>
/// <param name="value"></param>
/// <returns></returns>
public static int BinarySearch(this Array array, object value)
=> Array.BinarySearch(array, value);
/// <summary>
/// Binary Search
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
/// <param name="length"></param>
/// <param name="value"></param>
/// <returns></returns>
public static int BinarySearch(this Array array, int index, int length, object value)
=> Array.BinarySearch(array, index, length, value);
/// <summary>
/// Binary Search
/// </summary>
/// <param name="array"></param>
/// <param name="value"></param>
/// <param name="comparer"></param>
/// <returns></returns>
public static int BinarySearch(this Array array, object value, IComparer comparer)
=> Array.BinarySearch(array, value, comparer);
/// <summary>
/// Binary Search
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
/// <param name="length"></param>
/// <param name="value"></param>
/// <param name="comparer"></param>
/// <returns></returns>
public static int BinarySearch(this Array array, int index, int length, object value, IComparer comparer)
=> Array.BinarySearch(array, index, length, value, comparer);
}
} | 35.137255 | 113 | 0.554129 | [
"MIT"
] | alexinea/Cosmos.Standard | src/Cosmos.Extensions.Collections/Cosmos/Collections/Extensions/Array/Find/Extensions.Collections.A3y.Find.BinarySearch.cs | 1,792 | C# |
// semmle-extractor-options: /r:System.Collections.Specialized.dll /r:System.Collections.dll /r:System.Linq.dll
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
#nullable enable
public class Collections
{
void M1(string[] args)
{
var b = args.Length == 0;
b = args.Length == 1;
b = args.Length != 0;
b = args.Length != 1;
b = args.Length > 0;
b = args.Length >= 0;
b = args.Length >= 1;
}
void M2(ICollection<string> args)
{
var b = args.Count == 0;
b = args.Count == 1;
b = args.Count != 0;
b = args.Count != 1;
b = args.Count > 0;
b = args.Count >= 0;
b = args.Count >= 1;
}
void M3(string[] args)
{
var b = args.Count() == 0;
b = args.Count() == 1;
b = args.Count() != 0;
b = args.Count() != 1;
b = args.Count() > 0;
b = args.Count() >= 0;
b = args.Count() >= 1;
}
void M4(string[] args)
{
var b = args.Any();
}
void M5(List<string> args)
{
if (args.Count == 0)
return;
var x = args.ToArray();
args.Clear();
x = args.ToArray();
x = new string[] { "a", "b", "c" };
x = x;
x = new string[0];
x = x;
}
void M6()
{
var x = new string[] { "a", "b", "c" }.ToList();
x.Clear();
if (x.Count == 0)
{
x.Add("a");
x.Add("b");
}
}
void M7(string[] args)
{
bool IsEmpty(string s) => s == "";
var b = args.Any(IsEmpty);
b = args.Count(IsEmpty) == 0;
b = args.Count(IsEmpty) == 1;
b = args.Count(IsEmpty) != 0;
b = args.Count(IsEmpty) != 1;
b = args.Count(IsEmpty) > 0;
b = args.Count(IsEmpty) >= 0;
b = args.Count(IsEmpty) >= 1;
}
void M8()
{
var x = new string[] { };
string[] y = { };
x = new string[] { "a" };
string[] z = { "a" };
}
void M9(string[] args)
{
foreach (var arg in args)
Console.WriteLine(args); // guarded by `args` being non-empty
}
void M10(string[] args)
{
foreach (var arg in args)
;
Console.WriteLine(args);
}
}
| 22.46729 | 111 | 0.450915 | [
"MIT"
] | AlexDenisov/codeql | csharp/ql/test/library-tests/controlflow/guards/Collections.cs | 2,404 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
using System.IO;
using Amazon.DynamoDBv2.DataModel;
using Xunit;
namespace Amazon.DNXCore.IntegrationTests.DynamoDB
{
public partial class DynamoDBTests : IClassFixture<DynamoDBTestsFixture>
{
[Fact]
[Trait(CategoryAttribute, "DynamoDB")]
public async Task TestContext()
{
// It is a known bug that this test currently fails due to an AOT-compilation
// issue, on iOS using mono2x.
foreach (var conversion in new DynamoDBEntryConversion [] { DynamoDBEntryConversion.V1, DynamoDBEntryConversion.V2 })
{
SharedTestFixture.TableCache.Clear();
// Cleanup existing data
await SharedTestFixture.CleanupTables();
// Recreate context
SharedTestFixture.CreateContext(conversion);
await TestEnumHashKeyObjects();
await TestEmptyCollections(conversion);
TestContextConversions();
await TestUnsupportedTypes();
TestEnums(conversion);
await TestHashObjects();
await TestHashRangeObjects();
await TestOtherContextOperations();
await TestBatchOperations();
}
}
private async Task TestUnsupportedTypes()
{
InvalidOperationException exception;
// Verify that saving objects with invalid properties result in exceptions
var employee2 = new Employee2
{
Name = "Alan",
Age = 31,
TimeWithCompany = TimeSpan.FromDays(300)
};
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(employee2));
Assert.Equal(exception.Message, "Type System.TimeSpan is unsupported, it cannot be instantiated");
var employee3 = new Employee3
{
Name = "Alan",
Age = 31,
EmptyProperty = new EmptyType()
};
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(employee3));
Assert.Equal(exception.Message, "Type Amazon.DNXCore.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members");
// Verify that objects that are invalid result in exceptions
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => SharedTestFixture.Context.ScanAsync<TimeSpan>(new List<ScanCondition>(), null).GetNextSetAsync());
Assert.Equal(exception.Message, "Type System.TimeSpan is unsupported, it cannot be instantiated");
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => SharedTestFixture.Context.ScanAsync<EmptyType>(new List<ScanCondition>(), null).GetNextSetAsync());
Assert.Equal(exception.Message, "Type Amazon.DNXCore.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members");
}
private void TestContextConversions()
{
var conversionV1 = DynamoDBEntryConversion.V1;
var conversionV2 = DynamoDBEntryConversion.V2;
Product product = new Product
{
Id = 1,
Name = "CloudSpotter",
CompanyName = "CloudsAreGrate",
Price = 1200,
TagSet = new HashSet<string> { "Prod", "1.0" },
CurrentStatus = Status.Active,
FormerStatus = Status.Upcoming,
Supports = Support.Unix | Support.Windows,
PreviousSupport = null,
InternalId = "T1000",
IsPublic = true,
AlwaysN = true,
Rating = 4,
Components = new List<string> { "Code", "Coffee" },
KeySizes = new List<byte> { 16, 64, 128 },
CompanyInfo = new CompanyInfo
{
Name = "MyCloud",
Founded = new DateTime(1994, 7, 6),
Revenue = 9001
}
};
{
var docV1 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV1 });
var docV2 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV2 });
VerifyConversions(docV1, docV2);
}
{
using (var contextV1 = new DynamoDBContext(Client, new DynamoDBContextConfig { Conversion = conversionV1 }))
using (var contextV2 = new DynamoDBContext(Client, new DynamoDBContextConfig { Conversion = conversionV2 }))
{
var docV1 = contextV1.ToDocument(product);
var docV2 = contextV2.ToDocument(product);
VerifyConversions(docV1, docV2);
}
}
{
using (var contextV1 = new DynamoDBContext(Client, new DynamoDBContextConfig { Conversion = conversionV1 }))
{
contextV1.SaveAsync(product);
contextV1.SaveAsync(product, new DynamoDBOperationConfig { Conversion = conversionV2 });
}
}
// Introduce a circular reference and try to serialize
{
product.CompanyInfo = new CompanyInfo
{
Name = "MyCloud",
Founded = new DateTime(1994, 7, 6),
Revenue = 9001,
MostPopularProduct = product
};
Assert.Throws<InvalidOperationException>(() => SharedTestFixture.Context.ToDocument(product));
Assert.Throws<InvalidOperationException>(() => SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV1 }));
Assert.Throws<InvalidOperationException>(() => SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV2 }));
// Remove circular dependence
product.CompanyInfo.MostPopularProduct = new Product
{
Id = 3,
Name = "CloudDebugger",
CompanyName = "CloudsAreGrate",
Price = 9000,
TagSet = new HashSet<string> { "Test" },
};
var docV1 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV1 });
var docV2 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV2 });
VerifyConversions(docV1, docV2);
}
// Introduce circular reference in a Document and try to deserialize
{
// Normal serialization
var docV1 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV1 });
var docV2 = SharedTestFixture.Context.ToDocument(product, new DynamoDBOperationConfig { Conversion = conversionV2 });
VerifyConversions(docV1, docV2);
// Add circular references
docV1["CompanyInfo"].AsDocument()["MostPopularProduct"] = docV1;
docV2["CompanyInfo"].AsDocument()["MostPopularProduct"] = docV2;
Assert.Throws<InvalidOperationException>(() => SharedTestFixture.Context.FromDocument<Product>(docV1, new DynamoDBOperationConfig { Conversion = conversionV1 }));
Assert.Throws<InvalidOperationException>(() => SharedTestFixture.Context.FromDocument<Product>(docV2, new DynamoDBOperationConfig { Conversion = conversionV2 }));
// Remove circular references
docV1["CompanyInfo"].AsDocument()["MostPopularProduct"] = null;
docV2["CompanyInfo"].AsDocument()["MostPopularProduct"] = docV1;
var prod1 = SharedTestFixture.Context.FromDocument<Product>(docV1, new DynamoDBOperationConfig { Conversion = conversionV1 });
var prod2 = SharedTestFixture.Context.FromDocument<Product>(docV2, new DynamoDBOperationConfig { Conversion = conversionV2 });
}
}
private void TestEnums(DynamoDBEntryConversion conversion)
{
Product product = new Product
{
Id = 1,
Name = "CloudSpotter",
CompanyName = "CloudsAreGrate",
Price = 1200,
TagSet = new HashSet<string> { "Prod", "1.0" },
CurrentStatus = Status.Active,
FormerStatus = Status.Upcoming,
Supports = Support.Unix | Support.Windows,
PreviousSupport = null,
};
// try round-tripping the enums
var doc1 = SharedTestFixture.Context.ToDocument(product);
var product2 = SharedTestFixture.Context.FromDocument<Product>(doc1);
Assert.Equal(product.CurrentStatus, product2.CurrentStatus);
Assert.Equal(product.FormerStatus, product2.FormerStatus);
Assert.Equal(product.Supports, product2.Supports);
// try changing underlying enum data to strings
var doc2 = SharedTestFixture.Context.ToDocument(product);
doc2["CurrentStatus"] = product.CurrentStatus.ToString();
doc2["FormerStatus"] = product.FormerStatus.ToString();
doc2["Supports"] = product.Supports.ToString();
doc2 = doc2.ForceConversion(conversion);
var product3 = SharedTestFixture.Context.FromDocument<Product>(doc2);
Assert.Equal(product.CurrentStatus, product3.CurrentStatus);
Assert.Equal(product.FormerStatus, product3.FormerStatus);
Assert.Equal(product.Supports, product3.Supports);
}
private static void VerifyConversions(Document docV1, Document docV2)
{
Assert.Equal(1, docV1["Id"].AsInt());
Assert.Equal("CloudSpotter", docV1["Product"].AsString());
Assert.NotNull(docV1["Components"].AsPrimitiveList());
Assert.NotNull(docV1["IsPublic"].AsPrimitive());
Assert.NotNull(docV1["Tags"].AsPrimitiveList());
Assert.NotNull(docV1["CompanyInfo"] as Document);
Assert.NotNull(docV1["KeySizes"].AsPrimitiveList());
Assert.Equal(1, docV2["Id"].AsInt());
Assert.Equal("CloudSpotter", docV2["Product"].AsString());
Assert.Null(docV2["Components"].AsPrimitiveList());
Assert.NotNull(docV2["Components"].AsDynamoDBList());
Assert.Null(docV2["IsPublic"].AsPrimitive());
Assert.NotNull(docV2["IsPublic"].AsDynamoDBBool());
Assert.NotNull(docV2["Tags"].AsPrimitiveList());
Assert.NotNull(docV2["CompanyInfo"] as Document);
Assert.NotNull(docV2["KeySizes"].AsPrimitiveList());
}
private async Task TestEmptyCollections(DynamoDBEntryConversion conversion)
{
// Check if the conversion being used is V1
// In V1 conversion, lists are stored as sets, which cannot
// be empty, so for V1 we are not testing empty lists
var isV1 = (conversion == DynamoDBEntryConversion.V1);
// Create and save item
Product product = new Product
{
Id = 1,
Map = new Dictionary<string, string>()
};
if (!isV1)
product.Components = new List<string>();
await SharedTestFixture.Context.SaveAsync(product);
// Load and test the item
var retrieved = await SharedTestFixture.Context.LoadAsync(product);
if (!isV1)
{
Assert.NotNull(retrieved.Components);
Assert.Equal(0, retrieved.Components.Count);
}
Assert.NotNull(retrieved.Map);
Assert.Equal(0, retrieved.Map.Count);
}
private async Task TestEnumHashKeyObjects()
{
// Create and save item
EnumProduct1 product1 = new EnumProduct1
{
Id = Status.Upcoming,
Name = "CloudSpotter"
};
await SharedTestFixture.Context.SaveAsync(product1);
EnumProduct2 product2 = new EnumProduct2
{
Id = Status.Removed,
Name = "CloudSpotter"
};
await SharedTestFixture.Context.SaveAsync(product2);
var rt1 = await SharedTestFixture.Context.LoadAsync(product1);
Assert.Equal(product1.Id, rt1.Id);
Assert.Equal(product1.IdAsInt, rt1.IdAsInt);
var rt2 = await SharedTestFixture.Context.LoadAsync(product2);
Assert.Equal(product2.Id, rt2.Id);
await SharedTestFixture.Context.DeleteAsync(product1);
await SharedTestFixture.Context.DeleteAsync(product2);
}
private async Task TestHashObjects()
{
string bucketName = "aws-sdk-net-s3link-" + DateTime.Now.Ticks;
var s3Client = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast1);
await s3Client.PutBucketAsync(bucketName);
try
{
// Create and save item
Product product = new Product
{
Id = 1,
Name = "CloudSpotter",
CompanyName = "CloudsAreGrate",
Price = 1200,
TagSet = new HashSet<string> { "Prod", "1.0" },
CurrentStatus = Status.Active,
FormerStatus = Status.Upcoming,
Supports = Support.Windows | Support.Abacus,
PreviousSupport = null,
InternalId = "T1000",
IsPublic = true,
AlwaysN = true,
Rating = 4,
Components = new List<string> { "Code", "Coffee" },
KeySizes = new List<byte> { 16, 64, 128 },
CompanyInfo = new CompanyInfo
{
Name = "MyCloud",
Founded = new DateTime(1994, 7, 6),
Revenue = 9001,
AllProducts = new List<Product>
{
new Product { Id = 12, Name = "CloudDebugger" },
new Product { Id = 13, Name = "CloudDebuggerTester" }
},
CompetitorProducts = new Dictionary<string, List<Product>>
{
{
"CloudsAreOK",
new List<Product>
{
new Product { Id = 90, Name = "CloudSpotter RipOff" },
new Product { Id = 100, Name = "CloudDebugger RipOff" },
}
},
{
"CloudsAreBetter",
new List<Product>
{
new Product { Id = 92, Name = "CloudSpotter RipOff 2" },
new Product { Id = 102, Name = "CloudDebugger RipOff 3" },
}
},
}
},
Map = new Dictionary<string, string>
{
{ "a", "1" },
{ "b", "2" }
}
};
product.FullProductDescription = S3Link.Create(SharedTestFixture.Context, bucketName, "my-product", Amazon.RegionEndpoint.USEast1);
// await product.FullProductDescription.UploadStreamAsync(new MemoryStream(UTF8Encoding.UTF8.GetBytes("Lots of data")));
await SharedTestFixture.Context.SaveAsync(product);
// Test conversion
var doc = SharedTestFixture.Context.ToDocument(product);
Assert.NotNull(doc["Tags"].AsPrimitiveList());
//if (DynamoDBEntryConversion.Schema == DynamoDBEntryConversion.ConversionSchema.V1)
// Assert.NotNull(doc["Components"].AsPrimitiveList());
//else
// Assert.NotNull(doc["Components"].AsDynamoDBList());
Assert.True(
doc["Components"].AsPrimitiveList() != null ||
doc["Components"].AsDynamoDBList() != null);
Assert.NotNull(doc["CompanyInfo"].AsDocument());
Assert.NotNull(doc["Supports"]);
// Load item
Product retrieved = await SharedTestFixture.Context.LoadAsync<Product>(1);
Assert.Equal(product.Id, retrieved.Id);
Assert.Equal(product.TagSet.Count, retrieved.TagSet.Count);
Assert.Equal(product.Components.Count, retrieved.Components.Count);
Assert.Null(retrieved.InternalId);
Assert.Equal(product.CurrentStatus, retrieved.CurrentStatus);
Assert.Equal(product.FormerStatus, retrieved.FormerStatus);
Assert.Equal(product.Supports, retrieved.Supports);
Assert.Equal(product.PreviousSupport, retrieved.PreviousSupport);
Assert.Equal(product.IsPublic, retrieved.IsPublic);
Assert.Equal(product.Rating, retrieved.Rating);
Assert.Equal(product.KeySizes.Count, retrieved.KeySizes.Count);
Assert.NotNull(retrieved.CompanyInfo);
Assert.Equal(product.CompanyInfo.Name, retrieved.CompanyInfo.Name);
Assert.Equal(product.CompanyInfo.Founded, retrieved.CompanyInfo.Founded);
Assert.NotEqual(product.CompanyInfo.Revenue, retrieved.CompanyInfo.Revenue);
Assert.Equal(product.CompanyInfo.AllProducts.Count, retrieved.CompanyInfo.AllProducts.Count);
Assert.Equal(product.CompanyInfo.AllProducts[0].Id, retrieved.CompanyInfo.AllProducts[0].Id);
Assert.Equal(product.CompanyInfo.AllProducts[1].Id, retrieved.CompanyInfo.AllProducts[1].Id);
Assert.Equal(product.Map.Count, retrieved.Map.Count);
Assert.Equal(product.CompanyInfo.CompetitorProducts.Count, retrieved.CompanyInfo.CompetitorProducts.Count);
Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(0).Key, retrieved.CompanyInfo.CompetitorProducts.ElementAt(0).Key);
Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(0).Value.Count, retrieved.CompanyInfo.CompetitorProducts.ElementAt(0).Value.Count);
Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(1).Key, retrieved.CompanyInfo.CompetitorProducts.ElementAt(1).Key);
Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(1).Value.Count, retrieved.CompanyInfo.CompetitorProducts.ElementAt(1).Value.Count);
Assert.NotNull(retrieved.FullProductDescription);
/*using(var stream = retrieved.FullProductDescription.OpenStream())
using(var reader = new StreamReader(stream))
{
Assert.Equal("Lots of data", reader.ReadToEnd());
}*/
// Try saving circularly-referencing object
product.CompanyInfo.AllProducts.Add(product);
await Assert.ThrowsAsync<InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(product));
product.CompanyInfo.AllProducts.RemoveAt(2);
// Create and save new item
product.Id++;
product.Price = 94;
product.TagSet = null;
product.Components = null;
product.CurrentStatus = Status.Upcoming;
product.IsPublic = false;
product.AlwaysN = false;
product.Rating = null;
product.KeySizes = null;
await SharedTestFixture.Context.SaveAsync(product);
// Load new item
retrieved = await SharedTestFixture.Context.LoadAsync<Product>(product);
Assert.Equal(product.Id, retrieved.Id);
Assert.Null(retrieved.TagSet);
Assert.Null(retrieved.Components);
Assert.Null(retrieved.InternalId);
Assert.Equal(product.CurrentStatus, retrieved.CurrentStatus);
Assert.Equal(product.IsPublic, retrieved.IsPublic);
Assert.Equal(product.AlwaysN, retrieved.AlwaysN);
Assert.Equal(product.Rating, retrieved.Rating);
Assert.Null(retrieved.KeySizes);
// Enumerate all products and save their Ids
List<int> productIds = new List<int>();
IEnumerable<Product> products = await SharedTestFixture.Context.ScanAsync<Product>(new List<ScanCondition>()).GetNextSetAsync();
foreach(var p in products)
{
productIds.Add(p.Id);
}
Assert.Equal(2, productIds.Count);
// Load first product
var firstId = productIds[0];
product = await SharedTestFixture.Context.LoadAsync<Product>(firstId);
Assert.NotNull(product);
Assert.Equal(firstId, product.Id);
// Query GlobalIndex
products = await SharedTestFixture.Context.QueryAsync<Product>(
product.CompanyName, // Hash-key for the index is Company
QueryOperator.GreaterThan, // Range-key for the index is Price, so the
new object[] { 90 }, // condition is against a numerical value
new DynamoDBOperationConfig // Configure the index to use
{
IndexName = "GlobalIndex",
}).GetNextSetAsync();
Assert.Equal(2, products.Count());
// Query GlobalIndex with an additional non-key condition
products = await SharedTestFixture.Context.QueryAsync<Product>(
product.CompanyName, // Hash-key for the index is Company
QueryOperator.GreaterThan, // Range-key for the index is Price, so the
new object[] { 90 }, // condition is against a numerical value
new DynamoDBOperationConfig // Configure the index to use
{
IndexName = "GlobalIndex",
QueryFilter = new List<ScanCondition>
{
new ScanCondition("TagSet", ScanOperator.Contains, "1.0")
}
}).GetNextSetAsync();
Assert.Equal(1, products.Count());
// Delete first product
await SharedTestFixture.Context.DeleteAsync<Product>(firstId);
product = await SharedTestFixture.Context.LoadAsync<Product>(product.Id);
Assert.Null(product);
// Scan the table
products = await SharedTestFixture.Context.ScanAsync<Product>(new List<ScanCondition>()).GetNextSetAsync();
Assert.Equal(1, products.Count());
// Scan the table with consistent read
products = await SharedTestFixture.Context.ScanAsync<Product>(
new ScanCondition[] { },
new DynamoDBOperationConfig { ConsistentRead = true }).GetNextSetAsync();
Assert.Equal(1, products.Count());
// Test a versioned product
VersionedProduct vp = new VersionedProduct
{
Id = 3,
Name = "CloudDebugger",
CompanyName = "CloudsAreGrate",
Price = 9000,
TagSet = new HashSet<string> { "Test" },
};
await SharedTestFixture.Context.SaveAsync(vp);
// Update and save
vp.Price++;
await SharedTestFixture.Context.SaveAsync(vp);
// Alter the version and try to save
vp.Version = 0;
await Assert.ThrowsAsync<ConditionalCheckFailedException>(() => SharedTestFixture.Context.SaveAsync(vp));
// Load and save
vp = await SharedTestFixture.Context.LoadAsync(vp);
await SharedTestFixture.Context.SaveAsync(vp);
}
finally
{
await UtilityMethods.DeleteBucketWithObjectsAsync(s3Client, bucketName);
}
}
private async Task TestHashRangeObjects()
{
// Create and save item
Employee employee = new Employee
{
Name = "Alan",
Age = 31,
CompanyName = "Big River",
CurrentStatus = Status.Active,
Score = 120,
ManagerName = "Barbara",
InternalId = "Alan@BigRiver",
Aliases = new List<string> { "Al", "Steve" },
Data = Encoding.UTF8.GetBytes("Some binary data"),
};
await SharedTestFixture.Context.SaveAsync(employee);
// Load item
Employee retrieved = await SharedTestFixture.Context.LoadAsync(employee);
Assert.Equal(employee.Name, retrieved.Name);
Assert.Equal(employee.Age, retrieved.Age);
Assert.Equal(employee.CompanyName, retrieved.CompanyName);
Assert.Equal(employee.CurrentStatus, retrieved.CurrentStatus);
// Create and save new item
employee.Name = "Chuck";
employee.Age = 30;
employee.CurrentStatus = Status.Inactive;
employee.Aliases = new List<string> { "Charles" };
employee.Data = Encoding.UTF8.GetBytes("Binary data");
employee.Score = 94;
await SharedTestFixture.Context.SaveAsync(employee);
// Load item
retrieved = await SharedTestFixture.Context.LoadAsync(employee);
Assert.Equal(employee.Name, retrieved.Name);
Assert.Equal(employee.Age, retrieved.Age);
Assert.Equal(employee.CompanyName, retrieved.CompanyName);
Assert.Equal(employee.CurrentStatus, retrieved.CurrentStatus);
Assert.Equal(employee.Data.Length, retrieved.Data.Length);
// Create more items
Employee employee2 = new Employee
{
Name = "Diane",
Age = 40,
CompanyName = "Madeira",
Score = 140,
ManagerName = "Eva",
Data = new byte[] { 1, 2, 3 },
CurrentStatus = Status.Upcoming,
InternalId = "Diane@Madeira",
};
await SharedTestFixture.Context.SaveAsync(employee2);
employee2.Age = 24;
employee2.Score = 101;
await SharedTestFixture.Context.SaveAsync(employee2);
retrieved = await SharedTestFixture.Context.LoadAsync<Employee>("Alan", 31);
Assert.Equal(retrieved.Name, "Alan");
retrieved = await SharedTestFixture.Context.LoadAsync(employee);
Assert.Equal(retrieved.Name, "Chuck");
retrieved = await SharedTestFixture.Context.LoadAsync(employee2, new DynamoDBOperationConfig { ConsistentRead = true });
Assert.Equal(retrieved.Name, "Diane");
Assert.Equal(retrieved.Age, 24);
// Scan for all items
var employees = await (SharedTestFixture.Context.ScanAsync<Employee>(new List<ScanCondition>())).GetNextSetAsync();
Assert.Equal(4, employees.Count);
// Query for items with Hash-Key = "Diane"
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Diane").GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Query for items with Hash-Key = "Diane" and Range-Key > 30
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Diane", QueryOperator.GreaterThan, new object[]{30}).GetNextSetAsync();
Assert.Equal(1, employees.Count);
// Index Query
// Query local index for items with Hash-Key = "Diane"
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Diane", new DynamoDBOperationConfig { IndexName = "LocalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Query local index for items with Hash-Key = "Diane" and Range-Key = "Eva"
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Diane", QueryOperator.Equal, new object[] { "Eva" },
new DynamoDBOperationConfig { IndexName = "LocalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Query global index for item with Hash-Key (Company) = "Big River"
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Big River", new DynamoDBOperationConfig { IndexName = "GlobalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Query global index for item with Hash-Key (Company) = "Big River", with QueryFilter for CurrentStatus = Status.Active
employees = await SharedTestFixture.Context.QueryAsync<Employee>("Big River",
new DynamoDBOperationConfig
{
IndexName = "GlobalIndex",
QueryFilter = new List<ScanCondition>
{
new ScanCondition("CurrentStatus", ScanOperator.Equal, Status.Active)
}
}).GetNextSetAsync();
Assert.Equal(1, employees.Count);
// Index Scan
// Scan local index for items with Hash-Key = "Diane"
employees = await SharedTestFixture.Context.ScanAsync<Employee>(
new List<ScanCondition> { new ScanCondition("Name", ScanOperator.Equal, "Diane") },
new DynamoDBOperationConfig { IndexName = "LocalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Scan local index for items with Hash-Key = "Diane" and Range-Key = "Eva"
employees = await SharedTestFixture.Context.ScanAsync<Employee>(
new List<ScanCondition>
{
new ScanCondition("Name", ScanOperator.Equal, "Diane"),
new ScanCondition("ManagerName", ScanOperator.Equal, "Eva")
},
new DynamoDBOperationConfig { IndexName = "LocalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Scan global index for item with Hash-Key (Company) = "Big River"
employees = await SharedTestFixture.Context.ScanAsync<Employee>(
new List<ScanCondition> { new ScanCondition("CompanyName", ScanOperator.Equal, "Big River") },
new DynamoDBOperationConfig { IndexName = "GlobalIndex" }).GetNextSetAsync();
Assert.Equal(2, employees.Count);
// Scan global index for item with Hash-Key (Company) = "Big River", with QueryFilter for CurrentStatus = Status.Active
employees = await SharedTestFixture.Context.ScanAsync<Employee>(
new List<ScanCondition>
{
new ScanCondition("CompanyName", ScanOperator.Equal, "Big River"),
new ScanCondition("CurrentStatus", ScanOperator.Equal, Status.Active)
},
new DynamoDBOperationConfig
{
IndexName = "GlobalIndex"
}).GetNextSetAsync();
Assert.Equal(1, employees.Count);
}
private async Task TestBatchOperations()
{
int itemCount = 10;
string employeePrefix = "Employee-";
int employeeAgeStart = 20;
int productIdStart = 90;
string productPrefix = "Product-";
var allEmployees = new List<Employee>();
var batchWrite1 = SharedTestFixture.Context.CreateBatchWrite<Employee>();
var batchWrite2 = SharedTestFixture.Context.CreateBatchWrite<Product>();
for (int i = 0; i < itemCount; i++)
{
var employee = new Employee
{
Name = employeePrefix + i,
Age = employeeAgeStart + i,
CompanyName = "Big River",
CurrentStatus = i % 2 == 0 ? Status.Active : Status.Inactive,
Score = 90 + i,
ManagerName = "Barbara",
InternalId = i + "@BigRiver",
Data = Encoding.UTF8.GetBytes(new string('@', i + 5))
};
allEmployees.Add(employee);
batchWrite2.AddPutItem(new Product
{
Id = productIdStart + i,
Name = productPrefix + i
});
}
batchWrite1.AddPutItems(allEmployees);
// Write both batches at once
var multiTableWrite = SharedTestFixture.Context.CreateMultiTableBatchWrite(batchWrite1, batchWrite2);
await multiTableWrite.ExecuteAsync();
// Create BatchGets
var batchGet1 = SharedTestFixture.Context.CreateBatchGet<Product>();
var batchGet2 = SharedTestFixture.Context.CreateBatchGet<Employee>();
for (int i = 0; i < itemCount;i++ )
batchGet1.AddKey(productIdStart + i, productPrefix + i);
foreach (var employee in allEmployees)
batchGet2.AddKey(employee);
// Execute BatchGets together
await SharedTestFixture.Context.ExecuteBatchGetAsync(batchGet1, batchGet2);
// Verify items are loaded
Assert.Equal(itemCount, batchGet1.Results.Count);
Assert.Equal(itemCount, batchGet2.Results.Count);
}
private async Task TestOtherContextOperations()
{
Employee employee1 = new Employee
{
Name = "Alan",
Age = 31,
CompanyName = "Big River",
CurrentStatus = Status.Active,
Score = 120,
ManagerName = "Barbara",
InternalId = "Alan@BigRiver",
Aliases = new List<string> { "Al", "Steve" },
Data = Encoding.UTF8.GetBytes("Some binary data")
};
Document doc = SharedTestFixture.Context.ToDocument(employee1);
Assert.Equal(employee1.Name, doc["Name"].AsString());
Assert.Equal(employee1.Data.Length, doc["Data"].AsByteArray().Length);
// Ignored properties are not propagated to the Document
Assert.False(doc.ContainsKey("InternalId"));
Employee roundtrip = SharedTestFixture.Context.FromDocument<Employee>(doc);
Assert.Equal(employee1.Name, roundtrip.Name);
Assert.Equal(employee1.Data.Length, roundtrip.Data.Length);
Assert.Null(roundtrip.InternalId);
// Recreate the record
await SharedTestFixture.Context.DeleteAsync(employee1);
await SharedTestFixture.Context.SaveAsync(employee1);
// Get record using Table instead of Context
var table = SharedTestFixture.Context.GetTargetTable<Employee>();
Document retrieved = await table.GetItemAsync(doc);
Assert.Equal(employee1.Name, doc["Name"].AsString());
Assert.Equal(employee1.Data.Length, doc["Data"].AsByteArray().Length);
}
#region OPM definitions
public enum Status : long
{
Active = 256,
Inactive = 1024,
Upcoming = 9999,
Obsolete = -10,
Removed = 42
}
[Flags]
public enum Support
{
Windows = 1 << 0,
iOS = 1 << 1,
Unix = 1 << 2,
Abacus = 1 << 3,
}
public class StatusConverter : IPropertyConverter
{
public DynamoDBEntry ToEntry(object value)
{
Status status = (Status)value;
return new Primitive(status.ToString());
}
public object FromEntry(DynamoDBEntry entry)
{
Primitive primitive = entry.AsPrimitive();
string text = primitive.AsString();
Status status = (Status)Enum.Parse(typeof(Status), text);
return status;
}
}
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashTable
/// </summary>
[DynamoDBTable("HashTable")]
public class Product
{
[DynamoDBHashKey]
public int Id { get; set; }
[DynamoDBProperty("Product")]
public string Name { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey("GlobalIndex", AttributeName = "Company")]
public string CompanyName { get; set; }
public CompanyInfo CompanyInfo { get; set; }
[DynamoDBGlobalSecondaryIndexRangeKey("GlobalIndex")]
public int Price { get; set; }
[DynamoDBProperty("Tags")]
public HashSet<string> TagSet { get; set; }
public MemoryStream Data { get; set; }
[DynamoDBProperty(Converter = typeof(StatusConverter))]
public Status CurrentStatus { get; set; }
public Status FormerStatus { get; set; }
public Support Supports { get; set; }
public Support? PreviousSupport { get; set; }
[DynamoDBIgnore]
public string InternalId { get; set; }
public bool IsPublic { get; set; }
//[DynamoDBProperty(Converter = typeof(BoolAsNConverter))]
public bool AlwaysN { get; set; }
public int? Rating { get; set; }
public List<string> Components { get; set; }
//[DynamoDBProperty(Converter = typeof(SetPropertyConverter<List<byte>,byte>))]
[DynamoDBProperty(Converter = typeof(ListToSetPropertyConverter<byte>))]
public List<byte> KeySizes { get; set; }
public Dictionary<string, string> Map { get; set; }
public S3Link FullProductDescription { get; set; }
}
public class CompanyInfo
{
public string Name { get; set; }
public DateTime Founded { get; set; }
public Product MostPopularProduct { get; set; }
public List<Product> AllProducts { get; set; }
public Dictionary<string, List<Product>> CompetitorProducts { get; set; }
[DynamoDBIgnore]
public decimal Revenue { get; set; }
}
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashTable
/// This class uses optimistic locking via the Version field
/// </summary>
public class VersionedProduct : Product
{
[DynamoDBVersion]
public int? Version { get; set; }
}
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashTable,
/// with the Id field being an Enum, with hidden int conversion
/// </summary>
[DynamoDBTable("HashTable")]
public class EnumProduct1
{
[DynamoDBIgnore]
public Status Id { get; set; }
[DynamoDBHashKey("Id")]
public int IdAsInt
{
get { return (int)Id; }
set { Id = (Status)value; }
}
[DynamoDBProperty("Product")]
public string Name { get; set; }
}
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashTable,
/// with the Id field being an Enum
/// </summary>
[DynamoDBTable("HashTable")]
public class EnumProduct2
{
public Status Id { get; set; }
[DynamoDBProperty("Product")]
public string Name { get; set; }
}
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashRangeTable
///
/// No DynamoDB attributes are defined on the type:
/// -some attributes are inferred from the table
/// -some attributes are defined in app.config
/// </summary>
public class Employee
{
// Hash key
public string Name { get; set; }
// Range key
public int Age { get; set; }
public string CompanyName { get; set; }
public int Score { get; set; }
public string ManagerName { get; set; }
public byte[] Data { get; set; }
public Status CurrentStatus { get; set; }
public List<string> Aliases { get; set; }
public string InternalId { get; set; }
}
/// <summary>
/// Class with a property of a type that has no valid constructor
/// </summary>
public class Employee2 : Employee
{
public TimeSpan TimeWithCompany { get; set; }
}
/// <summary>
/// Class with a property of an empty type
/// </summary>
public class Employee3 : Employee
{
public EmptyType EmptyProperty { get; set; }
}
/// <summary>
/// Empty type
/// </summary>
public class EmptyType
{ }
/// <summary>
/// Class representing items in the table [TableNamePrefix]HashTable
/// This class uses optimistic locking via the Version field
/// </summary>
public class VersionedEmployee : Employee
{
public int? Version { get; set; }
}
#endregion
}
}
| 44.772822 | 181 | 0.55812 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/test/CoreCLR/IntegrationTests/IntegrationTests/DynamoDB/DataModelTests.cs | 43,163 | C# |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the macie2-2020-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Macie2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Macie2.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateOrganizationConfiguration Request Marshaller
/// </summary>
public class UpdateOrganizationConfigurationRequestMarshaller : IMarshaller<IRequest, UpdateOrganizationConfigurationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UpdateOrganizationConfigurationRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateOrganizationConfigurationRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Macie2");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-01-01";
request.HttpMethod = "PATCH";
request.ResourcePath = "/admin/configuration";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAutoEnable())
{
context.Writer.WritePropertyName("autoEnable");
context.Writer.Write(publicRequest.AutoEnable);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpdateOrganizationConfigurationRequestMarshaller _instance = new UpdateOrganizationConfigurationRequestMarshaller();
internal static UpdateOrganizationConfigurationRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateOrganizationConfigurationRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.145631 | 177 | 0.645716 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Macie2/Generated/Model/Internal/MarshallTransformations/UpdateOrganizationConfigurationRequestMarshaller.cs | 3,723 | C# |
#pragma checksum "C:\Users\ureta\OneDrive\Documentos\dev\C#\TaDandoOnda\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\ureta\OneDrive\Documentos\dev\C#\TaDandoOnda\Views\_ViewImports.cshtml"
using TaDandoOnda;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\ureta\OneDrive\Documentos\dev\C#\TaDandoOnda\Views\_ViewImports.cshtml"
using TaDandoOnda.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9883c040f79bf00de985dfa587461ac8be57929b", @"/Views/_ViewImports.cshtml")]
public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\ureta\OneDrive\Documentos\dev\C#\TaDandoOnda\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 47.830508 | 181 | 0.750177 | [
"MIT"
] | iuriaguiarr/SurfsUp | obj/Debug/netcoreapp3.1/Razor/Views/_ViewStart.cshtml.g.cs | 2,822 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: StreamRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
/// <summary>
/// The type ApplicationLogoRequestBuilder.
/// </summary>
public partial class ApplicationLogoRequestBuilder : BaseRequestBuilder, IApplicationLogoRequestBuilder
{
/// <summary>
/// Constructs a new ApplicationLogoRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public ApplicationLogoRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public IApplicationLogoRequest Request(IEnumerable<Option> options = null)
{
return new ApplicationLogoRequest(this.RequestUrl, this.Client, options);
}
}
}
| 37.952381 | 153 | 0.580301 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ApplicationLogoRequestBuilder.cs | 1,594 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Simplic.Flow.Editor.Definition.Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIMPLIC GmbH")]
[assembly: AssemblyProduct("Simplic.Flow.Editor.Definition.Service")]
[assembly: AssemblyCopyright("Copyright © SIMPLIC GmbH 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb050bc6-5e07-4875-9ff4-ff0046a0e589")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("7.0.121.513")]
[assembly: AssemblyFileVersion("7.0.121.513")]
| 39.916667 | 84 | 0.752262 | [
"MIT"
] | simplic/simplic-flow | src/Simplic.Flow.Editor.Definition.Service/Properties/AssemblyInfo.cs | 1,440 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.RecaptchaEnterprise.V1Beta1.Snippets
{
// [START recaptchaenterprise_v1beta1_generated_RecaptchaEnterpriseServiceV1Beta1_GetKey_async]
using Google.Cloud.RecaptchaEnterprise.V1Beta1;
using System.Threading.Tasks;
public sealed partial class GeneratedRecaptchaEnterpriseServiceV1Beta1ClientSnippets
{
/// <summary>Snippet for GetKeyAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetKeyRequestObjectAsync()
{
// Create client
RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync();
// Initialize request argument(s)
GetKeyRequest request = new GetKeyRequest
{
KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"),
};
// Make the request
Key response = await recaptchaEnterpriseServiceV1Beta1Client.GetKeyAsync(request);
}
}
// [END recaptchaenterprise_v1beta1_generated_RecaptchaEnterpriseServiceV1Beta1_GetKey_async]
}
| 42.6 | 154 | 0.716223 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.RecaptchaEnterprise.V1Beta1/Google.Cloud.RecaptchaEnterprise.V1Beta1.GeneratedSnippets/RecaptchaEnterpriseServiceV1Beta1Client.GetKeyRequestObjectAsyncSnippet.g.cs | 1,917 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
namespace System
{
internal static class Strings
{
public static string NO_ELEMENTS = "Source sequence doesn't contain any elements.";
public static string MORE_THAN_ONE_ELEMENT = "Source sequence contains more than one element.";
public static string NOT_SUPPORTED = "Specified method is not supported.";
}
}
| 39.928571 | 103 | 0.729875 | [
"Apache-2.0"
] | NewellClark/reactive | Ix.NET/Source/System.Linq.Async/System/Strings.cs | 561 | C# |
#if (UNITY_STANDALONE_WIN)
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.LongExposureInfraredFrameReference
//
public sealed partial class LongExposureInfraredFrameReference : Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal LongExposureInfraredFrameReference(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_LongExposureInfraredFrameReference_AddRefObject(ref _pNative);
}
~LongExposureInfraredFrameReference()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReference_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReference_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<LongExposureInfraredFrameReference>(_pNative);
Windows_Kinect_LongExposureInfraredFrameReference_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern long Windows_Kinect_LongExposureInfraredFrameReference_get_RelativeTime(RootSystem.IntPtr pNative);
public RootSystem.TimeSpan RelativeTime
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReference");
}
return RootSystem.TimeSpan.FromMilliseconds(Windows_Kinect_LongExposureInfraredFrameReference_get_RelativeTime(_pNative));
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameReference_AcquireFrame(RootSystem.IntPtr pNative);
public Windows.Kinect.LongExposureInfraredFrame AcquireFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReference");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameReference_AcquireFrame(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrame>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrame(n));
}
private void __EventCleanup()
{
}
}
}
#endif
| 40.956522 | 173 | 0.700637 | [
"MIT"
] | TastSong/Kinect3DRunner | Kinect3DRunner/Assets/K2Examples/Standard Assets/Windows/Kinect/LongExposureInfraredFrameReference.cs | 3,768 | C# |
using System.Collections.Generic;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Services;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.PropertyEditors
{
internal class EyeDropperColorPickerConfigurationEditor : ConfigurationEditor<EyeDropperColorPickerConfiguration>
{
public EyeDropperColorPickerConfigurationEditor(IIOHelper ioHelper, IEditorConfigurationParser editorConfigurationParser) : base(ioHelper, editorConfigurationParser)
{
}
/// <inheritdoc />
public override Dictionary<string, object> ToConfigurationEditor(EyeDropperColorPickerConfiguration? configuration)
{
return new Dictionary<string, object>
{
{ "showAlpha", configuration?.ShowAlpha ?? false },
{ "showPalette", configuration?.ShowPalette ?? false },
};
}
/// <inheritdoc />
public override EyeDropperColorPickerConfiguration FromConfigurationEditor(IDictionary<string, object?>? editorValues, EyeDropperColorPickerConfiguration? configuration)
{
var showAlpha = true;
var showPalette = true;
if (editorValues is not null && editorValues.TryGetValue("showAlpha", out var alpha))
{
var attempt = alpha.TryConvertTo<bool>();
if (attempt.Success)
showAlpha = attempt.Result;
}
if (editorValues is not null && editorValues.TryGetValue("showPalette", out var palette))
{
var attempt = palette.TryConvertTo<bool>();
if (attempt.Success)
showPalette = attempt.Result;
}
return new EyeDropperColorPickerConfiguration
{
ShowAlpha = showAlpha,
ShowPalette = showPalette
};
}
}
}
| 36.461538 | 177 | 0.618671 | [
"MIT"
] | Lantzify/Umbraco-CMS | src/Umbraco.Core/PropertyEditors/EyeDropperColorPickerConfigurationEditor.cs | 1,896 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace StudentSystem.Web.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 20.571429 | 55 | 0.502315 | [
"Apache-2.0"
] | encho253/StudentSystem | StudentSystem/StudentSystem.Web/Controllers/ValuesController.cs | 866 | C# |
#if UNITY_STANDALONE_WIN
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
using UnityExtensionMethods;
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable IdentifierTypo
// ReSharper disable once CheckNamespace
namespace SFB
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OpenFileName
{
public int structSize;
public IntPtr dlgOwner;
public IntPtr instance;
[MarshalAs(UnmanagedType.LPWStr)] public string filter;
[MarshalAs(UnmanagedType.LPStr)] public string customFilter;
public int maxCustFilter;
public int filterIndex;
public IntPtr file;
public int maxFile;
[MarshalAs(UnmanagedType.LPStr)] public string fileTitle;
public int maxFileTitle;
[MarshalAs(UnmanagedType.LPWStr)] public string initialDir;
[MarshalAs(UnmanagedType.LPWStr)] public string title;
public int flags;
public ushort fileOffset;
public ushort fileExtension;
[MarshalAs(UnmanagedType.LPWStr)] public string defExt;
[MarshalAs(UnmanagedType.LPWStr)] public string custData;
public IntPtr hook;
[MarshalAs(UnmanagedType.LPWStr)] public string templateName;
public IntPtr reservedPtr;
public int reservedInt;
public int flagsEx;
}
public class StandaloneFileBrowserWindows : IStandaloneFileBrowser
{
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
[DllImport("Comdlg32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetOpenFileName(ref OpenFileName openFileName);
public string[] OpenFilePanel(string title, string directory, ExtensionFilter[] extensions, bool multiselect)
{
try
{
var openFileName = new OpenFileName {dlgOwner = GetActiveWindow()};
if (extensions != null && extensions.Length > 0)
{
var stringBuilder = new StringBuilder();
foreach (ExtensionFilter filter in extensions)
{
stringBuilder.Append(filter.Name);
stringBuilder.Append("\0");
for (var ii = 0; ii < filter.Extensions.Length; ii++)
{
stringBuilder.Append("*.");
stringBuilder.Append(filter.Extensions[ii]);
if (ii + 1 < filter.Extensions.Length)
stringBuilder.Append(";");
}
stringBuilder.Append("\0");
}
stringBuilder.Append("\0");
openFileName.filter = stringBuilder.ToString();
}
else
openFileName.filter = "All files\0*.*\0\0";
openFileName.filterIndex = 1;
if (!string.IsNullOrEmpty(directory))
openFileName.initialDir = directory;
var chars = new char[65536];
for (var ii = 0; ii < 65536; ii++)
{
chars[ii] = ' ';
}
openFileName.file = Marshal.StringToBSTR(new string(chars));
openFileName.maxFile = 65536;
openFileName.title = title;
openFileName.flags = 0x00000008 | 0x00001000 | 0x00000800 |
(multiselect ? 0x00000200 | 0x00080000 : 0x00000000);
openFileName.structSize = Marshal.SizeOf(openFileName);
if (GetOpenFileName(ref openFileName))
{
string file = UnityFileMethods.ValidateFile(Marshal.PtrToStringBSTR(openFileName.file));
if (!multiselect)
return new[] {file};
char[] nullChar = {(char) 0};
string[] files = file.Split(nullChar, StringSplitOptions.RemoveEmptyEntries);
if (files.Length <= 2)
return new[] {file};
List<string> selectedFilesList = new List<string>();
for (var ii = 1; ii < files.Length - 1; ii++)
{
string resultFile = files[0] + '\\' + files[ii];
selectedFilesList.Add(UnityFileMethods.ValidateFile(resultFile));
}
return selectedFilesList.ToArray();
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
return new string[0];
}
public void OpenFilePanelAsync(string title, string directory, ExtensionFilter[] extensions,
bool multiselect,
Action<string[]> cb)
{
cb.Invoke(OpenFilePanel(title, directory, extensions, multiselect));
}
public string[] OpenFolderPanel(string title, string directory, bool multiselect)
{
return new string[0];
}
public void OpenFolderPanelAsync(string title, string directory, bool multiselect, Action<string[]> cb)
{
cb.Invoke(OpenFolderPanel(title, directory, multiselect));
}
public string SaveFilePanel(string title, string directory, string defaultName,
ExtensionFilter[] extensions)
{
return string.Empty;
}
public void SaveFilePanelAsync(string title, string directory, string defaultName,
ExtensionFilter[] extensions,
Action<string> cb)
{
cb.Invoke(SaveFilePanel(title, directory, defaultName, extensions));
}
}
}
#endif
| 34.660819 | 117 | 0.555593 | [
"MPL-2.0"
] | Dejers/Card-Game-Simulator | Assets/StandaloneFileBrowser/StandaloneFileBrowserWindows.cs | 5,927 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DotNetNuke.Modules.Forums.UserControls {
public partial class admin_dashboard {
}
}
| 28.9375 | 81 | 0.447084 | [
"MIT"
] | EPTamminga/DNN.Forum | UserControls/admin_dashboard.ascx.designer.cs | 465 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200301.Inputs
{
/// <summary>
/// Details the service to which the subnet is delegated.
/// </summary>
public sealed class DelegationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The name of the resource that is unique within a subnet. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers).
/// </summary>
[Input("serviceName")]
public Input<string>? ServiceName { get; set; }
public DelegationArgs()
{
}
}
}
| 29.121951 | 114 | 0.605528 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200301/Inputs/DelegationArgs.cs | 1,194 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
namespace System.ServiceModel
{
public abstract class DuplexClientBase<TChannel> : ClientBase<TChannel>
where TChannel : class
{
// IMPORTANT: any changes to the set of protected .ctors of this class need to be reflected
// in ServiceContractGenerator.cs as well.
protected DuplexClientBase(object callbackInstance)
: this(new InstanceContext(callbackInstance))
{
}
protected DuplexClientBase(object callbackInstance, string endpointConfigurationName)
: this(new InstanceContext(callbackInstance), endpointConfigurationName)
{
}
protected DuplexClientBase(object callbackInstance, string endpointConfigurationName, string remoteAddress)
: this(new InstanceContext(callbackInstance), endpointConfigurationName, remoteAddress)
{
}
protected DuplexClientBase(object callbackInstance, string endpointConfigurationName, EndpointAddress remoteAddress)
: this(new InstanceContext(callbackInstance), endpointConfigurationName, remoteAddress)
{
}
protected DuplexClientBase(object callbackInstance, Binding binding, EndpointAddress remoteAddress)
: this(new InstanceContext(callbackInstance), binding, remoteAddress)
{
}
protected DuplexClientBase(object callbackInstance, ServiceEndpoint endpoint)
: this(new InstanceContext(callbackInstance), endpoint)
{
}
protected DuplexClientBase(InstanceContext callbackInstance)
: base(callbackInstance)
{
}
protected DuplexClientBase(InstanceContext callbackInstance, string endpointConfigurationName)
: base(callbackInstance, endpointConfigurationName)
{
}
protected DuplexClientBase(InstanceContext callbackInstance, string endpointConfigurationName, string remoteAddress)
: base(callbackInstance, endpointConfigurationName, remoteAddress)
{
}
protected DuplexClientBase(InstanceContext callbackInstance, string endpointConfigurationName, EndpointAddress remoteAddress)
: base(callbackInstance, endpointConfigurationName, remoteAddress)
{
}
protected DuplexClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
: base(callbackInstance, binding, remoteAddress)
{
}
protected DuplexClientBase(InstanceContext callbackInstance, ServiceEndpoint endpoint)
: base(callbackInstance, endpoint)
{
}
public IDuplexContextChannel InnerDuplexChannel
{
get
{
return (IDuplexContextChannel)InnerChannel;
}
}
}
}
| 40.118421 | 133 | 0.693342 | [
"MIT"
] | 777Eternal777/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/DuplexClientBase.cs | 3,049 | C# |
using System;
using System.Runtime.InteropServices;
using NClang.Natives;
namespace NClang
{
public class ClangIndexerCallbacks
{
public event Func<IntPtr,bool> AbortQuery;
public event Action<IntPtr,ClangDiagnosticSet> Diagnostic;
public event Func<IntPtr,ClangFile,ClangIndex.ClientFile> EnteredMainFile;
public event Func<IntPtr,ClangIndex.IncludedFileInfo,ClangIndex.ClientFile> PreprocessIncludedFile;
public event Func<IntPtr,ClangIndex.ImportedAstFileInfo,ClangIndex.ClientAstFile> ImportedAstFile;
public event Func<IntPtr,ClangIndex.ContainerInfo> StartedTranslationUnit;
public event Action<IntPtr,ClangIndex.DeclarationInfo> IndexDeclaration;
public event Action<IntPtr,ClangIndex.EntityReferenceInfo> IndexEntityReference;
internal IndexerCallbacks ToNative ()
{
var ret = new IndexerCallbacks ();
if (AbortQuery != null)
ret.AbortQuery = (clientData, reserved) => AbortQuery (clientData) ? 1 : 0;
if (Diagnostic != null)
ret.Diagnostic = (clientData, ds, reserved) => Diagnostic (clientData, new ClangDiagnosticSet (ds));
if (EnteredMainFile != null)
ret.EnteredMainFile = (clientData, f, reserved) => EnteredMainFile (clientData, new ClangFile (f)).Address;
if (PreprocessIncludedFile != null)
ret.PpIncludedFile = (IntPtr clientData, IntPtr includedFile) => PreprocessIncludedFile (clientData, new ClangIndex.IncludedFileInfo (includedFile)).Address;
if (ImportedAstFile != null)
ret.ImportedASTFile = (IntPtr clientData, IntPtr importedAstFile) => ImportedAstFile (clientData, new ClangIndex.ImportedAstFileInfo (importedAstFile)).Address;
if (StartedTranslationUnit != null)
ret.StartedTranslationUnit = (clientData, reserved) => StartedTranslationUnit (clientData).Address;
if (IndexDeclaration != null)
ret.IndexDeclaration = (IntPtr clientData, IntPtr declInfo) => IndexDeclaration (clientData, new ClangIndex.DeclarationInfo (declInfo));
if (IndexEntityReference != null)
ret.IndexEntityReference = (IntPtr clientData, IntPtr entRefInfo) => IndexEntityReference (clientData, new ClangIndex.EntityReferenceInfo (entRefInfo));
return ret;
}
}
}
| 50.116279 | 164 | 0.779118 | [
"MIT"
] | Dadoum/nclang | NClang/LanguageService/ClangIndexerCallbacks.cs | 2,155 | C# |
using System;
using System.Linq;
using System.Reflection;
using HotChocolate.Language;
using HotChocolate.Types.Descriptors.Definitions;
namespace HotChocolate.Types.Descriptors
{
public class InterfaceFieldDescriptor
: OutputFieldDescriptorBase<InterfaceFieldDefinition>
, IInterfaceFieldDescriptor
{
private bool _argumentsInitialized;
protected internal InterfaceFieldDescriptor(
IDescriptorContext context,
NameString fieldName)
: base(context)
{
Definition.Name = fieldName.EnsureNotEmpty(nameof(fieldName));
}
protected internal InterfaceFieldDescriptor(
IDescriptorContext context,
InterfaceFieldDefinition definition)
: base(context)
{
Definition = definition ?? throw new ArgumentNullException(nameof(definition));
}
protected internal InterfaceFieldDescriptor(
IDescriptorContext context,
MemberInfo member)
: base(context)
{
Definition.Member = member
?? throw new ArgumentNullException(nameof(member));
Definition.Name = context.Naming.GetMemberName(
member,
MemberKind.InputObjectField);
Definition.Description = context.Naming.GetMemberDescription(
member,
MemberKind.InputObjectField);
Definition.Type = context.TypeInspector.GetOutputReturnTypeRef(member);
if (context.Naming.IsDeprecated(member, out string reason))
{
Deprecated(reason);
}
if (member is MethodInfo m)
{
Parameters = m.GetParameters().ToDictionary(t => new NameString(t.Name));
}
}
protected internal override InterfaceFieldDefinition Definition { get; protected set; } =
new InterfaceFieldDefinition();
protected override void OnCreateDefinition(InterfaceFieldDefinition definition)
{
if (!Definition.AttributesAreApplied && Definition.Member is not null)
{
Context.TypeInspector.ApplyAttributes(
Context,
this,
Definition.Member);
Definition.AttributesAreApplied = true;
}
base.OnCreateDefinition(definition);
CompleteArguments(definition);
}
private void CompleteArguments(InterfaceFieldDefinition definition)
{
if (!_argumentsInitialized && Parameters.Any())
{
FieldDescriptorUtilities.DiscoverArguments(
Context,
definition.Arguments,
definition.Member);
_argumentsInitialized = true;
}
}
public new IInterfaceFieldDescriptor SyntaxNode(FieldDefinitionNode fieldDefinitionNode)
{
base.SyntaxNode(fieldDefinitionNode);
return this;
}
public new IInterfaceFieldDescriptor Name(NameString name)
{
base.Name(name);
return this;
}
public new IInterfaceFieldDescriptor Description(string description)
{
base.Description(description);
return this;
}
[Obsolete("Use `Deprecated`.")]
public IInterfaceFieldDescriptor DeprecationReason(string reason) =>
Deprecated(reason);
public new IInterfaceFieldDescriptor Deprecated(string reason)
{
base.Deprecated(reason);
return this;
}
public new IInterfaceFieldDescriptor Deprecated()
{
base.Deprecated();
return this;
}
public new IInterfaceFieldDescriptor Type<TOutputType>()
where TOutputType : IOutputType
{
base.Type<TOutputType>();
return this;
}
public new IInterfaceFieldDescriptor Type<TOutputType>(TOutputType outputType)
where TOutputType : class, IOutputType
{
base.Type(outputType);
return this;
}
public new IInterfaceFieldDescriptor Type(ITypeNode type)
{
base.Type(type);
return this;
}
public new IInterfaceFieldDescriptor Type(Type type)
{
base.Type(type);
return this;
}
public new IInterfaceFieldDescriptor Argument(
NameString name,
Action<IArgumentDescriptor> argument)
{
base.Argument(name, argument);
return this;
}
public new IInterfaceFieldDescriptor Ignore(bool ignore = true)
{
base.Ignore(ignore);
return this;
}
public new IInterfaceFieldDescriptor Directive<T>(T directive)
where T : class
{
base.Directive(directive);
return this;
}
public new IInterfaceFieldDescriptor Directive<T>()
where T : class, new()
{
base.Directive<T>();
return this;
}
public new IInterfaceFieldDescriptor Directive(
NameString name,
params ArgumentNode[] arguments)
{
base.Directive(name, arguments);
return this;
}
public static InterfaceFieldDescriptor New(
IDescriptorContext context,
NameString fieldName) =>
new InterfaceFieldDescriptor(context, fieldName);
public static InterfaceFieldDescriptor New(
IDescriptorContext context,
MemberInfo member) =>
new InterfaceFieldDescriptor(context, member);
public static InterfaceFieldDescriptor From(
IDescriptorContext context,
InterfaceFieldDefinition definition) =>
new InterfaceFieldDescriptor(context, definition);
}
}
| 30.258706 | 97 | 0.58221 | [
"MIT"
] | Alxandr/hotchocolate | src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceFieldDescriptor.cs | 6,082 | C# |
// Copyright (c) 2021 Maxim Kuzmin. All rights reserved. Licensed under the MIT License.
using Makc2021.Layer3.Sample.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Makc2021.Layer3.Sample.Mappers.EF.Entities.UserToken
{
/// <summary>
/// Схема сущности "UserToken" сопоставителя.
/// </summary>
public class MapperUserTokenEntitySchema : MapperSchema<MapperUserTokenEntityObject>
{
#region Constructors
/// <inheritdoc/>
public MapperUserTokenEntitySchema(EntitiesSettings entitiesSettings)
: base(entitiesSettings)
{
}
#endregion Constructors
#region Public methods
/// <inheritdoc/>
public sealed override void Configure(EntityTypeBuilder<MapperUserTokenEntityObject> builder)
{
Sample.Entities.UserToken.UserTokenEntitySettings setting = EntitiesSettings.UserToken;
builder.ToTable(setting.DbTable, setting.DbSchema);
builder.HasKey(x => new { x.UserId, x.LoginProvider, x.Name }).HasName(setting.DbPrimaryKey);
builder.Property(x => x.LoginProvider)
.HasColumnName(setting.DbColumnForLoginProvider);
builder.Property(x => x.Name)
.HasColumnName(setting.DbColumnForName);
builder.Property(x => x.Value)
.HasColumnName(setting.DbColumnForValue);
builder.Property(x => x.UserId)
.HasColumnName(setting.DbColumnForUserEntityId);
builder.HasOne(x => x.ObjectOfUserEntity)
.WithMany(x => x.ObjectsOfUserTokenEntity)
.HasForeignKey(x => x.UserId)
.HasConstraintName(setting.DbForeignKeyToUserEntity);
}
#endregion Public methods
}
}
| 33.107143 | 105 | 0.654261 | [
"MIT"
] | maxim-kuzmin/Makc2021 | server/src/Makc2021.Layer3.Sample.Mappers.EF/Entities/UserToken/MapperUserTokenEntitySchema.cs | 1,882 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace QuartzHost.Contract.Models
{
public interface IEntity
{
}
public class BaseEntity
{
public int Total { get; set; }
}
} | 15.333333 | 38 | 0.656522 | [
"MIT"
] | cddldg/QuartzHost | src/QuartzHost.Contract/Models/IEntity.cs | 232 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LoggingFromAppConfig")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("LoggingFromAppConfig")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("be81d417-c98e-401d-b8cc-e98f572f92c8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.675676 | 84 | 0.751223 | [
"Apache-2.0",
"MIT"
] | abombss/NServiceBus | IntegrationTests/GenericHost/LoggingFromAppConfig/Properties/AssemblyInfo.cs | 1,434 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace Serpent5.AspNetCore.Middleware.CacheHeaders;
public class CacheHeadersMiddleware
{
private readonly RequestDelegate nextMiddleware;
public CacheHeadersMiddleware(RequestDelegate nextMiddleware)
=> this.nextMiddleware = nextMiddleware;
public Task InvokeAsync(HttpContext ctx)
{
ArgumentNullException.ThrowIfNull(ctx);
ctx.Response.OnStarting(
static ctxAsObject =>
{
var ctx = (HttpContext)ctxAsObject;
var httpResponseHeaders = ctx.Response.GetTypedHeaders();
// It's common to set "Cache-Control: no-cache, no-store".
// According to MDN (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control):
// - no-store means "Don't cache this, ever".
// - no-cache means "Check with me before you use the cache".
// Because this doesn't seem logical, let's clear the value and let the "no-store" fallback kick in.
if (httpResponseHeaders.CacheControl is { NoCache: true, NoStore: true })
httpResponseHeaders.CacheControl = null;
// Prefer ETag over Last-Modified.
if (httpResponseHeaders.ETag is not null)
httpResponseHeaders.LastModified = null;
// Set a default Cache-Control header
if (httpResponseHeaders.ETag is not null || httpResponseHeaders.LastModified is not null)
// Resources with a version identifier should be checked first.
httpResponseHeaders.CacheControl ??= new() { NoCache = true };
else
// All other resources aren't cacheable.
httpResponseHeaders.CacheControl ??= new() { NoStore = true };
// The Cache-Control header supercedes Expires and Pragma.
ctx.Response.Headers.Remove(HeaderNames.Expires);
ctx.Response.Headers.Remove(HeaderNames.Pragma);
return Task.CompletedTask;
},
ctx);
return nextMiddleware(ctx);
}
}
| 41.240741 | 116 | 0.610238 | [
"MIT"
] | serpent5/Serpent5.AspNetCore.Middleware | Serpent5.AspNetCore.Middleware/CacheHeaders/CacheHeadersMiddleware.cs | 2,227 | C# |
/*
** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
** Copyright (C) 2011 Silicon Graphics, Inc.
** All Rights Reserved.
**
** 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 including the dates of first publication and either this
** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC.
** 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.
**
** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not
** be used in advertising or otherwise to promote the sale, use or other dealings in
** this Software without prior written authorization from Silicon Graphics, Inc.
*/
/*
** Original Author: Eric Veach, July 1994.
** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/.
** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet
*/
using System.Diagnostics;
namespace LibTessDotNet
{
internal class Mesh
{
internal MeshUtils.Vertex _vHead;
internal MeshUtils.Face _fHead;
internal MeshUtils.Edge _eHead, _eHeadSym;
public Mesh()
{
var v = _vHead = new MeshUtils.Vertex();
var f = _fHead = new MeshUtils.Face();
var pair = MeshUtils.EdgePair.Create();
var e = _eHead = pair._e;
var eSym = _eHeadSym = pair._eSym;
v._next = v._prev = v;
v._anEdge = null;
f._next = f._prev = f;
f._anEdge = null;
f._trail = null;
f._marked = false;
f._inside = false;
e._next = e;
e._Sym = eSym;
e._Onext = null;
e._Lnext = null;
e._Org = null;
e._Lface = null;
e._winding = 0;
e._activeRegion = null;
eSym._next = eSym;
eSym._Sym = e;
eSym._Onext = null;
eSym._Lnext = null;
eSym._Org = null;
eSym._Lface = null;
eSym._winding = 0;
eSym._activeRegion = null;
}
/// <summary>
/// Creates one edge, two vertices and a loop (face).
/// The loop consists of the two new half-edges.
/// </summary>
public MeshUtils.Edge MakeEdge()
{
var e = MeshUtils.MakeEdge(_eHead);
MeshUtils.MakeVertex(new MeshUtils.Vertex(), e, _vHead);
MeshUtils.MakeVertex(new MeshUtils.Vertex(), e._Sym, _vHead);
MeshUtils.MakeFace(new MeshUtils.Face(), e, _fHead);
return e;
}
/// <summary>
/// Splice is the basic operation for changing the
/// mesh connectivity and topology. It changes the mesh so that
/// eOrg->Onext = OLD( eDst->Onext )
/// eDst->Onext = OLD( eOrg->Onext )
/// where OLD(...) means the value before the meshSplice operation.
///
/// This can have two effects on the vertex structure:
/// - if eOrg->Org != eDst->Org, the two vertices are merged together
/// - if eOrg->Org == eDst->Org, the origin is split into two vertices
/// In both cases, eDst->Org is changed and eOrg->Org is untouched.
///
/// Similarly (and independently) for the face structure,
/// - if eOrg->Lface == eDst->Lface, one loop is split into two
/// - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one
/// In both cases, eDst->Lface is changed and eOrg->Lface is unaffected.
///
/// Some special cases:
/// If eDst == eOrg, the operation has no effect.
/// If eDst == eOrg->Lnext, the new face will have a single edge.
/// If eDst == eOrg->Lprev, the old face will have a single edge.
/// If eDst == eOrg->Onext, the new vertex will have a single edge.
/// If eDst == eOrg->Oprev, the old vertex will have a single edge.
/// </summary>
public void Splice(MeshUtils.Edge eOrg, MeshUtils.Edge eDst)
{
if (eOrg == eDst)
{
return;
}
bool joiningVertices = false;
if (eDst._Org != eOrg._Org)
{
// We are merging two disjoint vertices -- destroy eDst->Org
joiningVertices = true;
MeshUtils.KillVertex(eDst._Org, eOrg._Org);
}
bool joiningLoops = false;
if (eDst._Lface != eOrg._Lface)
{
// We are connecting two disjoint loops -- destroy eDst->Lface
joiningLoops = true;
MeshUtils.KillFace(eDst._Lface, eOrg._Lface);
}
// Change the edge structure
MeshUtils.Splice(eDst, eOrg);
if (!joiningVertices)
{
// We split one vertex into two -- the new vertex is eDst->Org.
// Make sure the old vertex points to a valid half-edge.
MeshUtils.MakeVertex(new MeshUtils.Vertex(), eDst, eOrg._Org);
eOrg._Org._anEdge = eOrg;
}
if (!joiningLoops)
{
// We split one loop into two -- the new loop is eDst->Lface.
// Make sure the old face points to a valid half-edge.
MeshUtils.MakeFace(new MeshUtils.Face(), eDst, eOrg._Lface);
eOrg._Lface._anEdge = eOrg;
}
}
/// <summary>
/// Removes the edge eDel. There are several cases:
/// if (eDel->Lface != eDel->Rface), we join two loops into one; the loop
/// eDel->Lface is deleted. Otherwise, we are splitting one loop into two;
/// the newly created loop will contain eDel->Dst. If the deletion of eDel
/// would create isolated vertices, those are deleted as well.
/// </summary>
public void Delete(MeshUtils.Edge eDel)
{
var eDelSym = eDel._Sym;
// First step: disconnect the origin vertex eDel->Org. We make all
// changes to get a consistent mesh in this "intermediate" state.
bool joiningLoops = false;
if (eDel._Lface != eDel._Rface)
{
// We are joining two loops into one -- remove the left face
joiningLoops = true;
MeshUtils.KillFace(eDel._Lface, eDel._Rface);
}
if (eDel._Onext == eDel)
{
MeshUtils.KillVertex(eDel._Org, null);
}
else
{
// Make sure that eDel->Org and eDel->Rface point to valid half-edges
eDel._Rface._anEdge = eDel._Oprev;
eDel._Org._anEdge = eDel._Onext;
MeshUtils.Splice(eDel, eDel._Oprev);
if (!joiningLoops)
{
// We are splitting one loop into two -- create a new loop for eDel.
MeshUtils.MakeFace(new MeshUtils.Face(), eDel, eDel._Lface);
}
}
// Claim: the mesh is now in a consistent state, except that eDel->Org
// may have been deleted. Now we disconnect eDel->Dst.
if (eDelSym._Onext == eDelSym)
{
MeshUtils.KillVertex(eDelSym._Org, null);
MeshUtils.KillFace(eDelSym._Lface, null);
}
else
{
// Make sure that eDel->Dst and eDel->Lface point to valid half-edges
eDel._Lface._anEdge = eDelSym._Oprev;
eDelSym._Org._anEdge = eDelSym._Onext;
MeshUtils.Splice(eDelSym, eDelSym._Oprev);
}
// Any isolated vertices or faces have already been freed.
MeshUtils.KillEdge(eDel);
}
/// <summary>
/// Creates a new edge such that eNew == eOrg.Lnext and eNew.Dst is a newly created vertex.
/// eOrg and eNew will have the same left face.
/// </summary>
public MeshUtils.Edge AddEdgeVertex(MeshUtils.Edge eOrg)
{
var eNew = MeshUtils.MakeEdge(eOrg);
var eNewSym = eNew._Sym;
// Connect the new edge appropriately
MeshUtils.Splice(eNew, eOrg._Lnext);
// Set vertex and face information
eNew._Org = eOrg._Dst;
MeshUtils.MakeVertex(new MeshUtils.Vertex(), eNewSym, eNew._Org);
eNew._Lface = eNewSym._Lface = eOrg._Lface;
return eNew;
}
/// <summary>
/// Splits eOrg into two edges eOrg and eNew such that eNew == eOrg.Lnext.
/// The new vertex is eOrg.Dst == eNew.Org.
/// eOrg and eNew will have the same left face.
/// </summary>
public MeshUtils.Edge SplitEdge(MeshUtils.Edge eOrg)
{
var eTmp = AddEdgeVertex(eOrg);
var eNew = eTmp._Sym;
// Disconnect eOrg from eOrg->Dst and connect it to eNew->Org
MeshUtils.Splice(eOrg._Sym, eOrg._Sym._Oprev);
MeshUtils.Splice(eOrg._Sym, eNew);
// Set the vertex and face information
eOrg._Dst = eNew._Org;
eNew._Dst._anEdge = eNew._Sym; // may have pointed to eOrg->Sym
eNew._Rface = eOrg._Rface;
eNew._winding = eOrg._winding; // copy old winding information
eNew._Sym._winding = eOrg._Sym._winding;
return eNew;
}
/// <summary>
/// Creates a new edge from eOrg->Dst to eDst->Org, and returns the corresponding half-edge eNew.
/// If eOrg->Lface == eDst->Lface, this splits one loop into two,
/// and the newly created loop is eNew->Lface. Otherwise, two disjoint
/// loops are merged into one, and the loop eDst->Lface is destroyed.
///
/// If (eOrg == eDst), the new face will have only two edges.
/// If (eOrg->Lnext == eDst), the old face is reduced to a single edge.
/// If (eOrg->Lnext->Lnext == eDst), the old face is reduced to two edges.
/// </summary>
public MeshUtils.Edge Connect(MeshUtils.Edge eOrg, MeshUtils.Edge eDst)
{
var eNew = MeshUtils.MakeEdge(eOrg);
var eNewSym = eNew._Sym;
bool joiningLoops = false;
if (eDst._Lface != eOrg._Lface)
{
// We are connecting two disjoint loops -- destroy eDst->Lface
joiningLoops = true;
MeshUtils.KillFace(eDst._Lface, eOrg._Lface);
}
// Connect the new edge appropriately
MeshUtils.Splice(eNew, eOrg._Lnext);
MeshUtils.Splice(eNewSym, eDst);
// Set the vertex and face information
eNew._Org = eOrg._Dst;
eNewSym._Org = eDst._Org;
eNew._Lface = eNewSym._Lface = eOrg._Lface;
// Make sure the old face points to a valid half-edge
eOrg._Lface._anEdge = eNewSym;
if (!joiningLoops)
{
MeshUtils.MakeFace(new MeshUtils.Face(), eNew, eOrg._Lface);
}
return eNew;
}
/// <summary>
/// Destroys a face and removes it from the global face list. All edges of
/// fZap will have a NULL pointer as their left face. Any edges which
/// also have a NULL pointer as their right face are deleted entirely
/// (along with any isolated vertices this produces).
/// An entire mesh can be deleted by zapping its faces, one at a time,
/// in any order. Zapped faces cannot be used in further mesh operations!
/// </summary>
public void ZapFace(MeshUtils.Face fZap)
{
var eStart = fZap._anEdge;
// walk around face, deleting edges whose right face is also NULL
var eNext = eStart._Lnext;
MeshUtils.Edge e, eSym;
do {
e = eNext;
eNext = e._Lnext;
e._Lface = null;
if (e._Rface == null)
{
// delete the edge -- see TESSmeshDelete above
if (e._Onext == e)
{
MeshUtils.KillVertex(e._Org, null);
}
else
{
// Make sure that e._Org points to a valid half-edge
e._Org._anEdge = e._Onext;
MeshUtils.Splice(e, e._Oprev);
}
eSym = e._Sym;
if (eSym._Onext == eSym)
{
MeshUtils.KillVertex(eSym._Org, null);
}
else
{
// Make sure that eSym._Org points to a valid half-edge
eSym._Org._anEdge = eSym._Onext;
MeshUtils.Splice(eSym, eSym._Oprev);
}
MeshUtils.KillEdge(e);
}
} while (e != eStart);
/* delete from circular doubly-linked list */
var fPrev = fZap._prev;
var fNext = fZap._next;
fNext._prev = fPrev;
fPrev._next = fNext;
}
public void MergeConvexFaces(int maxVertsPerFace)
{
for (var f = _fHead._next; f != _fHead; f = f._next)
{
// Skip faces which are outside the result
if (!f._inside)
{
continue;
}
var eCur = f._anEdge;
var vStart = eCur._Org;
while (true)
{
var eNext = eCur._Lnext;
var eSym = eCur._Sym;
if (eSym != null && eSym._Lface != null && eSym._Lface._inside)
{
// Try to merge the neighbour faces if the resulting polygons
// does not exceed maximum number of vertices.
int curNv = f.VertsCount;
int symNv = eSym._Lface.VertsCount;
if ((curNv + symNv - 2) <= maxVertsPerFace)
{
// Merge if the resulting poly is convex.
if (Geom.VertCCW(eCur._Lprev._Org, eCur._Org, eSym._Lnext._Lnext._Org) &&
Geom.VertCCW(eSym._Lprev._Org, eSym._Org, eCur._Lnext._Lnext._Org))
{
eNext = eSym._Lnext;
Delete(eSym);
eCur = null;
}
}
}
if (eCur != null && eCur._Lnext._Org == vStart)
break;
// Continue to next edge.
eCur = eNext;
}
}
}
public void Check()
{
MeshUtils.Edge e;
MeshUtils.Face fPrev = _fHead, f;
for (fPrev = _fHead; (f = fPrev._next) != _fHead; fPrev = f)
{
e = f._anEdge;
do {
Debug.Assert(e._Sym != e);
Debug.Assert(e._Sym._Sym == e);
Debug.Assert(e._Lnext._Onext._Sym == e);
Debug.Assert(e._Onext._Sym._Lnext == e);
Debug.Assert(e._Lface == f);
e = e._Lnext;
} while (e != f._anEdge);
}
Debug.Assert(f._prev == fPrev && f._anEdge == null);
MeshUtils.Vertex vPrev = _vHead, v;
for (vPrev = _vHead; (v = vPrev._next) != _vHead; vPrev = v)
{
Debug.Assert(v._prev == vPrev);
e = v._anEdge;
do
{
Debug.Assert(e._Sym != e);
Debug.Assert(e._Sym._Sym == e);
Debug.Assert(e._Lnext._Onext._Sym == e);
Debug.Assert(e._Onext._Sym._Lnext == e);
Debug.Assert(e._Org == v);
e = e._Onext;
} while (e != v._anEdge);
}
Debug.Assert(v._prev == vPrev && v._anEdge == null);
MeshUtils.Edge ePrev = _eHead;
for (ePrev = _eHead; (e = ePrev._next) != _eHead; ePrev = e)
{
Debug.Assert(e._Sym._next == ePrev._Sym);
Debug.Assert(e._Sym != e);
Debug.Assert(e._Sym._Sym == e);
Debug.Assert(e._Org != null);
Debug.Assert(e._Dst != null);
Debug.Assert(e._Lnext._Onext._Sym == e);
Debug.Assert(e._Onext._Sym._Lnext == e);
}
Debug.Assert(e._Sym._next == ePrev._Sym
&& e._Sym == _eHeadSym
&& e._Sym._Sym == e
&& e._Org == null && e._Dst == null
&& e._Lface == null && e._Rface == null);
}
}
}
| 39.757511 | 106 | 0.499595 | [
"MIT"
] | uareurapid/nightinthewoods | Assets/Ferr/2DTerrain/Scripts/LibTessDotNet/Mesh.cs | 18,529 | C# |
namespace A_Miner_Task
{
using System;
using System.Collections.Generic;
using System.IO;
public class MinerTask
{
public static void Main(string[] args)
{
Dictionary<string, long> resources = AvalableResources();
ResourcesToFile(resources);
}
private static void ResourcesToFile(Dictionary<string, long> resources)
{
string result = null;
foreach (KeyValuePair<string, long> resource in resources)
{
result += $"{resource.Key} -> {resource.Value}{Environment.NewLine}";
}
File.WriteAllText("../../InputOutput/Output.txt", result);
}
private static Dictionary<string, long> AvalableResources()
{
string[] data = File.ReadAllLines("../../InputOutput/Input.txt");
Dictionary<string, long> resources = new Dictionary<string, long>();
string resourceName = data[0];
resources[resourceName] = 0;
for (int i = 1; i < data.Length; i++)
{
if (i % 2 == 0)
{
resourceName = data[i];
if (!resources.ContainsKey(resourceName))
{
resources[resourceName] = 0;
}
}
else
{
resources[resourceName] += long.Parse(data[i]);
}
}
return resources;
}
}
}
| 28.759259 | 85 | 0.484868 | [
"MIT"
] | RAstardzhiev/SoftUni-C- | Programming Fundamentals/Files and Exceptions - Exercises/A Miner Task/MinerTask.cs | 1,555 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HelloWorldWin
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
FormHello formHello = new FormHello();
Application.Run(formHello);
}
}
}
| 20.1 | 50 | 0.634328 | [
"MIT"
] | lgleto/HelloWorldWin | HelloWorldWin/Program.cs | 404 | C# |
using NgrxGettingStarted.Dtos;
using System.Collections.Generic;
namespace NgrxGettingStarted.Services
{
public interface IDoctorService
{
DoctorAddOrUpdateResponseDto AddOrUpdate(DoctorAddOrUpdateRequestDto request);
ICollection<DoctorDto> Get();
DoctorDto GetById(int id);
dynamic Remove(int id);
}
}
| 24.857143 | 86 | 0.732759 | [
"MIT"
] | QuinntyneBrown/ngrx-getting-started | NgrxGettingStarted/Services/IDoctorService.cs | 348 | C# |
/*
* Copyright 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.
*/
/*
* Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.ServiceCatalog
{
/// <summary>
/// Configuration for accessing Amazon ServiceCatalog service
/// </summary>
public partial class AmazonServiceCatalogConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.29");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonServiceCatalogConfig()
{
this.AuthenticationServiceName = "servicecatalog";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "servicecatalog";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-12-10";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.5 | 112 | 0.593868 | [
"Apache-2.0"
] | nechemiaseif/aws-sdk-net | sdk/src/Services/ServiceCatalog/Generated/AmazonServiceCatalogConfig.cs | 2,120 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Storages.Binary.Algo
File: BinaryMarketDataSerializer.cs
Created: 2015, 12, 14, 1:43 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Storages.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Reflection;
using Ecng.Serialization;
using StockSharp.Localization;
using StockSharp.Messages;
static class MarketDataVersions
{
//public static readonly Version Version30 = new Version(3, 0);
public static readonly Version Version31 = new Version(3, 1);
public static readonly Version Version33 = new Version(3, 3);
public static readonly Version Version34 = new Version(3, 4);
public static readonly Version Version35 = new Version(3, 5);
public static readonly Version Version36 = new Version(3, 6);
public static readonly Version Version40 = new Version(4, 0);
public static readonly Version Version41 = new Version(4, 1);
public static readonly Version Version42 = new Version(4, 2);
public static readonly Version Version43 = new Version(4, 3);
public static readonly Version Version44 = new Version(4, 4);
public static readonly Version Version45 = new Version(4, 5);
public static readonly Version Version46 = new Version(4, 6);
public static readonly Version Version47 = new Version(4, 7);
public static readonly Version Version48 = new Version(4, 8);
public static readonly Version Version49 = new Version(4, 9);
public static readonly Version Version50 = new Version(5, 0);
public static readonly Version Version51 = new Version(5, 1);
public static readonly Version Version52 = new Version(5, 2);
public static readonly Version Version53 = new Version(5, 3);
public static readonly Version Version54 = new Version(5, 4);
public static readonly Version Version55 = new Version(5, 5);
public static readonly Version Version56 = new Version(5, 6);
public static readonly Version Version57 = new Version(5, 7);
public static readonly Version Version58 = new Version(5, 8);
public static readonly Version Version59 = new Version(5, 9);
public static readonly Version Version60 = new Version(6, 0);
public static readonly Version Version61 = new Version(6, 1);
public static readonly Version Version62 = new Version(6, 2);
public static readonly Version Version63 = new Version(6, 3);
public static readonly Version Version64 = new Version(6, 4);
public static readonly Version Version65 = new Version(6, 5);
public static readonly Version Version66 = new Version(6, 6);
public static readonly Version Version67 = new Version(6, 7);
public static readonly Version Version68 = new Version(6, 8);
public static readonly Version Version69 = new Version(6, 9);
}
abstract class BinaryMetaInfo : MetaInfo
{
protected BinaryMetaInfo(DateTime date)
: base(date)
{
LocalOffset = DateTimeOffset.Now.Offset;
FirstLocalTime = LastLocalTime = DateTime.UtcNow;
}
public Version Version { get; set; }
public TimeSpan LocalOffset { get; private set; }
public TimeSpan ServerOffset { get; set; }
// сериализация и десериализация их полей сделана в дочерних классах
public decimal FirstPrice { get; set; }
public decimal LastPrice { get; set; }
public decimal FirstFractionalPrice { get; set; }
public decimal LastFractionalPrice { get; set; }
public decimal FirstFractionalVolume { get; set; }
public decimal LastFractionalVolume { get; set; }
public DateTime FirstLocalTime { get; set; }
public DateTime LastLocalTime { get; set; }
public TimeSpan FirstLocalOffset { get; set; }
public TimeSpan LastLocalOffset { get; set; }
public TimeSpan FirstServerOffset { get; set; }
public TimeSpan LastServerOffset { get; set; }
public TimeSpan FirstItemLocalOffset { get; set; }
public TimeSpan LastItemLocalOffset { get; set; }
public DateTime FirstItemLocalTime { get; set; }
public DateTime LastItemLocalTime { get; set; }
public long FirstSeqNum { get; set; }
public long PrevSeqNum { get; set; }
public override object LastId
{
get => LastTime;
set { }
}
public bool IsEmpty()
{
return Count == 0;
}
public override void Write(Stream stream)
{
stream.WriteByte((byte)Version.Major);
stream.WriteByte((byte)Version.Minor);
stream.WriteEx(Count);
stream.WriteEx(PriceStep);
if (Version < MarketDataVersions.Version40)
stream.WriteEx(0m); // ранее был StepPrice
stream.WriteEx(FirstTime);
stream.WriteEx(LastTime);
if (Version < MarketDataVersions.Version40)
return;
stream.WriteEx(LocalOffset);
// размер под дополнительную информацию.
// пока этой информации нет.
stream.WriteEx((short)0);
}
public override void Read(Stream stream)
{
Version = new Version(stream.ReadByte(), stream.ReadByte());
Count = stream.Read<int>();
PriceStep = stream.Read<decimal>();
/*FirstPriceStep = */LastPriceStep = PriceStep;
if (Version < MarketDataVersions.Version40)
stream.Read<decimal>(); // ранее был StepPrice
FirstTime = stream.Read<DateTime>().UtcKind();
LastTime = stream.Read<DateTime>().UtcKind();
if (Version < MarketDataVersions.Version40)
return;
LocalOffset = stream.Read<TimeSpan>();
// пропускаем блок данных, выделенных под дополнительную информацию
var extInfoSize = stream.Read<short>();
// здесь можно будет читать доп информацию из потока
stream.Position += extInfoSize;
}
protected void WriteFractionalPrice(Stream stream)
{
if (Version < MarketDataVersions.Version43)
return;
stream.WriteEx(FirstFractionalPrice);
stream.WriteEx(LastFractionalPrice);
}
protected void ReadFractionalPrice(Stream stream)
{
if (Version < MarketDataVersions.Version43)
return;
FirstFractionalPrice = stream.Read<decimal>();
LastFractionalPrice = stream.Read<decimal>();
}
protected void WritePriceStep(Stream stream)
{
WriteFractionalPrice(stream);
stream.WriteEx(/*FirstPriceStep*/0m);
stream.WriteEx(LastPriceStep);
}
protected void ReadPriceStep(Stream stream)
{
ReadFractionalPrice(stream);
/*FirstPriceStep = */stream.Read<decimal>();
LastPriceStep = stream.Read<decimal>();
}
protected void WriteFractionalVolume(Stream stream)
{
if (Version < MarketDataVersions.Version44)
return;
stream.WriteEx(VolumeStep);
stream.WriteEx(FirstFractionalVolume);
stream.WriteEx(LastFractionalVolume);
}
protected void ReadFractionalVolume(Stream stream)
{
if (Version < MarketDataVersions.Version44)
return;
VolumeStep = stream.Read<decimal>();
FirstFractionalVolume = stream.Read<decimal>();
LastFractionalVolume = stream.Read<decimal>();
}
protected void WriteLocalTime(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
stream.WriteEx(FirstLocalTime);
stream.WriteEx(LastLocalTime);
}
protected void ReadLocalTime(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
FirstLocalTime = stream.Read<DateTime>();
LastLocalTime = stream.Read<DateTime>();
}
protected void WriteOffsets(Stream stream)
{
stream.WriteEx(FirstLocalOffset);
stream.WriteEx(LastLocalOffset);
stream.WriteEx(FirstServerOffset);
stream.WriteEx(LastServerOffset);
}
protected void ReadOffsets(Stream stream)
{
FirstLocalOffset = stream.Read<TimeSpan>();
LastLocalOffset = stream.Read<TimeSpan>();
FirstServerOffset = stream.Read<TimeSpan>();
LastServerOffset = stream.Read<TimeSpan>();
}
protected void WriteSeqNums(Stream stream)
{
stream.WriteEx(FirstSeqNum);
stream.WriteEx(PrevSeqNum);
}
protected void ReadSeqNums(Stream stream)
{
FirstSeqNum = stream.Read<long>();
PrevSeqNum = stream.Read<long>();
}
protected void WriteItemLocalOffset(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
stream.WriteEx(FirstItemLocalOffset);
stream.WriteEx(LastItemLocalOffset);
}
protected void ReadItemLocalOffset(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
FirstItemLocalOffset = stream.Read<TimeSpan>();
LastItemLocalOffset = stream.Read<TimeSpan>();
}
protected void WriteItemLocalTime(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
stream.WriteEx(FirstItemLocalTime);
stream.WriteEx(LastItemLocalTime);
}
protected void ReadItemLocalTime(Stream stream, Version minVersion)
{
if (Version < minVersion)
return;
FirstItemLocalTime = stream.Read<DateTime>();
LastItemLocalTime = stream.Read<DateTime>();
}
//public override TMetaInfo Clone()
//{
// var copy = typeof(TMetaInfo).CreateInstance<TMetaInfo>(Date);
// copy.CopyFrom((TMetaInfo)this);
// return copy;
//}
public virtual void CopyFrom(BinaryMetaInfo src)
{
Version = src.Version;
Count = src.Count;
PriceStep = src.PriceStep;
//StepPrice = src.StepPrice;
FirstTime = src.FirstTime;
LastTime = src.LastTime;
LocalOffset = src.LocalOffset;
ServerOffset = src.ServerOffset;
FirstFractionalPrice = src.FirstFractionalPrice;
LastFractionalPrice = src.LastFractionalPrice;
VolumeStep = src.VolumeStep;
FirstFractionalVolume = src.FirstFractionalVolume;
LastFractionalVolume = src.LastFractionalVolume;
FirstLocalTime = src.FirstLocalTime;
LastLocalTime = src.LastLocalTime;
FirstLocalOffset = src.FirstLocalOffset;
LastLocalOffset = src.LastLocalOffset;
FirstServerOffset = src.FirstServerOffset;
LastServerOffset = src.LastServerOffset;
FirstItemLocalTime = src.FirstItemLocalTime;
LastItemLocalTime = src.LastItemLocalTime;
FirstItemLocalOffset = src.FirstItemLocalOffset;
LastItemLocalOffset = src.LastItemLocalOffset;
//FirstPriceStep = src.FirstPriceStep;
LastPriceStep = src.LastPriceStep;
FirstPrice = src.FirstPrice;
LastPrice = src.LastPrice;
FirstSeqNum = src.FirstSeqNum;
PrevSeqNum = src.PrevSeqNum;
}
}
abstract class BinaryMarketDataSerializer<TData, TMetaInfo> : IMarketDataSerializer<TData>
where TMetaInfo : BinaryMetaInfo
{
public class MarketDataEnumerator : SimpleEnumerator<TData>
{
private readonly TMetaInfo _originalMetaInfo;
public MarketDataEnumerator(BinaryMarketDataSerializer<TData, TMetaInfo> serializer, BitArrayReader reader, TMetaInfo metaInfo)
{
Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
Index = -1;
Reader = reader ?? throw new ArgumentNullException(nameof(reader));
_originalMetaInfo = metaInfo ?? throw new ArgumentNullException(nameof(metaInfo));
}
public BitArrayReader Reader { get; }
public TMetaInfo MetaInfo { get; private set; }
public BinaryMarketDataSerializer<TData, TMetaInfo> Serializer { get; }
public int Index { get; private set; }
public int PartSize { get; private set; }
public TData Previous { get; private set; }
public TData Delta { get; internal set; }
public override bool MoveNext()
{
if (Index < 0) // enumerator стоит перед первой записью
{
MetaInfo = (TMetaInfo)((IMarketDataSerializer)Serializer).CreateMetaInfo(_originalMetaInfo.Date);
MetaInfo.CopyFrom(_originalMetaInfo);
Index = 0;
}
if (Index >= MetaInfo.Count)
return false;
if (Index == PartSize)
PartSize += Reader.ReadInt();
Current = Serializer.MoveNext(this);
Previous = Current;
if (Index == (PartSize - 1))
{
//Reader.AlignReader();
if ((Reader.Offset % 8) != 0)
{
var shift = ((Reader.Offset / 8) * 8 + 8) - Reader.Offset;
Reader.Offset += shift;
}
}
Index++;
return true;
}
public override void Reset()
{
Index = -1;
MetaInfo = null;
Previous = Current = default;
PartSize = 0;
if (Reader != null)
Reader.Offset = 0;
}
}
protected BinaryMarketDataSerializer(SecurityId securityId, object arg, int dataSize, Version version, IExchangeInfoProvider exchangeInfoProvider)
{
if (securityId == null)
throw new ArgumentNullException(nameof(securityId));
Arg = arg;
SecurityId = securityId;
DataSize = dataSize;
Version = version;
ExchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider));
}
protected object Arg { get; }
protected SecurityId SecurityId { get; }
protected int DataSize { get; }
protected Version Version { get; set; }
protected IExchangeInfoProvider ExchangeInfoProvider { get; }
public TimeSpan TimePrecision { get; } = TimeSpan.FromTicks(1);
public StorageFormats Format => StorageFormats.Binary;
IMarketDataMetaInfo IMarketDataSerializer.CreateMetaInfo(DateTime date)
{
var info = typeof(TMetaInfo).CreateInstance<TMetaInfo>(date);
info.Version = Version;
return info;
}
void IMarketDataSerializer.Serialize(Stream stream, IEnumerable data, IMarketDataMetaInfo metaInfo)
{
Serialize(stream, data.Cast<TData>(), metaInfo);
}
IEnumerable IMarketDataSerializer.Deserialize(Stream stream, IMarketDataMetaInfo metaInfo)
{
return Deserialize(stream, metaInfo);
}
private void CheckVersion(TMetaInfo metaInfo, string operation)
{
if (metaInfo.Version <= Version)
return;
var name = $"{SecurityId}/{typeof(TData)}/{Arg}";
Debug.WriteLine($"Storage ({operation}) !! DISABLED !!: {name}");
throw new InvalidOperationException(LocalizedStrings.StorageVersionNewerKey.Put(name, metaInfo.Version, Version));
}
public void Serialize(Stream stream, IEnumerable<TData> data, IMarketDataMetaInfo metaInfo)
{
var typedInfo = (TMetaInfo)metaInfo;
CheckVersion(typedInfo, "Save");
//var temp = new MemoryStream { Capacity = DataSize * data.Count() * 2 };
using (var writer = new BitArrayWriter(stream))
OnSave(writer, data, typedInfo);
//return stream.To<byte[]>();
}
public IEnumerable<TData> Deserialize(Stream stream, IMarketDataMetaInfo metaInfo)
{
var typedInfo = (TMetaInfo)metaInfo;
CheckVersion(typedInfo, "Load");
var data = new MemoryStream();
stream.CopyTo(data);
stream.Dispose();
return new SimpleEnumerable<TData>(() => new MarketDataEnumerator(this, new BitArrayReader(data), typedInfo));
}
protected abstract void OnSave(BitArrayWriter writer, IEnumerable<TData> data, TMetaInfo metaInfo);
public abstract TData MoveNext(MarketDataEnumerator enumerator);
protected void WriteItemLocalTime(BitArrayWriter writer, TMetaInfo metaInfo, Message message, bool isTickPrecision)
{
var lastLocalOffset = metaInfo.LastItemLocalOffset;
metaInfo.LastItemLocalTime = writer.WriteTime(message.LocalTime, metaInfo.LastItemLocalTime, "local time", true, true, metaInfo.LocalOffset, true, isTickPrecision, ref lastLocalOffset, true);
metaInfo.LastItemLocalOffset = lastLocalOffset;
}
protected DateTimeOffset ReadItemLocalTime(BitArrayReader reader, TMetaInfo metaInfo, bool isTickPrecision)
{
var prevTsTime = metaInfo.FirstItemLocalTime;
var lastOffset = metaInfo.FirstItemLocalOffset;
var retVal = reader.ReadTime(ref prevTsTime, true, true, lastOffset, true, isTickPrecision, ref lastOffset);
metaInfo.FirstItemLocalTime = prevTsTime;
metaInfo.FirstItemLocalOffset = lastOffset;
return retVal;
}
}
} | 30.472381 | 194 | 0.720965 | [
"Apache-2.0"
] | Ahrvo-Trading-Systems/StockSharp | Algo/Storages/Binary/BinaryMarketDataSerializer.cs | 16,249 | C# |
using KetoRecipies.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace KetoRecipies.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LogoutModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return Page();
}
}
}
} | 27.756098 | 101 | 0.625659 | [
"Apache-2.0"
] | omence/KetoRecipes.com | KetoRecipies/Areas/Identity/Pages/Account/Logout.cshtml.cs | 1,140 | C# |
'From Squeak3.8 of ''5 May 2005'' [latest update: #6665] on 8 September 2005 at 3:07:58 pm'!
SmartSyntaxInterpreterPlugin subclass: #ServicesPlugin
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'VMMaker-Plugins'!
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 11:17'!
initialiseModule
self export: true.
^self sqServicesInitialize ! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 11:17'!
moduleUnloaded: aModuleName
"The module with the given name was just unloaded.
Make sure we have no dangling references."
self export: true.
self var: #aModuleName type: 'char *'.
(aModuleName strcmp: 'ServicesPlugin') = 0
ifTrue: [self sqServicesShutdown]! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:21'!
primitiveGetBytes
"Setup bytes, could be text, could be TIFF"
| length oop |
self primitive: 'primitiveGetBytes'.
length := self sqServicesGetTextStringLength.
oop := interpreterProxy instantiateClass: interpreterProxy classByteArray indexableSize: length.
self sqServicesGetTextStringInto: (interpreterProxy firstIndexableField: oop).
^oop
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 13:11'!
primitiveGetTextString
"Setup text string"
| length oop |
self primitive: 'primitiveGetTextString'.
length := self sqServicesGetTextStringLength.
oop := interpreterProxy instantiateClass: interpreterProxy classString indexableSize: length.
self sqServicesGetTextStringInto: (interpreterProxy firstIndexableField: oop).
^oop
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:23'!
primitiveSetBytes: aTextString
"Setup text string"
| dataTypesLength |
self primitive: 'primitiveSetBytes'
parameters: #(ByteArray).
dataTypesLength := interpreterProxy slotSizeOf: aTextString cPtrAsOop.
self sqServicesSetTextString: aTextString length: dataTypesLength.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:40'!
primitiveSetCopyOSTypeString: aTextString
"Setup copy ostype string"
self primitive: 'primitiveSetCopyOSTypeString'
parameters: #(String).
self sqServicesSetCopyOSTypeString: aTextString.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 11:25'!
primitiveSetDataTypes: dataTypes
"OSType MyAppsDataTypes[] ='TEXT','PICT','MooV','AIFF','utxt'}; "
| dataTypesLength |
self primitive: 'primitiveSetDataTypes'
parameters: #(String).
dataTypesLength := interpreterProxy slotSizeOf: dataTypes cPtrAsOop.
self sqServicesSetDataTypes: dataTypes length: dataTypesLength.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:40'!
primitiveSetPasteOSTypeString: aTextString
"Setup paste ostype string"
self primitive: 'primitiveSetPasteOSTypeString'
parameters: #(String).
self sqServicesSetPasteOSTypeString: aTextString.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:41'!
primitiveSetPerformOSTypeString: aTextString
"Setup perform ostype string"
self primitive: 'primitiveSetPerformOSTypeString'
parameters: #(String).
self sqServicesSetPerformOSTypeString: aTextString.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 9/8/2005 09:19'!
primitiveSetReturnBytes: aByteArray osType: aOSType
"Setup text string"
| dataTypesLength |
self primitive: 'primitiveSetReturnBytes'
parameters: #(ByteArray String).
dataTypesLength := interpreterProxy slotSizeOf: aByteArray cPtrAsOop.
self sqServicesSetBytes: aByteArray length: dataTypesLength osType: aOSType.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 15:13'!
primitiveSetReturnTextString: aTextString
"Setup text string"
| dataTypesLength |
self primitive: 'primitiveSetReturnTextString'
parameters: #(String).
dataTypesLength := interpreterProxy slotSizeOf: aTextString cPtrAsOop.
self sqServicesSetReturnTextString: aTextString length: dataTypesLength.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 11:33'!
primitiveSetSemaphore: semi
self primitive: 'primitiveSetSemaphore'
parameters: #(SmallInteger).
self sqServicesSetSemaphore: semi.
! !
!ServicesPlugin methodsFor: 'initialize' stamp: 'JMM 6/12/2005 11:44'!
primitiveSetTextString: aTextString
"Setup text string"
| dataTypesLength |
self primitive: 'primitiveSetTextString'
parameters: #(String).
dataTypesLength := interpreterProxy slotSizeOf: aTextString cPtrAsOop.
self sqServicesSetTextString: aTextString length: dataTypesLength.
! !
!ServicesPlugin class methodsFor: 'translation' stamp: 'JMM 9/8/2005 09:48'!
hasHeaderFile
"If there is a single intrinsic header file to be associated with the plugin, here is where you want to flag"
^true! !
!ServicesPlugin class methodsFor: 'translation' stamp: 'JMM 9/8/2005 09:52'!
requiresCrossPlatformFiles
"default is ok for most, any plugin needing platform specific files must say so"
^false! !
!ServicesPlugin class methodsFor: 'translation' stamp: 'JMM 6/12/2005 13:12'!
requiresPlatformFiles
"this plugin requires platform specific files in order to work"
^true! !
!ServicesPlugin class reorganize!
('translation' hasHeaderFile requiresCrossPlatformFiles requiresPlatformFiles)
!
!ServicesPlugin reorganize!
('initialize' initialiseModule moduleUnloaded: primitiveGetBytes primitiveGetTextString primitiveSetBytes: primitiveSetCopyOSTypeString: primitiveSetDataTypes: primitiveSetPasteOSTypeString: primitiveSetPerformOSTypeString: primitiveSetReturnBytes:osType: primitiveSetReturnTextString: primitiveSetSemaphore: primitiveSetTextString:)
!
| 1,865 | 4,840 | 0.786059 | [
"MIT"
] | AndWac/opensmalltalk-vm | platforms/Mac OS/plugins/ServicesPlugin/JMMServicesPlugin.2.cs | 5,595 | C# |
/*
* 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.Collections;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[SCENE INVENTORY]";
/// <summary>
/// Allows asynchronous derezzing of objects from the scene into a client's inventory.
/// </summary>
protected AsyncSceneObjectGroupDeleter m_asyncSceneObjectDeleter;
/// <summary>
/// Allows inventory details to be sent to clients asynchronously
/// </summary>
protected AsyncInventorySender m_asyncInventorySender;
/// <summary>
/// Creates all the scripts in the scene which should be started.
/// </summary>
/// <returns>
/// Number of scripts that were valid for starting. This does not guarantee that all these scripts
/// were actually started, but just that the start could be attempt (e.g. the asset data for the script could be found)
/// </returns>
public int CreateScriptInstances()
{
m_log.InfoFormat("[SCENE]: Initializing script instances in {0}", RegionInfo.RegionName);
int scriptsValidForStarting = 0;
EntityBase[] entities = Entities.GetEntities();
foreach (EntityBase group in entities)
{
if (group is SceneObjectGroup)
{
scriptsValidForStarting
+= ((SceneObjectGroup) group).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
((SceneObjectGroup) group).ResumeScripts();
}
}
m_log.InfoFormat(
"[SCENE]: Initialized {0} script instances in {1}",
scriptsValidForStarting, RegionInfo.RegionName);
return scriptsValidForStarting;
}
/// <summary>
/// Lets the script engines start processing scripts.
/// </summary>
public void StartScripts()
{
// m_log.InfoFormat("[SCENE]: Starting scripts in {0}, please wait.", RegionInfo.RegionName);
IScriptModule[] engines = RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule engine in engines)
engine.StartProcessing();
}
public void AddUploadedInventoryItem(UUID agentID, InventoryItemBase item)
{
IMoneyModule money = RequestModuleInterface<IMoneyModule>();
if (money != null)
{
money.ApplyUploadCharge(agentID, money.UploadCharge, "Asset upload");
}
AddInventoryItem(item);
}
public bool AddInventoryItemReturned(UUID AgentId, InventoryItemBase item)
{
if (AddInventoryItem(item))
return true;
else
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Unable to add item {1} to agent {2} inventory", item.Name, AgentId);
return false;
}
}
public bool AddInventoryItem(InventoryItemBase item)
{
return AddInventoryItem(item, true);
}
/// <summary>
/// Add the given inventory item to a user's inventory.
/// </summary>
/// <param name="item"></param>
public bool AddInventoryItem(InventoryItemBase item, bool trigger)
{
if (item.Folder != UUID.Zero && InventoryService.AddItem(item))
{
int userlevel = 0;
if (Permissions.IsGod(item.Owner))
{
userlevel = 1;
}
if (trigger)
EventManager.TriggerOnNewInventoryItemUploadComplete(item.Owner, (AssetType)item.AssetType, item.AssetID, item.Name, userlevel);
return true;
}
// OK so either the viewer didn't send a folderID or AddItem failed
UUID originalFolder = item.Folder;
InventoryFolderBase f = InventoryService.GetFolderForType(item.Owner, (AssetType)item.AssetType);
if (f != null)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Found folder {0} type {1} for item {2}",
f.Name, (AssetType)f.Type, item.Name);
item.Folder = f.ID;
}
else
{
f = InventoryService.GetRootFolder(item.Owner);
if (f != null)
{
item.Folder = f.ID;
}
else
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Could not find root folder for {0} when trying to add item {1} with no parent folder specified",
item.Owner, item.Name);
return false;
}
}
if (InventoryService.AddItem(item))
{
int userlevel = 0;
if (Permissions.IsGod(item.Owner))
{
userlevel = 1;
}
if (trigger)
EventManager.TriggerOnNewInventoryItemUploadComplete(item.Owner, (AssetType)item.AssetType, item.AssetID, item.Name, userlevel);
if (originalFolder != UUID.Zero)
{
// Tell the viewer that the item didn't go there
ChangePlacement(item, f);
}
return true;
}
else
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Agent {0} could not add item {1} {2}",
item.Owner, item.Name, item.ID);
return false;
}
}
private void ChangePlacement(InventoryItemBase item, InventoryFolderBase f)
{
ScenePresence sp = GetScenePresence(item.Owner);
if (sp != null)
{
if (sp.ControllingClient is IClientCore)
{
IClientCore core = (IClientCore)sp.ControllingClient;
IClientInventory inv;
if (core.TryGet<IClientInventory>(out inv))
{
InventoryFolderBase parent = new InventoryFolderBase(f.ParentID, f.Owner);
parent = InventoryService.GetFolder(parent);
inv.SendRemoveInventoryItems(new UUID[] { item.ID });
inv.SendBulkUpdateInventory(new InventoryFolderBase[0], new InventoryItemBase[] { item });
string message = "The item was placed in folder " + f.Name;
if (parent != null)
message += " under " + parent.Name;
sp.ControllingClient.SendAgentAlertMessage(message, false);
}
}
}
}
/// <summary>
/// Add the given inventory item to a user's inventory.
/// </summary>
/// <param name="AgentID">
/// A <see cref="UUID"/>
/// </param>
/// <param name="item">
/// A <see cref="InventoryItemBase"/>
/// </param>
[Obsolete("Use AddInventoryItem(InventoryItemBase item) instead. This was deprecated in OpenSim 0.7.1")]
public void AddInventoryItem(UUID AgentID, InventoryItemBase item)
{
AddInventoryItem(item);
}
/// <summary>
/// Add an inventory item to an avatar's inventory.
/// </summary>
/// <param name="remoteClient">The remote client controlling the avatar</param>
/// <param name="item">The item. This structure contains all the item metadata, including the folder
/// in which the item is to be placed.</param>
public void AddInventoryItem(IClientAPI remoteClient, InventoryItemBase item)
{
AddInventoryItem(item);
remoteClient.SendInventoryItemCreateUpdate(item, 0);
}
/// <summary>
/// <see>CapsUpdatedInventoryItemAsset(IClientAPI, UUID, byte[])</see>
/// </summary>
public UUID CapsUpdateInventoryItemAsset(UUID avatarId, UUID itemID, byte[] data)
{
ScenePresence avatar;
if (TryGetScenePresence(avatarId, out avatar))
{
IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
if (invAccess != null)
return invAccess.CapsUpdateInventoryItemAsset(avatar.ControllingClient, itemID, data);
}
else
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: " +
"Avatar {0} cannot be found to update its inventory item asset",
avatarId);
}
return UUID.Zero;
}
/// <summary>
/// Capability originating call to update the asset of a script in a prim's (task's) inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="primID">The prim which contains the item to update</param>
/// <param name="isScriptRunning">Indicates whether the script to update is currently running</param>
/// <param name="data"></param>
public ArrayList CapsUpdateTaskInventoryScriptAsset(IClientAPI remoteClient, UUID itemId,
UUID primId, bool isScriptRunning, byte[] data)
{
if (!Permissions.CanEditScript(itemId, primId, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
return new ArrayList();
}
// Retrieve group
SceneObjectPart part = GetSceneObjectPart(primId);
if (part == null)
return new ArrayList();
SceneObjectGroup group = part.ParentGroup;
// Retrieve item
TaskInventoryItem item = group.GetInventoryItem(part.LocalId, itemId);
if (null == item)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for caps script update "
+ " but the item does not exist in this inventory",
itemId, part.Name, part.UUID);
return new ArrayList();
}
AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)AssetType.LSLText, data, remoteClient.AgentId);
AssetService.Store(asset);
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Stored asset {0} when updating item {1} in prim {2} for {3}",
// asset.ID, item.Name, part.Name, remoteClient.Name);
if (isScriptRunning)
{
part.Inventory.RemoveScriptInstance(item.ItemID, false);
}
// Update item with new asset
item.AssetID = asset.FullID;
if (group.UpdateInventoryItem(item))
remoteClient.SendAlertMessage("Script saved");
part.SendPropertiesToClient(remoteClient);
// Trigger rerunning of script (use TriggerRezScript event, see RezScript)
ArrayList errors = new ArrayList();
if (isScriptRunning)
{
// Needs to determine which engine was running it and use that
//
part.Inventory.CreateScriptInstance(item.ItemID, 0, false, DefaultScriptEngine, 0);
errors = part.Inventory.GetScriptErrors(item.ItemID);
}
else
{
remoteClient.SendAlertMessage("Script saved");
}
// Tell anyone managing scripts that a script has been reloaded/changed
EventManager.TriggerUpdateScript(remoteClient.AgentId, itemId, primId, isScriptRunning, item.AssetID);
part.ParentGroup.ResumeScripts();
return errors;
}
/// <summary>
/// <see>CapsUpdateTaskInventoryScriptAsset(IClientAPI, UUID, UUID, bool, byte[])</see>
/// </summary>
public ArrayList CapsUpdateTaskInventoryScriptAsset(UUID avatarId, UUID itemId,
UUID primId, bool isScriptRunning, byte[] data)
{
ScenePresence avatar;
if (TryGetScenePresence(avatarId, out avatar))
{
return CapsUpdateTaskInventoryScriptAsset(
avatar.ControllingClient, itemId, primId, isScriptRunning, data);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Avatar {0} cannot be found to update its prim item asset",
avatarId);
return new ArrayList();
}
}
/// <summary>
/// Update an item which is either already in the client's inventory or is within
/// a transaction
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID">The transaction ID. If this is UUID.Zero we will
/// assume that we are not in a transaction</param>
/// <param name="itemID">The ID of the updated item</param>
/// <param name="name">The name of the updated item</param>
/// <param name="description">The description of the updated item</param>
/// <param name="nextOwnerMask">The permissions of the updated item</param>
/* public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID,
UUID itemID, string name, string description,
uint nextOwnerMask)*/
public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID,
UUID itemID, InventoryItemBase itemUpd)
{
// m_log.DebugFormat(
// "[USER INVENTORY]: Updating asset for item {0} {1}, transaction ID {2} for {3}",
// itemID, itemUpd.Name, transactionID, remoteClient.Name);
// This one will let people set next perms on items in agent
// inventory. Rut-Roh. Whatever. Make this secure. Yeah.
//
// Passing something to another avatar or a an object will already
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null)
{
if (item.Owner != remoteClient.AgentId)
return;
item.Name = itemUpd.Name;
item.Description = itemUpd.Description;
// m_log.DebugFormat(
// "[USER INVENTORY]: itemUpd {0} {1} {2} {3}, item {4} {5} {6} {7}",
// itemUpd.NextPermissions, itemUpd.GroupPermissions, itemUpd.EveryOnePermissions, item.Flags,
// item.NextPermissions, item.GroupPermissions, item.EveryOnePermissions, item.CurrentPermissions);
bool sendUpdate = false;
if (itemUpd.NextPermissions != 0) // Use this to determine validity. Can never be 0 if valid
{
// Create a set of base permissions that will not include export if the user
// is not allowed to change the export flag.
bool denyExportChange = false;
// m_log.DebugFormat("[XXX]: B: {0} O: {1} E: {2}", itemUpd.BasePermissions, itemUpd.CurrentPermissions, itemUpd.EveryOnePermissions);
// If the user is not the creator or doesn't have "E" in both "B" and "O", deny setting export
if ((item.BasePermissions & (uint)(PermissionMask.All | PermissionMask.Export)) != (uint)(PermissionMask.All | PermissionMask.Export) || (item.CurrentPermissions & (uint)PermissionMask.Export) == 0 || item.CreatorIdAsUuid != item.Owner)
denyExportChange = true;
// m_log.DebugFormat("[XXX]: Deny Export Update {0}", denyExportChange);
// If it is already set, force it set and also force full perm
// else prevent setting it. It can and should never be set unless
// set in base, so the condition above is valid
if (denyExportChange)
{
// If we are not allowed to change it, then force it to the
// original item's setting and if it was on, also force full perm
if ((item.EveryOnePermissions & (uint)PermissionMask.Export) != 0)
{
itemUpd.NextPermissions = (uint)(PermissionMask.All);
itemUpd.EveryOnePermissions |= (uint)PermissionMask.Export;
}
else
{
itemUpd.EveryOnePermissions &= ~(uint)PermissionMask.Export;
}
}
else
{
// If the new state is exportable, force full perm
if ((itemUpd.EveryOnePermissions & (uint)PermissionMask.Export) != 0)
{
// m_log.DebugFormat("[XXX]: Force full perm");
itemUpd.NextPermissions = (uint)(PermissionMask.All);
}
}
if (item.NextPermissions != (itemUpd.NextPermissions & item.BasePermissions))
item.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
item.NextPermissions = itemUpd.NextPermissions & item.BasePermissions;
if (item.EveryOnePermissions != (itemUpd.EveryOnePermissions & item.BasePermissions))
item.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
item.EveryOnePermissions = itemUpd.EveryOnePermissions & item.BasePermissions;
if (item.GroupPermissions != (itemUpd.GroupPermissions & item.BasePermissions))
item.Flags |= (uint)InventoryItemFlags.ObjectOverwriteGroup;
item.GroupPermissions = itemUpd.GroupPermissions & item.BasePermissions;
item.GroupID = itemUpd.GroupID;
item.GroupOwned = itemUpd.GroupOwned;
item.CreationDate = itemUpd.CreationDate;
// The client sends zero if its newly created?
if (itemUpd.CreationDate == 0)
item.CreationDate = Util.UnixTimeSinceEpoch();
else
item.CreationDate = itemUpd.CreationDate;
// TODO: Check if folder changed and move item
//item.NextPermissions = itemUpd.Folder;
item.InvType = itemUpd.InvType;
if (item.SalePrice != itemUpd.SalePrice ||
item.SaleType != itemUpd.SaleType)
item.Flags |= (uint)InventoryItemFlags.ObjectSlamSale;
item.SalePrice = itemUpd.SalePrice;
item.SaleType = itemUpd.SaleType;
if (item.InvType == (int)InventoryType.Wearable && (item.Flags & 0xf) == 0 && (itemUpd.Flags & 0xf) != 0)
{
item.Flags = (uint)(item.Flags & 0xfffffff0) | (itemUpd.Flags & 0xf);
sendUpdate = true;
}
InventoryService.UpdateItem(item);
}
if (UUID.Zero != transactionID)
{
if (AgentTransactionsModule != null)
{
AgentTransactionsModule.HandleItemUpdateFromTransaction(remoteClient, transactionID, item);
}
}
else
{
// This MAY be problematic, if it is, another solution
// needs to be found. If inventory item flags are updated
// the viewer's notion of the item needs to be refreshed.
//
// In other situations we cannot send out a bulk update here, since this will cause editing of clothing to start
// failing frequently. Possibly this is a race with a separate transaction that uploads the asset.
if (sendUpdate)
remoteClient.SendBulkUpdateInventory(item);
}
}
else
{
m_log.ErrorFormat(
"[AGENTINVENTORY]: Item id {0} not found for an inventory item update for {1}.",
itemID, remoteClient.Name);
}
}
/// <summary>
/// Give an inventory item from one user to another
/// </summary>
/// <param name="recipientClient"></param>
/// <param name="senderId">ID of the sender of the item</param>
/// <param name="itemId"></param>
public virtual void GiveInventoryItem(IClientAPI recipientClient, UUID senderId, UUID itemId, out string message)
{
InventoryItemBase itemCopy = GiveInventoryItem(recipientClient.AgentId, senderId, itemId, out message);
if (itemCopy != null)
recipientClient.SendBulkUpdateInventory(itemCopy);
}
/// <summary>
/// Give an inventory item from one user to another
/// </summary>
/// <param name="recipient"></param>
/// <param name="senderId">ID of the sender of the item</param>
/// <param name="itemId"></param>
/// <returns>The inventory item copy given, null if the give was unsuccessful</returns>
public virtual InventoryItemBase GiveInventoryItem(UUID recipient, UUID senderId, UUID itemId, out string message)
{
return GiveInventoryItem(recipient, senderId, itemId, UUID.Zero, out message);
}
/// <summary>
/// Give an inventory item from one user to another
/// </summary>
/// <param name="recipient"></param>
/// <param name="senderId">ID of the sender of the item</param>
/// <param name="itemId"></param>
/// <param name="recipientFolderId">
/// The id of the folder in which the copy item should go. If UUID.Zero then the item is placed in the most
/// appropriate default folder.
/// </param>
/// <returns>
/// The inventory item copy given, null if the give was unsuccessful
/// </returns>
public virtual InventoryItemBase GiveInventoryItem(
UUID recipient, UUID senderId, UUID itemId, UUID recipientFolderId, out string message)
{
//Console.WriteLine("Scene.Inventory.cs: GiveInventoryItem");
if (!Permissions.CanTransferUserInventory(itemId, senderId, recipient))
{
message = "Not allowed to transfer this item.";
return null;
}
InventoryItemBase item = new InventoryItemBase(itemId, senderId);
item = InventoryService.GetItem(item);
if (item == null)
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Failed to find item {0} sent by {1} to {2}", itemId, senderId, recipient);
message = string.Format("Item not found: {0}.", itemId);
return null;
}
if (item.Owner != senderId)
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Attempt to send item {0} {1} to {2} failed because sender {3} did not match item owner {4}",
item.Name, item.ID, recipient, senderId, item.Owner);
message = "Sender did not match item owner.";
return null;
}
IUserManagement uman = RequestModuleInterface<IUserManagement>();
if (uman != null)
uman.AddUser(item.CreatorIdAsUuid, item.CreatorData);
if (!Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
{
message = "Item doesn't have the Transfer permission.";
return null;
}
}
// Insert a copy of the item into the recipient
InventoryItemBase itemCopy = new InventoryItemBase();
itemCopy.Owner = recipient;
itemCopy.CreatorId = item.CreatorId;
itemCopy.CreatorData = item.CreatorData;
itemCopy.ID = UUID.Random();
itemCopy.AssetID = item.AssetID;
itemCopy.Description = item.Description;
itemCopy.Name = item.Name;
itemCopy.AssetType = item.AssetType;
itemCopy.InvType = item.InvType;
itemCopy.Folder = recipientFolderId;
if (Permissions.PropagatePermissions() && recipient != senderId)
{
// Trying to do this right this time. This is evil. If
// you believe in Good, go elsewhere. Vampires and other
// evil creatores only beyond this point. You have been
// warned.
// We're going to mask a lot of things by the next perms
// Tweak the next perms to be nicer to our data
//
// In this mask, all the bits we do NOT want to mess
// with are set. These are:
//
// Transfer
// Copy
// Modufy
uint permsMask = ~ ((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify);
// Now, reduce the next perms to the mask bits
// relevant to the operation
uint nextPerms = permsMask | (item.NextPermissions &
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify));
// nextPerms now has all bits set, except for the actual
// next permission bits.
// This checks for no mod, no copy, no trans.
// This indicates an error or messed up item. Do it like
// SL and assume trans
if (nextPerms == permsMask)
nextPerms |= (uint)PermissionMask.Transfer;
// Inventory owner perms are the logical AND of the
// folded perms and the root prim perms, however, if
// the root prim is mod, the inventory perms will be
// mod. This happens on "take" and is of little concern
// here, save for preventing escalation
// This hack ensures that items previously permalocked
// get unlocked when they're passed or rezzed
uint basePerms = item.BasePermissions |
(uint)PermissionMask.Move;
uint ownerPerms = item.CurrentPermissions;
// If this is an object, root prim perms may be more
// permissive than folded perms. Use folded perms as
// a mask
if (item.InvType == (int)InventoryType.Object)
{
bool isRootMod = (item.CurrentPermissions &
(uint)PermissionMask.Modify) != 0 ?
true : false;
// Mask the owner perms to the folded perms
PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref ownerPerms);
PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref basePerms);
// If the root was mod, let the mask reflect that
// We also need to adjust the base here, because
// we should be able to edit in-inventory perms
// for the root prim, if it's mod.
if (isRootMod)
{
ownerPerms |= (uint)PermissionMask.Modify;
basePerms |= (uint)PermissionMask.Modify;
}
}
// These will be applied to the root prim at next rez.
// The slam bit (bit 3) and folded permission (bits 0-2)
// are preserved due to the above mangling
ownerPerms &= nextPerms;
// Mask the base permissions. This is a conservative
// approach altering only the three main perms
basePerms &= nextPerms;
// Assign to the actual item. Make sure the slam bit is
// set, if it wasn't set before.
itemCopy.BasePermissions = basePerms;
itemCopy.CurrentPermissions = ownerPerms;
itemCopy.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
itemCopy.NextPermissions = item.NextPermissions;
// This preserves "everyone can move"
itemCopy.EveryOnePermissions = item.EveryOnePermissions &
nextPerms;
// Intentionally killing "share with group" here, as
// the recipient will not have the group this is
// set to
itemCopy.GroupPermissions = 0;
}
else
{
itemCopy.CurrentPermissions = item.CurrentPermissions;
itemCopy.NextPermissions = item.NextPermissions;
itemCopy.EveryOnePermissions = item.EveryOnePermissions & item.NextPermissions;
itemCopy.GroupPermissions = item.GroupPermissions & item.NextPermissions;
itemCopy.BasePermissions = item.BasePermissions;
}
if (itemCopy.Folder == UUID.Zero)
{
InventoryFolderBase folder = InventoryService.GetFolderForType(recipient, (AssetType)itemCopy.AssetType);
if (folder != null)
{
itemCopy.Folder = folder.ID;
}
else
{
InventoryFolderBase root = InventoryService.GetRootFolder(recipient);
if (root != null)
{
itemCopy.Folder = root.ID;
}
else
{
message = "Can't find a folder to add the item to.";
return null;
}
}
}
itemCopy.GroupID = UUID.Zero;
itemCopy.GroupOwned = false;
itemCopy.Flags = item.Flags;
itemCopy.SalePrice = item.SalePrice;
itemCopy.SaleType = item.SaleType;
IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
if (invAccess != null)
invAccess.TransferInventoryAssets(itemCopy, senderId, recipient);
AddInventoryItem(itemCopy, false);
if (!Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
List<UUID> items = new List<UUID>();
items.Add(itemId);
InventoryService.DeleteItems(senderId, items);
}
}
message = null;
return itemCopy;
}
/// <summary>
/// Give an entire inventory folder from one user to another. The entire contents (including all descendent
/// folders) is given.
/// </summary>
/// <param name="recipientId"></param>
/// <param name="senderId">ID of the sender of the item</param>
/// <param name="folderId"></param>
/// <param name="recipientParentFolderId">
/// The id of the receipient folder in which the send folder should be placed. If UUID.Zero then the
/// recipient folder is the root folder
/// </param>
/// <returns>
/// The inventory folder copy given, null if the copy was unsuccessful
/// </returns>
public virtual InventoryFolderBase GiveInventoryFolder(IClientAPI client,
UUID recipientId, UUID senderId, UUID folderId, UUID recipientParentFolderId)
{
//// Retrieve the folder from the sender
InventoryFolderBase folder = InventoryService.GetFolder(new InventoryFolderBase(folderId, senderId));
if (null == folder)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find inventory folder {0} to give", folderId);
return null;
}
if (recipientParentFolderId == UUID.Zero)
{
InventoryFolderBase recipientRootFolder = InventoryService.GetRootFolder(recipientId);
if (recipientRootFolder != null)
recipientParentFolderId = recipientRootFolder.ID;
else
{
m_log.WarnFormat("[AGENT INVENTORY]: Unable to find root folder for receiving agent");
return null;
}
}
UUID newFolderId = UUID.Random();
InventoryFolderBase newFolder
= new InventoryFolderBase(
newFolderId, folder.Name, recipientId, folder.Type, recipientParentFolderId, folder.Version);
InventoryService.AddFolder(newFolder);
// Give all the subfolders
InventoryCollection contents = InventoryService.GetFolderContent(senderId, folderId);
foreach (InventoryFolderBase childFolder in contents.Folders)
{
GiveInventoryFolder(client, recipientId, senderId, childFolder.ID, newFolder.ID);
}
// Give all the items
foreach (InventoryItemBase item in contents.Items)
{
string message;
if (GiveInventoryItem(recipientId, senderId, item.ID, newFolder.ID, out message) == null)
{
if (client != null)
client.SendAgentAlertMessage(message, false);
}
}
return newFolder;
}
public void CopyInventoryItem(IClientAPI remoteClient, uint callbackID, UUID oldAgentID, UUID oldItemID,
UUID newFolderID, string newName)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: CopyInventoryItem received by {0} with oldAgentID {1}, oldItemID {2}, new FolderID {3}, newName {4}",
remoteClient.AgentId, oldAgentID, oldItemID, newFolderID, newName);
InventoryItemBase item = null;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
item = LibraryService.LibraryRootFolder.FindItem(oldItemID);
if (item == null)
{
item = new InventoryItemBase(oldItemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item == null)
{
m_log.Error("[AGENT INVENTORY]: Failed to find item " + oldItemID.ToString());
return;
}
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
return;
}
if (newName == String.Empty)
newName = item.Name;
if (remoteClient.AgentId == oldAgentID
|| (LibraryService != null
&& LibraryService.LibraryRootFolder != null
&& oldAgentID == LibraryService.LibraryRootFolder.Owner))
{
CreateNewInventoryItem(
remoteClient, item.CreatorId, item.CreatorData, newFolderID,
newName, item.Description, item.Flags, callbackID, item.AssetID, (sbyte)item.AssetType, (sbyte)item.InvType,
item.BasePermissions, item.CurrentPermissions, item.EveryOnePermissions,
item.NextPermissions, item.GroupPermissions, Util.UnixTimeSinceEpoch(), false);
}
else
{
// If item is transfer or permissions are off or calling agent is allowed to copy item owner's inventory item.
if (((item.CurrentPermissions & (uint)PermissionMask.Transfer) != 0)
&& (m_permissions.BypassPermissions()
|| m_permissions.CanCopyUserInventory(remoteClient.AgentId, oldItemID)))
{
CreateNewInventoryItem(
remoteClient, item.CreatorId, item.CreatorData, newFolderID, newName, item.Description, item.Flags, callbackID,
item.AssetID, (sbyte)item.AssetType, (sbyte) item.InvType,
item.NextPermissions, item.NextPermissions, item.EveryOnePermissions & item.NextPermissions,
item.NextPermissions, item.GroupPermissions, Util.UnixTimeSinceEpoch(), false);
}
}
}
/// <summary>
/// Create a new asset data structure.
/// </summary>
public AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, UUID creatorID)
{
AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID.ToString());
asset.Description = description;
asset.Data = (data == null) ? new byte[1] : data;
return asset;
}
/// <summary>
/// Move an item within the agent's inventory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="itemID"></param>
/// <param name="length"></param>
/// <param name="newName"></param>
public void MoveInventoryItem(IClientAPI remoteClient, List<InventoryItemBase> items)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Moving {0} items for user {1}", items.Count, remoteClient.AgentId);
if (!InventoryService.MoveItems(remoteClient.AgentId, items))
m_log.Warn("[AGENT INVENTORY]: Failed to move items for user " + remoteClient.AgentId);
}
/// <summary>
/// Create a new inventory item.
/// </summary>
/// <param name="remoteClient">Client creating this inventory item.</param>
/// <param name="creatorID"></param>
/// <param name="creatorData"></param>
/// <param name="folderID">UUID of folder in which this item should be placed.</param>
/// <param name="name">Item name.</para>
/// <param name="description">Item description.</param>
/// <param name="flags">Item flags</param>
/// <param name="callbackID">Generated by the client.</para>
/// <param name="asset">Asset to which this item refers.</param>
/// <param name="invType">Type of inventory item.</param>
/// <param name="nextOwnerMask">Next owner pemrissions mask.</param>
/// <param name="creationDate">Unix timestamp at which this item was created.</param>
public void CreateNewInventoryItem(
IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
string name, string description, uint flags, uint callbackID,
UUID assetID, sbyte assetType, sbyte invType, uint nextOwnerMask, int creationDate)
{
CreateNewInventoryItem(
remoteClient, creatorID, creatorData, folderID, name, description, flags, callbackID, assetID, assetType, invType,
(uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All | (uint)PermissionMask.Export, 0, nextOwnerMask, 0,
creationDate, true);
}
/// <summary>
/// Create a new Inventory Item
/// </summary>
/// <param name="remoteClient">Client creating this inventory item.</param>
/// <param name="creatorID"></param>
/// <param name="creatorData"></param>
/// <param name="folderID">UUID of folder in which this item should be placed.</param>
/// <param name="name">Item name.</para>
/// <param name="description">Item description.</param>
/// <param name="flags">Item flags</param>
/// <param name="callbackID">Generated by the client.</para>
/// <param name="asset">Asset to which this item refers.</param>
/// <param name="invType">Type of inventory item.</param>
/// <param name="baseMask">Base permissions mask.</param>
/// <param name="currentMask">Current permissions mask.</param>
/// <param name="everyoneMask">Everyone permissions mask.</param>
/// <param name="nextOwnerMask">Next owner pemrissions mask.</param>
/// <param name="groupMask">Group permissions mask.</param>
/// <param name="creationDate">Unix timestamp at which this item was created.</param>
private void CreateNewInventoryItem(
IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
string name, string description, uint flags, uint callbackID, UUID assetID, sbyte assetType, sbyte invType,
uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate,
bool assetUpload)
{
InventoryItemBase item = new InventoryItemBase();
item.Owner = remoteClient.AgentId;
item.CreatorId = creatorID;
item.CreatorData = creatorData;
item.ID = UUID.Random();
item.AssetID = assetID;
item.Name = name;
item.Description = description;
item.Flags = flags;
item.AssetType = assetType;
item.InvType = invType;
item.Folder = folderID;
item.CurrentPermissions = currentMask;
item.NextPermissions = nextOwnerMask;
item.EveryOnePermissions = everyoneMask;
item.GroupPermissions = groupMask;
item.BasePermissions = baseMask;
item.CreationDate = creationDate;
if (AddInventoryItem(item, assetUpload))
{
remoteClient.SendInventoryItemCreateUpdate(item, callbackID);
}
else
{
m_dialogModule.SendAlertToUser(remoteClient, "Failed to create item");
m_log.WarnFormat(
"Failed to add item for {0} in CreateNewInventoryItem!",
remoteClient.Name);
}
}
/// <summary>
/// Link an inventory item to an existing item.
/// </summary>
/// <remarks>
/// The linkee item id is placed in the asset id slot. This appears to be what the viewer expects when
/// it receives inventory information.
/// </remarks>
/// <param name="remoteClient"></param>
/// <param name="transActionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type">/param>
/// <param name="olditemID"></param>
private void HandleLinkInventoryItem(IClientAPI remoteClient, UUID transActionID, UUID folderID,
uint callbackID, string description, string name,
sbyte invType, sbyte type, UUID olditemID)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Received request from {0} to create inventory item link {1} in folder {2} pointing to {3}, assetType {4}, inventoryType {5}",
// remoteClient.Name, name, folderID, olditemID, (AssetType)type, (InventoryType)invType);
if (!Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
return;
ScenePresence presence;
if (TryGetScenePresence(remoteClient.AgentId, out presence))
{
// Disabled the check for duplicate links.
//
// When outfits are being adjusted, the viewer rapidly sends delete link messages followed by
// create links. However, since these are handled asynchronously, the deletes do not complete before
// the creates are handled. Therefore, we cannot enforce a duplicate link check.
// InventoryItemBase existingLink = null;
// List<InventoryItemBase> existingItems = InventoryService.GetFolderItems(remoteClient.AgentId, folderID);
// foreach (InventoryItemBase item in existingItems)
// if (item.AssetID == olditemID)
// existingLink = item;
//
// if (existingLink != null)
// {
// m_log.WarnFormat(
// "[AGENT INVENTORY]: Ignoring request from {0} to create item link {1} in folder {2} pointing to {3} since a link named {4} with id {5} already exists",
// remoteClient.Name, name, folderID, olditemID, existingLink.Name, existingLink.ID);
//
// return;
// }
CreateNewInventoryItem(
remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID,
name, description, 0, callbackID, olditemID, type, invType,
(uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All,
(uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All | (uint)PermissionMask.Export, Util.UnixTimeSinceEpoch(),
false);
}
else
{
m_log.ErrorFormat(
"ScenePresence for agent uuid {0} unexpectedly not found in HandleLinkInventoryItem",
remoteClient.AgentId);
}
}
/// <summary>
/// Remove an inventory item for the client's inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
private void RemoveInventoryItem(IClientAPI remoteClient, List<UUID> itemIDs)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Removing inventory items {0} for {1}",
// string.Join(",", itemIDs.ConvertAll<string>(uuid => uuid.ToString()).ToArray()),
// remoteClient.Name);
InventoryService.DeleteItems(remoteClient.AgentId, itemIDs);
}
/// <summary>
/// Removes an inventory folder. This packet is sent when the user
/// right-clicks a folder that's already in trash and chooses "purge"
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
private void RemoveInventoryFolder(IClientAPI remoteClient, List<UUID> folderIDs)
{
m_log.DebugFormat("[SCENE INVENTORY]: RemoveInventoryFolders count {0}", folderIDs.Count);
InventoryService.DeleteFolders(remoteClient.AgentId, folderIDs);
}
/// <summary>
/// Send the details of a prim's inventory to the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="primLocalID"></param>
public void RequestTaskInventory(IClientAPI remoteClient, uint primLocalID)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part == null)
return;
if (XferManager != null)
part.Inventory.RequestInventoryFile(remoteClient, XferManager);
}
/// <summary>
/// Remove an item from a prim (task) inventory
/// </summary>
/// <param name="remoteClient">Unused at the moment but retained since the avatar ID might
/// be necessary for a permissions check at some stage.</param>
/// <param name="itemID"></param>
/// <param name="localID"></param>
public void RemoveTaskInventory(IClientAPI remoteClient, UUID itemID, uint localID)
{
SceneObjectPart part = GetSceneObjectPart(localID);
SceneObjectGroup group = null;
if (part != null)
{
group = part.ParentGroup;
}
if (part != null && group != null)
{
if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
return;
TaskInventoryItem item = group.GetInventoryItem(localID, itemID);
if (item == null)
return;
InventoryFolderBase destFolder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.TrashFolder);
// Move the item to trash. If this is a copyable item, only
// a copy will be moved and we will still need to delete
// the item from the prim. If it was no copy, it will be
// deleted by this method.
string message;
InventoryItemBase item2 = MoveTaskInventoryItem(remoteClient, destFolder.ID, part, itemID, out message);
if (item2 == null)
{
m_log.WarnFormat("[SCENE INVENTORY]: RemoveTaskInventory of item {0} failed: {1}", itemID, message);
remoteClient.SendAgentAlertMessage(message, false);
return;
}
if (group.GetInventoryItem(localID, itemID) != null)
{
if (item.Type == 10)
{
part.RemoveScriptEvents(itemID);
EventManager.TriggerRemoveScript(localID, itemID);
}
group.RemoveInventoryItem(localID, itemID);
}
part.SendPropertiesToClient(remoteClient);
}
}
/// <summary>
/// Creates (in memory only) a user inventory item that will contain a copy of a task inventory item.
/// </summary>
private InventoryItemBase CreateAgentInventoryItemFromTask(UUID destAgent, SceneObjectPart part, UUID itemId, out string message)
{
TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(itemId);
if (null == taskItem)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for creating an avatar"
+ " inventory item from a prim's inventory item "
+ " but the required item does not exist in the prim's inventory",
itemId, part.Name, part.UUID);
message = "Item not found: " + itemId;
return null;
}
if ((destAgent != taskItem.OwnerID) && ((taskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0))
{
message = "Item doesn't have the Transfer permission.";
return null;
}
InventoryItemBase agentItem = new InventoryItemBase();
agentItem.ID = UUID.Random();
agentItem.CreatorId = taskItem.CreatorID.ToString();
agentItem.CreatorData = taskItem.CreatorData;
agentItem.Owner = destAgent;
agentItem.AssetID = taskItem.AssetID;
agentItem.Description = taskItem.Description;
agentItem.Name = taskItem.Name;
agentItem.AssetType = taskItem.Type;
agentItem.InvType = taskItem.InvType;
agentItem.Flags = taskItem.Flags;
if ((part.OwnerID != destAgent) && Permissions.PropagatePermissions())
{
agentItem.BasePermissions = taskItem.BasePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
if (taskItem.InvType == (int)InventoryType.Object)
{
// Bake the new base permissions from folded permissions
// The folded perms are in the lowest 3 bits of the current perms
// We use base permissions here to avoid baking the "Locked" status
// into the item as it is passed.
uint perms = taskItem.BasePermissions & taskItem.NextPermissions;
PermissionsUtil.ApplyFoldedPermissions(taskItem.CurrentPermissions, ref perms);
// Avoid the "lock trap" - move must always be enabled but the above may remove it
// Add it back here.
agentItem.BasePermissions = perms | (uint)PermissionMask.Move;
// Newly given items cannot be "locked" on rez. Make sure by
// setting current equal to base.
}
agentItem.CurrentPermissions = agentItem.BasePermissions;
agentItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
agentItem.NextPermissions = taskItem.NextPermissions;
agentItem.EveryOnePermissions = taskItem.EveryonePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
agentItem.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions;
}
else
{
agentItem.BasePermissions = taskItem.BasePermissions;
agentItem.CurrentPermissions = taskItem.CurrentPermissions;
agentItem.NextPermissions = taskItem.NextPermissions;
agentItem.EveryOnePermissions = taskItem.EveryonePermissions;
agentItem.GroupPermissions = taskItem.GroupPermissions;
}
message = null;
return agentItem;
}
/// <summary>
/// If the task item is not-copyable then remove it from the prim.
/// </summary>
private void RemoveNonCopyTaskItemFromPrim(SceneObjectPart part, UUID itemId)
{
TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(itemId);
if (taskItem == null)
return;
if (!Permissions.BypassPermissions())
{
if ((taskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
if (taskItem.Type == (int)AssetType.LSLText)
{
part.RemoveScriptEvents(itemId);
EventManager.TriggerRemoveScript(part.LocalId, itemId);
}
part.Inventory.RemoveInventoryItem(itemId);
}
}
}
/// <summary>
/// Move the given item in the given prim to a folder in the client's inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="part"></param>
/// <param name="itemID"></param>
public InventoryItemBase MoveTaskInventoryItem(IClientAPI remoteClient, UUID folderId, SceneObjectPart part, UUID itemId, out string message)
{
m_log.DebugFormat(
"[PRIM INVENTORY]: Adding item {0} from {1} to folder {2} for {3}",
itemId, part.Name, folderId, remoteClient.Name);
InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(remoteClient.AgentId, part, itemId, out message);
if (agentItem == null)
return null;
agentItem.Folder = folderId;
AddInventoryItem(remoteClient, agentItem);
RemoveNonCopyTaskItemFromPrim(part, itemId);
message = null;
return agentItem;
}
/// <summary>
/// <see>ClientMoveTaskInventoryItem</see>
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="primLocalID"></param>
/// <param name="itemID"></param>
public void ClientMoveTaskInventoryItem(IClientAPI remoteClient, UUID folderId, uint primLocalId, UUID itemId)
{
SceneObjectPart part = GetSceneObjectPart(primLocalId);
if (null == part)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Move of inventory item {0} from prim with local id {1} failed because the prim could not be found",
itemId, primLocalId);
return;
}
TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(itemId);
if (null == taskItem)
{
m_log.WarnFormat("[PRIM INVENTORY]: Move of inventory item {0} from prim with local id {1} failed"
+ " because the inventory item could not be found",
itemId, primLocalId);
return;
}
if ((taskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
// If the item to be moved is no copy, we need to be able to
// edit the prim.
if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
return;
}
else
{
// If the item is copiable, then we just need to have perms
// on it. The delete check is a pure rights check
if (!Permissions.CanDeleteObject(part.UUID, remoteClient.AgentId))
return;
}
string message;
InventoryItemBase item = MoveTaskInventoryItem(remoteClient, folderId, part, itemId, out message);
if (item == null)
remoteClient.SendAgentAlertMessage(message, false);
}
/// <summary>
/// <see>MoveTaskInventoryItem</see>
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID">
/// The user inventory folder to move (or copy) the item to. If null, then the most
/// suitable system folder is used (e.g. the Objects folder for objects). If there is no suitable folder, then
/// the item is placed in the user's root inventory folder
/// </param>
/// <param name="part"></param>
/// <param name="itemID"></param>
public InventoryItemBase MoveTaskInventoryItem(UUID avatarId, UUID folderId, SceneObjectPart part, UUID itemId, out string message)
{
ScenePresence avatar;
if (TryGetScenePresence(avatarId, out avatar))
{
return MoveTaskInventoryItem(avatar.ControllingClient, folderId, part, itemId, out message);
}
else
{
InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(avatarId, part, itemId, out message);
if (agentItem == null)
return null;
agentItem.Folder = folderId;
AddInventoryItem(agentItem);
RemoveNonCopyTaskItemFromPrim(part, itemId);
return agentItem;
}
}
/// <summary>
/// Copy a task (prim) inventory item to another task (prim)
/// </summary>
/// <param name="destId">ID of destination part</param>
/// <param name="part">Source part</param>
/// <param name="itemId">Source item id to transfer</param>
public void MoveTaskInventoryItem(UUID destId, SceneObjectPart part, UUID itemId)
{
TaskInventoryItem srcTaskItem = part.Inventory.GetInventoryItem(itemId);
if (srcTaskItem == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for moving"
+ " but the item does not exist in this inventory",
itemId, part.Name, part.UUID);
return;
}
SceneObjectPart destPart = GetSceneObjectPart(destId);
if (destPart == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Could not find prim for ID {0}",
destId);
return;
}
if (part.OwnerID != destPart.OwnerID)
{
// Source must have transfer permissions
if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
return;
// Object cannot copy items to an object owned by a different owner
// unless llAllowInventoryDrop has been called on the destination
if ((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
return;
}
// must have both move and modify permission to put an item in an object
if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0)
return;
TaskInventoryItem destTaskItem = new TaskInventoryItem();
destTaskItem.ItemID = UUID.Random();
destTaskItem.CreatorID = srcTaskItem.CreatorID;
destTaskItem.CreatorData = srcTaskItem.CreatorData;
destTaskItem.AssetID = srcTaskItem.AssetID;
destTaskItem.GroupID = destPart.GroupID;
destTaskItem.OwnerID = destPart.OwnerID;
destTaskItem.ParentID = destPart.UUID;
destTaskItem.ParentPartID = destPart.UUID;
destTaskItem.BasePermissions = srcTaskItem.BasePermissions;
destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions;
destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions;
destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions;
destTaskItem.NextPermissions = srcTaskItem.NextPermissions;
destTaskItem.Flags = srcTaskItem.Flags;
if (destPart.OwnerID != part.OwnerID)
{
if (Permissions.PropagatePermissions())
{
destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions &
(srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions &
(srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions &
(srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.BasePermissions = srcTaskItem.BasePermissions &
(srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
}
}
destTaskItem.Description = srcTaskItem.Description;
destTaskItem.Name = srcTaskItem.Name;
destTaskItem.InvType = srcTaskItem.InvType;
destTaskItem.Type = srcTaskItem.Type;
destPart.Inventory.AddInventoryItem(destTaskItem, part.OwnerID != destPart.OwnerID);
if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
part.Inventory.RemoveInventoryItem(itemId);
ScenePresence avatar;
if (TryGetScenePresence(srcTaskItem.OwnerID, out avatar))
{
destPart.SendPropertiesToClient(avatar.ControllingClient);
}
}
public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items)
{
ScenePresence avatar;
IClientAPI remoteClient = null;
if (TryGetScenePresence(destID, out avatar))
remoteClient = avatar.ControllingClient;
InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID);
UUID newFolderID = UUID.Random();
InventoryFolderBase newFolder = new InventoryFolderBase(newFolderID, category, destID, -1, rootFolder.ID, rootFolder.Version);
InventoryService.AddFolder(newFolder);
foreach (UUID itemID in items)
{
string message;
InventoryItemBase agentItem = CreateAgentInventoryItemFromTask(destID, host, itemID, out message);
if (agentItem != null)
{
agentItem.Folder = newFolderID;
AddInventoryItem(agentItem);
RemoveNonCopyTaskItemFromPrim(host, itemID);
}
else
{
if (remoteClient != null)
remoteClient.SendAgentAlertMessage(message, false);
}
}
if (remoteClient != null)
{
SendInventoryUpdate(remoteClient, rootFolder, true, false);
SendInventoryUpdate(remoteClient, newFolder, false, true);
}
return newFolderID;
}
public void SendInventoryUpdate(IClientAPI client, InventoryFolderBase folder, bool fetchFolders, bool fetchItems)
{
if (folder == null)
return;
// TODO: This code for looking in the folder for the library should be folded somewhere else
// so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold = null;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
{
if ((fold = LibraryService.LibraryRootFolder.FindFolder(folder.ID)) != null)
{
client.SendInventoryFolderDetails(
fold.Owner, folder.ID, fold.RequestListOfItems(),
fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
return;
}
}
// Fetch the folder contents
InventoryCollection contents = InventoryService.GetFolderContent(client.AgentId, folder.ID);
// Fetch the folder itself to get its current version
InventoryFolderBase containingFolder = new InventoryFolderBase(folder.ID, client.AgentId);
containingFolder = InventoryService.GetFolder(containingFolder);
// m_log.DebugFormat("[AGENT INVENTORY]: Sending inventory folder contents ({0} nodes) for \"{1}\" to {2} {3}",
// contents.Folders.Count + contents.Items.Count, containingFolder.Name, client.FirstName, client.LastName);
if (containingFolder != null)
{
// If the folder requested contains links, then we need to send those folders first, otherwise the links
// will be broken in the viewer.
HashSet<UUID> linkedItemFolderIdsToSend = new HashSet<UUID>();
foreach (InventoryItemBase item in contents.Items)
{
if (item.AssetType == (int)AssetType.Link)
{
InventoryItemBase linkedItem = InventoryService.GetItem(new InventoryItemBase(item.AssetID));
// Take care of genuinely broken links where the target doesn't exist
// HACK: Also, don't follow up links that just point to other links. In theory this is legitimate,
// but no viewer has been observed to set these up and this is the lazy way of avoiding cycles
// rather than having to keep track of every folder requested in the recursion.
if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link)
{
// We don't need to send the folder if source and destination of the link are in the same
// folder.
if (linkedItem.Folder != containingFolder.ID)
linkedItemFolderIdsToSend.Add(linkedItem.Folder);
}
}
}
foreach (UUID linkedItemFolderId in linkedItemFolderIdsToSend)
SendInventoryUpdate(client, new InventoryFolderBase(linkedItemFolderId), false, true);
client.SendInventoryFolderDetails(
client.AgentId, folder.ID, contents.Items, contents.Folders,
containingFolder.Version, fetchFolders, fetchItems);
}
}
/// <summary>
/// Update an item in a prim (task) inventory.
/// This method does not handle scripts, <see>RezScript(IClientAPI, UUID, unit)</see>
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="itemInfo"></param>
/// <param name="primLocalID"></param>
public void UpdateTaskInventory(IClientAPI remoteClient, UUID transactionID, TaskInventoryItem itemInfo,
uint primLocalID)
{
UUID itemID = itemInfo.ItemID;
// Find the prim we're dealing with
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part != null)
{
TaskInventoryItem currentItem = part.Inventory.GetInventoryItem(itemID);
bool allowInventoryDrop = (part.GetEffectiveObjectFlags()
& (uint)PrimFlags.AllowInventoryDrop) != 0;
// Explicity allow anyone to add to the inventory if the
// AllowInventoryDrop flag has been set. Don't however let
// them update an item unless they pass the external checks
//
if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId)
&& (currentItem != null || !allowInventoryDrop))
return;
if (currentItem == null)
{
UUID copyID = UUID.Random();
if (itemID != UUID.Zero)
{
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
// Try library
if (null == item && LibraryService != null && LibraryService.LibraryRootFolder != null)
{
item = LibraryService.LibraryRootFolder.FindItem(itemID);
}
// If we've found the item in the user's inventory or in the library
if (item != null)
{
part.ParentGroup.AddInventoryItem(remoteClient.AgentId, primLocalID, item, copyID);
m_log.InfoFormat(
"[PRIM INVENTORY]: Update with item {0} requested of prim {1} for {2}",
item.Name, primLocalID, remoteClient.Name);
part.SendPropertiesToClient(remoteClient);
if (!Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
List<UUID> uuids = new List<UUID>();
uuids.Add(itemID);
RemoveInventoryItem(remoteClient, uuids);
}
}
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Could not find inventory item {0} to update for {1}!",
itemID, remoteClient.Name);
}
}
}
else // Updating existing item with new perms etc
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Updating item {0} in {1} for UpdateTaskInventory()",
// currentItem.Name, part.Name);
// Only look for an uploaded updated asset if we are passed a transaction ID. This is only the
// case for updates uploded through UDP. Updates uploaded via a capability (e.g. a script update)
// will not pass in a transaction ID in the update message.
if (transactionID != UUID.Zero && AgentTransactionsModule != null)
{
AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
remoteClient, part, transactionID, currentItem);
if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
remoteClient.SendAlertMessage("Notecard saved");
else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
remoteClient.SendAlertMessage("Script saved");
else
remoteClient.SendAlertMessage("Item saved");
}
// Base ALWAYS has move
currentItem.BasePermissions |= (uint)PermissionMask.Move;
itemInfo.Flags = currentItem.Flags;
// Check if we're allowed to mess with permissions
if (!Permissions.IsGod(remoteClient.AgentId)) // Not a god
{
if (remoteClient.AgentId != part.OwnerID) // Not owner
{
// Friends and group members can't change any perms
itemInfo.BasePermissions = currentItem.BasePermissions;
itemInfo.EveryonePermissions = currentItem.EveryonePermissions;
itemInfo.GroupPermissions = currentItem.GroupPermissions;
itemInfo.NextPermissions = currentItem.NextPermissions;
itemInfo.CurrentPermissions = currentItem.CurrentPermissions;
}
else
{
// Owner can't change base, and can change other
// only up to base
itemInfo.BasePermissions = currentItem.BasePermissions;
if (itemInfo.EveryonePermissions != currentItem.EveryonePermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
if (itemInfo.GroupPermissions != currentItem.GroupPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteGroup;
if (itemInfo.CurrentPermissions != currentItem.CurrentPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteOwner;
if (itemInfo.NextPermissions != currentItem.NextPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
itemInfo.EveryonePermissions &= currentItem.BasePermissions;
itemInfo.GroupPermissions &= currentItem.BasePermissions;
itemInfo.CurrentPermissions &= currentItem.BasePermissions;
itemInfo.NextPermissions &= currentItem.BasePermissions;
}
}
else
{
if (itemInfo.BasePermissions != currentItem.BasePermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteBase;
if (itemInfo.EveryonePermissions != currentItem.EveryonePermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
if (itemInfo.GroupPermissions != currentItem.GroupPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteGroup;
if (itemInfo.CurrentPermissions != currentItem.CurrentPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteOwner;
if (itemInfo.NextPermissions != currentItem.NextPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
}
// Next ALWAYS has move
itemInfo.NextPermissions |= (uint)PermissionMask.Move;
if (part.Inventory.UpdateInventoryItem(itemInfo))
{
part.SendPropertiesToClient(remoteClient);
}
}
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Update with item {0} requested of prim {1} for {2} but this prim does not exist",
itemID, primLocalID, remoteClient.Name);
}
}
/// <summary>
/// Rez a script into a prim's inventory, either ex nihilo or from an existing avatar inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemBase"> </param>
/// <param name="transactionID"></param>
/// <param name="localID"></param>
public void RezScript(IClientAPI remoteClient, InventoryItemBase itemBase, UUID transactionID, uint localID)
{
SceneObjectPart partWhereRezzed;
if (itemBase.ID != UUID.Zero)
partWhereRezzed = RezScriptFromAgentInventory(remoteClient.AgentId, itemBase.ID, localID);
else
partWhereRezzed = RezNewScript(remoteClient.AgentId, itemBase);
if (partWhereRezzed != null)
partWhereRezzed.SendPropertiesToClient(remoteClient);
}
/// <summary>
/// Rez a script into a prim from an agent inventory.
/// </summary>
/// <param name="agentID"></param>
/// <param name="fromItemID"></param>
/// <param name="localID"></param>
/// <returns>The part where the script was rezzed if successful. False otherwise.</returns>
public SceneObjectPart RezScriptFromAgentInventory(UUID agentID, UUID fromItemID, uint localID)
{
UUID copyID = UUID.Random();
InventoryItemBase item = new InventoryItemBase(fromItemID, agentID);
item = InventoryService.GetItem(item);
// Try library
// XXX clumsy, possibly should be one call
if (null == item && LibraryService != null && LibraryService.LibraryRootFolder != null)
{
item = LibraryService.LibraryRootFolder.FindItem(fromItemID);
}
if (item != null)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part != null)
{
if (!Permissions.CanEditObjectInventory(part.UUID, agentID))
return null;
part.ParentGroup.AddInventoryItem(agentID, localID, item, copyID);
// TODO: switch to posting on_rez here when scripts
// have state in inventory
part.Inventory.CreateScriptInstance(copyID, 0, false, DefaultScriptEngine, 0);
// tell anyone watching that there is a new script in town
EventManager.TriggerNewScript(agentID, part, copyID);
// m_log.InfoFormat("[PRIMINVENTORY]: " +
// "Rezzed script {0} into prim local ID {1} for user {2}",
// item.inventoryName, localID, remoteClient.Name);
part.ParentGroup.ResumeScripts();
return part;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Could not rez script {0} into prim local ID {1} for user {2}"
+ " because the prim could not be found in the region!",
item.Name, localID, agentID);
}
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Could not find script inventory item {0} to rez for {1}!",
fromItemID, agentID);
}
return null;
}
/// <summary>
/// Rez a new script from nothing.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemBase"></param>
/// <returns>The part where the script was rezzed if successful. False otherwise.</returns>
public SceneObjectPart RezNewScript(UUID agentID, InventoryItemBase itemBase)
{
return RezNewScript(
agentID,
itemBase,
"default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n}");
}
/// <summary>
/// Rez a new script from nothing with given script text.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemBase">Template item.</param>
/// <param name="scriptText"></param>
/// <returns>The part where the script was rezzed if successful. False otherwise.</returns>
public SceneObjectPart RezNewScript(UUID agentID, InventoryItemBase itemBase, string scriptText)
{
// The part ID is the folder ID!
SceneObjectPart part = GetSceneObjectPart(itemBase.Folder);
if (part == null)
{
// m_log.DebugFormat(
// "[SCENE INVENTORY]: Could not find part with id {0} for {1} to rez new script",
// itemBase.Folder, agentID);
return null;
}
if (!Permissions.CanCreateObjectInventory(itemBase.InvType, part.UUID, agentID))
{
// m_log.DebugFormat(
// "[SCENE INVENTORY]: No permission to create new script in {0} for {1}", part.Name, agentID);
return null;
}
AssetBase asset
= CreateAsset(
itemBase.Name,
itemBase.Description,
(sbyte)itemBase.AssetType,
Encoding.ASCII.GetBytes(scriptText),
agentID);
AssetService.Store(asset);
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ResetIDs(itemBase.Folder);
taskItem.ParentID = itemBase.Folder;
taskItem.CreationDate = (uint)itemBase.CreationDate;
taskItem.Name = itemBase.Name;
taskItem.Description = itemBase.Description;
taskItem.Type = itemBase.AssetType;
taskItem.InvType = itemBase.InvType;
taskItem.OwnerID = itemBase.Owner;
taskItem.CreatorID = itemBase.CreatorIdAsUuid;
taskItem.BasePermissions = itemBase.BasePermissions;
taskItem.CurrentPermissions = itemBase.CurrentPermissions;
taskItem.EveryonePermissions = itemBase.EveryOnePermissions;
taskItem.GroupPermissions = itemBase.GroupPermissions;
taskItem.NextPermissions = itemBase.NextPermissions;
taskItem.GroupID = itemBase.GroupID;
taskItem.GroupPermissions = 0;
taskItem.Flags = itemBase.Flags;
taskItem.PermsGranter = UUID.Zero;
taskItem.PermsMask = 0;
taskItem.AssetID = asset.FullID;
part.Inventory.AddInventoryItem(taskItem, false);
part.Inventory.CreateScriptInstance(taskItem, 0, false, DefaultScriptEngine, 0);
// tell anyone managing scripts that a new script exists
EventManager.TriggerNewScript(agentID, part, taskItem.ItemID);
part.ParentGroup.ResumeScripts();
return part;
}
/// <summary>
/// Rez a script into a prim's inventory from another prim
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="srcPart"> </param>
/// <param name="destId"> </param>
/// <param name="pin"></param>
/// <param name="running"></param>
/// <param name="start_param"></param>
public void RezScriptFromPrim(UUID srcId, SceneObjectPart srcPart, UUID destId, int pin, int running, int start_param)
{
TaskInventoryItem srcTaskItem = srcPart.Inventory.GetInventoryItem(srcId);
if (srcTaskItem == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for rezzing a script but the "
+ " item does not exist in this inventory",
srcId, srcPart.Name, srcPart.UUID);
return;
}
SceneObjectPart destPart = GetSceneObjectPart(destId);
if (destPart == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Could not find part {0} to insert script item {1} from {2} {3} in {4}",
destId, srcId, srcPart.Name, srcPart.UUID, Name);
return;
}
// Must own the object, and have modify rights
if (srcPart.OwnerID != destPart.OwnerID)
{
// Group permissions
if ((destPart.GroupID == UUID.Zero) || (destPart.GroupID != srcPart.GroupID) ||
((destPart.GroupMask & (uint)PermissionMask.Modify) == 0))
return;
}
else
{
if ((destPart.OwnerMask & (uint)PermissionMask.Modify) == 0)
return;
}
if (destPart.ScriptAccessPin == 0 || destPart.ScriptAccessPin != pin)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Script in object {0} : {1}, attempted to load script {2} : {3} into object {4} : {5} with invalid pin {6}",
srcPart.Name, srcId, srcTaskItem.Name, srcTaskItem.ItemID, destPart.Name, destId, pin);
// the LSL Wiki says we are supposed to shout on the DEBUG_CHANNEL -
// "Object: Task Object trying to illegally load script onto task Other_Object!"
// How do we shout from in here?
return;
}
TaskInventoryItem destTaskItem = new TaskInventoryItem();
destTaskItem.ItemID = UUID.Random();
destTaskItem.CreatorID = srcTaskItem.CreatorID;
destTaskItem.CreatorData = srcTaskItem.CreatorData;
destTaskItem.AssetID = srcTaskItem.AssetID;
destTaskItem.GroupID = destPart.GroupID;
destTaskItem.OwnerID = destPart.OwnerID;
destTaskItem.ParentID = destPart.UUID;
destTaskItem.ParentPartID = destPart.UUID;
destTaskItem.BasePermissions = srcTaskItem.BasePermissions;
destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions;
destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions;
destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions;
destTaskItem.NextPermissions = srcTaskItem.NextPermissions;
destTaskItem.Flags = srcTaskItem.Flags;
if (destPart.OwnerID != srcPart.OwnerID)
{
if (Permissions.PropagatePermissions())
{
destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions &
srcTaskItem.NextPermissions;
destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions &
srcTaskItem.NextPermissions;
destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions &
srcTaskItem.NextPermissions;
destTaskItem.BasePermissions = srcTaskItem.BasePermissions &
srcTaskItem.NextPermissions;
destTaskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
}
}
destTaskItem.Description = srcTaskItem.Description;
destTaskItem.Name = srcTaskItem.Name;
destTaskItem.InvType = srcTaskItem.InvType;
destTaskItem.Type = srcTaskItem.Type;
destPart.Inventory.AddInventoryItemExclusive(destTaskItem, false);
if (running > 0)
{
destPart.Inventory.CreateScriptInstance(destTaskItem, start_param, false, DefaultScriptEngine, 0);
}
destPart.ParentGroup.ResumeScripts();
ScenePresence avatar;
if (TryGetScenePresence(srcTaskItem.OwnerID, out avatar))
{
destPart.SendPropertiesToClient(avatar.ControllingClient);
}
}
/// <summary>
/// Derez one or more objects from the scene.
/// </summary>
/// <remarks>
/// Won't actually remove the scene object in the case where the object is being copied to a user inventory.
/// </remarks>
/// <param name='remoteClient'>Client requesting derez</param>
/// <param name='localIDs'>Local ids of root parts of objects to delete.</param>
/// <param name='groupID'>Not currently used. Here because the client passes this to us.</param>
/// <param name='action'>DeRezAction</param>
/// <param name='destinationID'>User folder ID to place derezzed object</param>
public virtual void DeRezObjects(
IClientAPI remoteClient, List<uint> localIDs, UUID groupID, DeRezAction action, UUID destinationID)
{
// First, see of we can perform the requested action and
// build a list of eligible objects
List<uint> deleteIDs = new List<uint>();
List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>();
// Start with true for both, then remove the flags if objects
// that we can't derez are part of the selection
bool permissionToTake = true;
bool permissionToTakeCopy = true;
bool permissionToDelete = true;
foreach (uint localID in localIDs)
{
// Invalid id
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
continue;
// Already deleted by someone else
if (part.ParentGroup.IsDeleted)
continue;
// Can't delete child prims
if (part != part.ParentGroup.RootPart)
continue;
SceneObjectGroup grp = part.ParentGroup;
deleteIDs.Add(localID);
deleteGroups.Add(grp);
// If child prims have invalid perms, fix them
grp.AdjustChildPrimPermissions(false);
if (remoteClient == null)
{
// Autoreturn has a null client. Nothing else does. So
// allow only returns
if (action != DeRezAction.Return)
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Ignoring attempt to {0} {1} {2} without a client",
action, grp.Name, grp.UUID);
return;
}
permissionToTakeCopy = false;
}
else
{
if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
permissionToTakeCopy = false;
if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
permissionToTake = false;
if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
permissionToDelete = false;
}
}
// Handle god perms
if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
{
permissionToTake = true;
permissionToTakeCopy = true;
permissionToDelete = true;
}
// If we're re-saving, we don't even want to delete
if (action == DeRezAction.SaveToExistingUserInventoryItem)
permissionToDelete = false;
// if we want to take a copy, we also don't want to delete
// Note: after this point, the permissionToTakeCopy flag
// becomes irrelevant. It already includes the permissionToTake
// permission and after excluding no copy items here, we can
// just use that.
if (action == DeRezAction.TakeCopy)
{
// If we don't have permission, stop right here
if (!permissionToTakeCopy)
{
remoteClient.SendAlertMessage("You don't have permission to take the object");
return;
}
permissionToTake = true;
// Don't delete
permissionToDelete = false;
}
if (action == DeRezAction.Return)
{
if (remoteClient != null)
{
if (Permissions.CanReturnObjects(
null,
remoteClient.AgentId,
deleteGroups))
{
permissionToTake = true;
permissionToDelete = true;
foreach (SceneObjectGroup g in deleteGroups)
{
AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return");
}
}
}
else // Auto return passes through here with null agent
{
permissionToTake = true;
permissionToDelete = true;
}
}
// OK, we're done with permissions. Let's check if any part of the code prevents the objects from being deleted
bool canDelete = EventManager.TriggerDeRezRequested(remoteClient, deleteGroups, action);
if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete))
{
m_asyncSceneObjectDeleter.DeleteToInventory(
action, destinationID, deleteGroups, remoteClient,
permissionToDelete && canDelete);
}
else if (permissionToDelete && canDelete)
{
foreach (SceneObjectGroup g in deleteGroups)
DeleteSceneObject(g, false);
}
}
/// <summary>
/// Returns the list of Scene Objects in an asset.
/// </summary>
/// <remarks>
/// Returns one object if the asset is a regular object, and multiple objects for a coalesced object.
/// </remarks>
/// <param name="assetData">Asset data</param>
/// <param name="isAttachment">True if the object is an attachment.</param>
/// <param name="objlist">The objects included in the asset</param>
/// <param name="veclist">Relative positions of the objects</param>
/// <param name="bbox">Bounding box of all the objects</param>
/// <param name="offsetHeight">Offset in the Z axis from the centre of the bounding box
/// to the centre of the root prim (relevant only when returning a single object)</param>
/// <returns>
/// true if returning a single object or deserialization fails, false if returning the coalesced
/// list of objects
/// </returns>
public bool GetObjectsToRez(
byte[] assetData, bool isAttachment, out List<SceneObjectGroup> objlist, out List<Vector3> veclist,
out Vector3 bbox, out float offsetHeight)
{
objlist = new List<SceneObjectGroup>();
veclist = new List<Vector3>();
string xmlData = Utils.BytesToString(assetData);
try
{
using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null))
{
using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }))
{
reader.Read();
bool isSingleObject = reader.Name != "CoalescedObject";
if (isSingleObject || isAttachment)
{
SceneObjectGroup g = SceneObjectSerializer.FromOriginalXmlFormat(reader);
objlist.Add(g);
veclist.Add(Vector3.Zero);
bbox = g.GetAxisAlignedBoundingBox(out offsetHeight);
return true;
}
else
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlElement e = (XmlElement)doc.SelectSingleNode("/CoalescedObject");
XmlElement coll = (XmlElement)e;
float bx = Convert.ToSingle(coll.GetAttribute("x"));
float by = Convert.ToSingle(coll.GetAttribute("y"));
float bz = Convert.ToSingle(coll.GetAttribute("z"));
bbox = new Vector3(bx, by, bz);
offsetHeight = 0;
XmlNodeList groups = e.SelectNodes("SceneObjectGroup");
foreach (XmlNode n in groups)
{
SceneObjectGroup g = SceneObjectSerializer.FromOriginalXmlFormat(n.OuterXml);
objlist.Add(g);
XmlElement el = (XmlElement)n;
string rawX = el.GetAttribute("offsetx");
string rawY = el.GetAttribute("offsety");
string rawZ = el.GetAttribute("offsetz");
float x = Convert.ToSingle(rawX);
float y = Convert.ToSingle(rawY);
float z = Convert.ToSingle(rawZ);
veclist.Add(new Vector3(x, y, z));
}
return false;
}
}
}
}
catch (Exception e)
{
m_log.Error(
"[AGENT INVENTORY]: Deserialization of xml failed when looking for CoalescedObject tag. Exception ",
e);
bbox = Vector3.Zero;
offsetHeight = 0;
}
return true;
}
/// <summary>
/// Event Handler Rez an object into a scene
/// Calls the non-void event handler
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="RayEnd"></param>
/// <param name="RayStart"></param>
/// <param name="RayTargetID"></param>
/// <param name="BypassRayCast"></param>
/// <param name="RayEndIsIntersection"></param>
/// <param name="EveryoneMask"></param>
/// <param name="GroupMask"></param>
/// <param name="RezSelected"></param>
/// <param name="RemoveItem"></param>
/// <param name="fromTaskID"></param>
public virtual void RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: RezObject from {0} for item {1} from task id {2}",
// remoteClient.Name, itemID, fromTaskID);
if (fromTaskID == UUID.Zero)
{
IInventoryAccessModule invAccess = RequestModuleInterface<IInventoryAccessModule>();
if (invAccess != null)
invAccess.RezObject(
remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
RezSelected, RemoveItem, fromTaskID, false);
}
else
{
SceneObjectPart part = GetSceneObjectPart(fromTaskID);
if (part == null)
{
m_log.ErrorFormat(
"[TASK INVENTORY]: {0} tried to rez item id {1} from object id {2} but there is no such scene object",
remoteClient.Name, itemID, fromTaskID);
return;
}
TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
if (item == null)
{
m_log.ErrorFormat(
"[TASK INVENTORY]: {0} tried to rez item id {1} from object id {2} but there is no such item",
remoteClient.Name, itemID, fromTaskID);
return;
}
byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0);
Vector3 scale = new Vector3(0.5f, 0.5f, 0.5f);
Vector3 pos
= GetNewRezLocation(
RayStart, RayEnd, RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true, scale, false);
RezObject(part, item, pos, null, Vector3.Zero, 0);
}
}
/// <summary>
/// Rez an object into the scene from a prim's inventory.
/// </summary>
/// <param name="sourcePart"></param>
/// <param name="item"></param>
/// <param name="pos">The position of the rezzed object.</param>
/// <param name="rot">The rotation of the rezzed object. If null, then the rotation stored with the object
/// will be used if it exists.</param>
/// <param name="vel">The velocity of the rezzed object.</param>
/// <param name="param"></param>
/// <returns>The SceneObjectGroup(s) rezzed, or null if rez was unsuccessful</returns>
public virtual List<SceneObjectGroup> RezObject(
SceneObjectPart sourcePart, TaskInventoryItem item, Vector3 pos, Quaternion? rot, Vector3 vel, int param)
{
if (null == item)
return null;
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
bool success = sourcePart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist);
if (!success)
return null;
int totalPrims = 0;
foreach (SceneObjectGroup group in objlist)
totalPrims += group.PrimCount;
if (!Permissions.CanRezObject(totalPrims, item.OwnerID, pos))
return null;
if (!Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
sourcePart.Inventory.RemoveInventoryItem(item.ItemID);
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup group = objlist[i];
Vector3 curpos = pos + veclist[i];
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
group.FromPartID = sourcePart.UUID;
AddNewSceneObject(group, true, curpos, rot, vel);
// We can only call this after adding the scene object, since the scene object references the scene
// to find out if scripts should be activated at all.
group.CreateScriptInstances(param, true, DefaultScriptEngine, 3);
group.ScheduleGroupForFullUpdate();
}
return objlist;
}
public virtual bool returnObjects(SceneObjectGroup[] returnobjects,
UUID AgentId)
{
List<uint> localIDs = new List<uint>();
foreach (SceneObjectGroup grp in returnobjects)
{
AddReturn(grp.OwnerID, grp.Name, grp.AbsolutePosition,
"parcel owner return");
localIDs.Add(grp.RootPart.LocalId);
}
DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return,
UUID.Zero);
return true;
}
public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
{
SceneObjectPart part = GetSceneObjectPart(objectID);
if (part == null)
return;
if (running)
EventManager.TriggerStartScript(part.LocalId, itemID);
else
EventManager.TriggerStopScript(part.LocalId, itemID);
}
public void GetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
{
EventManager.TriggerGetScriptRunning(controllingClient, objectID, itemID);
}
void ObjectOwner(IClientAPI remoteClient, UUID ownerID, UUID groupID, List<uint> localIDs)
{
if (!Permissions.IsGod(remoteClient.AgentId))
{
if (ownerID != UUID.Zero)
return;
if (!Permissions.CanDeedObject(remoteClient.AgentId, groupID))
return;
}
List<SceneObjectGroup> groups = new List<SceneObjectGroup>();
foreach (uint localID in localIDs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
continue;
if (!groups.Contains(part.ParentGroup))
groups.Add(part.ParentGroup);
}
foreach (SceneObjectGroup sog in groups)
{
if (ownerID != UUID.Zero)
{
sog.SetOwnerId(ownerID);
sog.SetGroup(groupID, remoteClient);
sog.ScheduleGroupForFullUpdate();
SceneObjectPart[] partList = sog.Parts;
foreach (SceneObjectPart child in partList)
{
child.Inventory.ChangeInventoryOwner(ownerID);
child.TriggerScriptChangedEvent(Changed.OWNER);
}
}
else
{
if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId))
continue;
if (sog.GroupID != groupID)
continue;
SceneObjectPart[] partList = sog.Parts;
foreach (SceneObjectPart child in partList)
{
child.LastOwnerID = child.OwnerID;
child.Inventory.ChangeInventoryOwner(groupID);
child.TriggerScriptChangedEvent(Changed.OWNER);
}
sog.SetOwnerId(groupID);
sog.ApplyNextOwnerPermissions();
}
}
foreach (uint localID in localIDs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
continue;
part.SendPropertiesToClient(remoteClient);
}
}
public void DelinkObjects(List<uint> primIds, IClientAPI client)
{
List<SceneObjectPart> parts = new List<SceneObjectPart>();
foreach (uint localID in primIds)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
continue;
if (Permissions.CanDelinkObject(client.AgentId, part.ParentGroup.RootPart.UUID))
parts.Add(part);
}
m_sceneGraph.DelinkObjects(parts);
}
/// <summary>
/// Link the scene objects containing the indicated parts to a root object.
/// </summary>
/// <param name="client"></param>
/// <param name="parentPrimId">A root prim id of the object which will be the root prim of the resulting linkset.</param>
/// <param name="childPrimIds">A list of child prims for the objects that should be linked in.</param>
public void LinkObjects(IClientAPI client, uint parentPrimId, List<uint> childPrimIds)
{
LinkObjects(client.AgentId, parentPrimId, childPrimIds);
}
/// <summary>
/// Link the scene objects containing the indicated parts to a root object.
/// </summary>
/// <param name="agentId">The ID of the user linking.</param>
/// <param name="parentPrimId">A root prim id of the object which will be the root prim of the resulting linkset.</param>
/// <param name="childPrimIds">A list of child prims for the objects that should be linked in.</param>
public void LinkObjects(UUID agentId, uint parentPrimId, List<uint> childPrimIds)
{
List<UUID> owners = new List<UUID>();
List<SceneObjectPart> children = new List<SceneObjectPart>();
SceneObjectPart root = GetSceneObjectPart(parentPrimId);
if (root == null)
{
m_log.DebugFormat("[LINK]: Can't find linkset root prim {0}", parentPrimId);
return;
}
if (!Permissions.CanLinkObject(agentId, root.ParentGroup.RootPart.UUID))
{
m_log.DebugFormat("[LINK]: Refusing link. No permissions on root prim");
return;
}
foreach (uint localID in childPrimIds)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
continue;
if (!owners.Contains(part.OwnerID))
owners.Add(part.OwnerID);
if (Permissions.CanLinkObject(agentId, part.ParentGroup.RootPart.UUID))
children.Add(part);
}
// Must be all one owner
//
if (owners.Count > 1)
{
m_log.DebugFormat("[LINK]: Refusing link. Too many owners");
return;
}
if (children.Count == 0)
{
m_log.DebugFormat("[LINK]: Refusing link. No permissions to link any of the children");
return;
}
m_sceneGraph.LinkObjects(root, children);
}
private string PermissionString(uint permissions)
{
PermissionMask perms = (PermissionMask)permissions &
(PermissionMask.Move |
PermissionMask.Copy |
PermissionMask.Transfer |
PermissionMask.Modify);
return perms.ToString();
}
}
}
| 44.713904 | 256 | 0.541641 | [
"BSD-3-Clause"
] | BlueWall/opensim | OpenSim/Region/Framework/Scenes/Scene.Inventory.cs | 117,061 | C# |
using System;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;
namespace Maui.Controls.Sample.Pages
{
public partial class WindowsCollapseStyleChangerPage : ContentPage
{
public static readonly BindableProperty ParentPageProperty = BindableProperty.Create("ParentPage", typeof(Microsoft.Maui.Controls.FlyoutPage), typeof(WindowsCollapseStyleChangerPage), null, propertyChanged:OnParentPagePropertyChanged);
public Microsoft.Maui.Controls.FlyoutPage ParentPage
{
get { return (Microsoft.Maui.Controls.FlyoutPage)GetValue(ParentPageProperty); }
set { SetValue(ParentPageProperty, value); }
}
public WindowsCollapseStyleChangerPage()
{
InitializeComponent();
PopulatePicker();
}
void PopulatePicker()
{
var enumType = typeof(CollapseStyle);
var collapseOptions = Enum.GetNames(enumType);
foreach (string option in collapseOptions)
{
picker.Items.Add(option);
}
}
void OnPickerSelectedIndexChanged(object sender, EventArgs e)
{
ParentPage.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().SetCollapseStyle((CollapseStyle)Enum.Parse(typeof(CollapseStyle), picker.Items[picker.SelectedIndex]));
}
static void OnParentPagePropertyChanged(BindableObject element, object oldValue, object newValue)
{
if (newValue != null)
{
var enumType = typeof(CollapseStyle);
var instance = element as WindowsCollapseStyleChangerPage;
instance.picker.SelectedIndex = Array.IndexOf(Enum.GetNames(enumType), Enum.GetName(enumType, instance.ParentPage.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>().GetCollapseStyle()));
}
}
}
}
| 39.673469 | 243 | 0.669753 | [
"MIT"
] | dandycheung/maui | src/Controls/samples/Controls.Sample/Pages/PlatformSpecifics/Windows/WindowsCollapseStyleChangerPage.xaml.cs | 1,946 | C# |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFRegional.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFRegional.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for IPSetDescriptor Object
/// </summary>
public class IPSetDescriptorUnmarshaller : IUnmarshaller<IPSetDescriptor, XmlUnmarshallerContext>, IUnmarshaller<IPSetDescriptor, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
IPSetDescriptor IUnmarshaller<IPSetDescriptor, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public IPSetDescriptor Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
IPSetDescriptor unmarshalledObject = new IPSetDescriptor();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Type", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Type = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Value", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Value = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static IPSetDescriptorUnmarshaller _instance = new IPSetDescriptorUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static IPSetDescriptorUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.459184 | 158 | 0.629553 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/Internal/MarshallTransformations/IPSetDescriptorUnmarshaller.cs | 3,377 | C# |
using System.Linq;
using DotVVM.Framework.Configuration;
namespace DotVVM.Contrib
{
public static class DotvvmConfigurationExtensions
{
public static void AddContribPolicyViewConfiguration(this DotvvmConfiguration config)
{
// register tag prefix
if (!config.Markup.Controls.Any(c => c.TagPrefix == "dc"))
{
config.Markup.Controls.Add(new DotvvmControlConfiguration()
{
Assembly = "DotVVM.Contrib",
Namespace = "DotVVM.Contrib",
TagPrefix = "dc"
});
}
}
}
}
| 28.347826 | 93 | 0.544479 | [
"Apache-2.0"
] | PadreSVK/dotvvm-contrib | Controls/PolicyView/src/DotVVM.Contrib/DotvvmConfigurationExtensions.cs | 654 | C# |
using Csla;
using Csla.Core.FieldManager;
using System;
namespace CslaContrib.CustomFieldData
{
/// <summary>
/// ProperyInformationFactory class - must be configured in app.config or web.config
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class PropertyInformationUsingOriginalValue<T>
: PropertyInfo<T>
{
public PropertyInformationUsingOriginalValue(Type containingType, string name)
: base(name)
{
this.ContainingType = containingType;
}
public PropertyInformationUsingOriginalValue(Type containingType, string name, string friendlyName)
: base(name, friendlyName)
{
this.ContainingType = containingType;
}
public PropertyInformationUsingOriginalValue(Type containingType, string name, string friendlyName,
RelationshipTypes relationship)
: base(name, friendlyName, relationship)
{
this.ContainingType = containingType;
}
public PropertyInformationUsingOriginalValue(Type containingType, string name, string friendlyName,
T defaultValue)
: base(name, friendlyName, defaultValue)
{
this.ContainingType = containingType;
}
public PropertyInformationUsingOriginalValue(Type containingType, string name, string friendlyName,
T defaultValue, RelationshipTypes relationship)
: base(name, friendlyName, defaultValue, relationship)
{
this.ContainingType = containingType;
}
protected override IFieldData NewFieldData(string name)
{
return typeof(T).IsAssignableFrom(typeof(string)) ?
new FieldDataUsingOriginalValueViaHashCode<T>(name) as IFieldData :
new FieldDataUsingOriginalValueViaDuplicate<T>(name) as IFieldData;
}
private Type ContainingType { get; set; }
}
} | 32.857143 | 104 | 0.705435 | [
"MIT"
] | MarimerLLC/cslacontrib | branches/V4-3-x/Source/CslaContrib.CustomFieldData/PropertyInformationUsingOriginalValue.cs | 1,842 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ToolBox.Extensions.DbCommands;
using ToolBox.Models;
namespace ToolBox.Services
{
public class DB<TConnection>
where TConnection : class, IDbConnection, new()
{
private readonly string connectionString;
public DB(string connectionString)
{
this.connectionString = connectionString;
}
public IEnumerable<T> select<T>(string query, Func<IDataRecord, T> buildDelegate, IEnumerable<KeyValuePair<string, object>> parameters = null)
{
parameters = parameters ?? Enumerable.Empty<KeyValuePair<string, object>>();
using (TConnection connection = new TConnection())
{
connection.ConnectionString = this.connectionString;
connection.Open();
using (IDbTransaction transaction = connection.BeginTransaction())
using (IDbCommand command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = query;
command.setParameters(parameters);
using (IDataReader reader = command.ExecuteReader())
while (reader.Read())
yield return buildDelegate(reader);
transaction.Commit();
}
connection.Close();
}
}
public object selectValue(string query, IEnumerable<KeyValuePair<string, object>> parameters = null)
{
object result;
parameters = parameters ?? Enumerable.Empty<KeyValuePair<string, object>>();
using (TConnection connection = new TConnection())
{
connection.ConnectionString = this.connectionString;
connection.Open();
using (IDbTransaction transaction = connection.BeginTransaction())
using (IDbCommand command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = query;
command.setParameters(parameters);
result = command.ExecuteScalar();
transaction.Commit();
}
connection.Close();
}
return result;
}
public int write(string query, IEnumerable<KeyValuePair<string, object>> parameters = null)
{
int affectedRows;
parameters = parameters ?? Enumerable.Empty<KeyValuePair<string, object>>();
using (TConnection connection = new TConnection())
{
connection.ConnectionString = this.connectionString;
connection.Open();
using (IDbTransaction transaction = connection.BeginTransaction())
using (IDbCommand command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = query;
command.setParameters(parameters);
affectedRows = command.ExecuteNonQuery();
transaction.Commit();
}
connection.Close();
}
return affectedRows;
}
public void transact(Func<ICommandBuilder, TransactionAction> statementBlockDelegate)
{
using (TConnection connection = new TConnection())
{
connection.ConnectionString = this.connectionString;
connection.Open();
using (IDbTransaction transaction = connection.BeginTransaction())
{
ICommandBuilder commandBuilder = new PrvCommandBuilder(transaction);
TransactionAction action = statementBlockDelegate(commandBuilder);
if (action == TransactionAction.Commit)
transaction.Commit();
else
transaction.Rollback();
}
connection.Close();
}
}
private class PrvCommandBuilder : ICommandBuilder
{
private readonly IDbTransaction transaction;
private readonly IDictionary<string, object> parameters;
private string query;
public PrvCommandBuilder(IDbTransaction transaction)
{
this.transaction = transaction;
this.parameters = new Dictionary<string, object>();
}
public IDbCommand build()
{
IDbCommand command = this.transaction.Connection.CreateCommand();
command.Transaction = this.transaction;
command.CommandText = this.query;
command.setParameters(this.parameters);
return command;
}
public ICommandBuilder setParameter(string name, object value)
{
Asserts.stringIsFilled(name);
this.parameters[name] = value;
return this;
}
public ICommandBuilder setQuery(string query)
{
Asserts.stringIsFilled(query);
this.query = query;
return this;
}
}
}
}
| 33.420732 | 150 | 0.545521 | [
"MIT"
] | hossmi/beca-dotnet-2019 | ToolBox/Services/DB.cs | 5,483 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("DualityLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DualityLauncher")]
[assembly: AssemblyCopyright("Copyright © Fedja Adam 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("f73501ac-fb90-4db2-8161-f32a69e60c8f")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
| 40.416667 | 107 | 0.740893 | [
"MIT"
] | BraveSirAndrew/duality_onikira | DualityLauncher/Properties/AssemblyInfo.cs | 1,473 | C# |
using System;
using System.Linq;
using FuzzyRanks.Matching.FuzzyCompare.Base;
using FuzzyRanks.Matching.StringTokenize;
using FuzzyRanks.Matching.StringTokenize.Base;
namespace FuzzyRanks.Matching.FuzzyCompare.Common
{
public class NGramDistance : FuzzyComparer
{
// ***********************Fields***********************
private int nGramLength = 2;
private StringTokenizer tokenizer = new GramTokenizer();
// ***********************Properties***********************
public int NGramLength
{
get { return this.nGramLength; }
set { this.nGramLength = value; }
}
// ***********************Functions***********************
public override float Compare(string str1, string str2)
{
if (str1 == null || str2 == null)
{
return 0;
}
if (!this.CaseSensitiv)
{
str1 = str1.ToLower();
str2 = str2.ToLower();
}
if (str1.Equals(str2))
{
return 1.0f;
}
// building NGram of length=3
this.tokenizer.MaxLength = this.nGramLength;
// tokenize into NGrams e.g "Müller" -> ##M #Mü Mül üll lle ler er# r##
string[] nGrams1 = this.tokenizer.Tokenize(str1);
// tokenize into NGrams e.g "Meier" -> ##M #Me Mei eie ier er# r##
string[] nGrams2 = this.tokenizer.Tokenize(str2);
float distance = this.BuildNGramDistance(nGrams1, nGrams2);
return this.NormalizeScore(nGrams1, nGrams2, distance);
}
private float NormalizeScore(string[] nGrams1, string[] nGrams2, float score)
{
float maxDistance = nGrams1.Count() + nGrams2.Count();
if (maxDistance == 0)
{
return 0;
}
return (maxDistance - score) / maxDistance;
}
private float BuildNGramDistance(string[] nGrams1, string[] nGrams2)
{
int distance = 0;
// T = |X or Y| Vereinigungsmenge
string[] unionNGrams = nGrams1.Union(nGrams2).ToArray();
foreach (string nGram in unionNGrams)
{
// create local variable (http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/)
var currentNGram = nGram;
// |T & X| innerer Schnitt
int countInStr1 = nGrams1.Where(d => d == currentNGram).Count();
// |T & Y| innerer Schnitt
int countInStr2 = nGrams2.Where(d => d == currentNGram).Count();
distance += Math.Abs(countInStr1 - countInStr2);
}
return distance;
}
}
} | 31.010526 | 137 | 0.492872 | [
"MIT"
] | Vladimir-Novick/FuzzyRanks | Matching/FuzzyCompare/Common/NGramDistance.cs | 2,952 | C# |
namespace TraktNet.Objects.Basic.Json.Reader
{
using Newtonsoft.Json;
using Objects.Json;
using System.Threading;
using System.Threading.Tasks;
internal class CertificationsObjectJsonReader : AObjectJsonReader<ITraktCertifications>
{
public override async Task<ITraktCertifications> ReadObjectAsync(JsonTextReader jsonReader, CancellationToken cancellationToken = default)
{
CheckJsonTextReader(jsonReader);
if (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.StartObject)
{
var certificationsArrayReader = new ArrayJsonReader<ITraktCertification>();
ITraktCertifications traktCertifications = new TraktCertifications();
while (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.PropertyName)
{
var propertyName = jsonReader.Value.ToString();
switch (propertyName)
{
case JsonProperties.PROPERTY_NAME_US:
traktCertifications.US = await certificationsArrayReader.ReadArrayAsync(jsonReader, cancellationToken);
break;
default:
await JsonReaderHelper.ReadAndIgnoreInvalidContentAsync(jsonReader, cancellationToken);
break;
}
}
return traktCertifications;
}
return await Task.FromResult(default(ITraktCertifications));
}
}
}
| 40.073171 | 146 | 0.609251 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Basic/Json/Reader/CertificationsObjectJsonReader.cs | 1,645 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LeeWay.Ensure.ControllerAttributes.Tests.Fakes.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = PolicyNames.RequireAuthorizedUser)]
public class UserController : ControllerBase
{
// GET: api/Home
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Home/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/Home
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT: api/Home/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 23.066667 | 68 | 0.545279 | [
"MIT"
] | JimiSweden/LeeWay | LeeWay.Ensure.ControllerAttributes.Tests/Fakes/Controllers/UserController.cs | 1,040 | C# |
/*
* Copyright (C) 2021 AppDrill, https://appdrill.io
*
* 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.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppDrillMobileApp.Models;
using AppDrillMobileApp.ViewModels;
using AppDrillMobileApp.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace AppDrillMobileApp.Views
{
public partial class ItemsPage : ContentPage
{
ItemsViewModel _viewModel;
public ItemsPage()
{
InitializeComponent();
BindingContext = _viewModel = new ItemsViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.OnAppearing();
}
}
} | 27.791667 | 75 | 0.70015 | [
"Apache-2.0"
] | AppDrill/AppDrillSamples | AppDrillMobileApp/AppDrillMobileApp/AppDrillMobileApp/Views/ItemsPage.xaml.cs | 1,336 | C# |
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Miscellaneous;
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
using System.IO;
namespace Lucene.Net.Analysis.Sv
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Simple tests for <seealso cref="SwedishLightStemFilter"/>
/// </summary>
public class TestSwedishLightStemFilter : BaseTokenStreamTestCase
{
private Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper();
private class AnalyzerAnonymousInnerClassHelper : Analyzer
{
public AnalyzerAnonymousInnerClassHelper()
{
}
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer source = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(source, new SwedishLightStemFilter(source));
}
}
/// <summary>
/// Test against a vocabulary from the reference impl </summary>
[Test]
public virtual void TestVocabulary()
{
VocabularyAssert.AssertVocabulary(analyzer, GetDataFile("svlighttestdata.zip"), "svlight.txt");
}
[Test]
public virtual void TestKeyword()
{
CharArraySet exclusionSet = new CharArraySet(TEST_VERSION_CURRENT, AsSet("jaktkarlens"), false);
Analyzer a = new AnalyzerAnonymousInnerClassHelper2(this, exclusionSet);
CheckOneTerm(a, "jaktkarlens", "jaktkarlens");
}
private class AnalyzerAnonymousInnerClassHelper2 : Analyzer
{
private readonly TestSwedishLightStemFilter outerInstance;
private CharArraySet exclusionSet;
public AnalyzerAnonymousInnerClassHelper2(TestSwedishLightStemFilter outerInstance, CharArraySet exclusionSet)
{
this.outerInstance = outerInstance;
this.exclusionSet = exclusionSet;
}
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer source = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
TokenStream sink = new SetKeywordMarkerFilter(source, exclusionSet);
return new TokenStreamComponents(source, new SwedishLightStemFilter(sink));
}
}
/// <summary>
/// blast some random strings through the analyzer </summary>
[Test]
public virtual void TestRandomStrings()
{
CheckRandomData(Random(), analyzer, 1000 * RANDOM_MULTIPLIER);
}
[Test]
public virtual void TestEmptyTerm()
{
Analyzer a = new AnalyzerAnonymousInnerClassHelper3(this);
CheckOneTerm(a, "", "");
}
private class AnalyzerAnonymousInnerClassHelper3 : Analyzer
{
private readonly TestSwedishLightStemFilter outerInstance;
public AnalyzerAnonymousInnerClassHelper3(TestSwedishLightStemFilter outerInstance)
{
this.outerInstance = outerInstance;
}
protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer tokenizer = new KeywordTokenizer(reader);
return new TokenStreamComponents(tokenizer, new SwedishLightStemFilter(tokenizer));
}
}
}
} | 38.300885 | 122 | 0.658965 | [
"Apache-2.0"
] | b9chris/lucenenet | src/Lucene.Net.Tests.Analysis.Common/Analysis/Sv/TestSwedishLightStemFilter.cs | 4,330 | C# |
#region << 文 件 说 明 >>
/*----------------------------------------------------------------
// 文件名称:AddNewFunctionViewModel
// 创 建 者:杨程
// 创建时间:2021/12/10 16:52:34
// 文件版本:V1.0.0
// ===============================================================
// 功能描述:
//
//
//----------------------------------------------------------------*/
#endregion
using InterfaceCallRelationship.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Vampirewal.Core.Interface;
using Vampirewal.Core.SimpleMVVM;
namespace InterfaceCallRelationship.ViewModel
{
public class AddNewFunctionViewModel:BaseCRUDVM<FunctionClass>
{
private IDialogMessage Dialog { get; set; }
public AddNewFunctionViewModel(IDataContext dc,IDialogMessage dialog):base(dc)
{
Dialog = dialog;
//构造函数
}
private bool IsEdit { get; set; }=false;
public override void PassData(object obj)
{
/*
* 此处获取MainViewModel传递过来的值,如果没有传值,那么就是新增
*/
FunctionClass current=obj as FunctionClass;
if (current != null)
{
//如果是修改的话,此处需要到数据库中将systemclass数据根据这个id查出来
var system=DC.Set<SystemClass>().First(f=>f.ID==current.SystemClassId);
//传入这个命令中
SelectedSystemChangedCommand(system);
//通过框架自带的设置当前页面的实体
SetEntity(current);
Title = "修改功能模块";
IsEdit =true;
}
else
{
Title = "新增功能模块";
}
}
bool IsOk = false;
public override object GetResult()
{
/*
* 根据情况返回数据,此处图简单,就传了个bool回去
* 关闭窗体的时候生效
*/
return IsOk;
}
protected override void BaseCRUDInit()
{
Systems = new ObservableCollection<SystemClass>();
Modules= new ObservableCollection<ModuleClass>();
NewMethodClass = new MethodClass();
GetData();
}
#region 属性
/// <summary>
/// 系统下拉框的列表
/// </summary>
public ObservableCollection<SystemClass> Systems { get; set; }
/// <summary>
/// 系统下拉框中选择的系统模块
/// </summary>
public SystemClass SelectSystem { get; set; }
/// <summary>
/// 模块下拉框的列表
/// </summary>
public ObservableCollection<ModuleClass> Modules { get; set; }
/// <summary>
/// 模块下拉框中选择的模块
/// </summary>
public ModuleClass SelectModule { get; set; }
private MethodClass _NewMethodClass;
/// <summary>
/// 新增方法,因为随时会进行变更,所以改成完整属性并添加属性通知
/// </summary>
public MethodClass NewMethodClass
{
get { return _NewMethodClass; }
set { _NewMethodClass = value; DoNotify(); }
}
#endregion
#region 公共方法
#endregion
#region 私有方法
/// <summary>
/// 初始化的时候,获取系统下拉框的数据
/// </summary>
private void GetData()
{
Systems.Clear();
var systems = DC.Set<SystemClass>().ToList();
foreach (var item in systems)
{
Systems.Add(item);
}
}
#endregion
#region 命令
/// <summary>
/// 保存命令
/// </summary>
public override RelayCommand SaveCommand => new RelayCommand(() =>
{
//判断是否选择了系统和模块
if (SelectSystem != null && SelectModule != null)
{
//赋值
Entity.SystemClassId = SelectSystem.ID;
Entity.SystemClassName = SelectSystem.SystemName;
Entity.ModuleClassId = SelectModule.ID;
Entity.ModuleClassName = SelectModule.ModuleName;
//判断是否填写功能名称
if (!string.IsNullOrEmpty(Entity.FunctionName))
{
//开启事务
using (var trans = DC.Database.BeginTransaction())
{
try
{
//读取数据库获取到这个功能ID下的全部方法,然后在Entity的Methods中排除掉已存在数据库中的数据,剩下的就是本次新增的
DC.Set<MethodClass>().Where(w => w.FunctionClassId == Entity.ID).ToList().ForEach(f => Entity.methods.Remove(f));
//翔数据库中插入新增的数据
foreach (var item in Entity.methods)
{
item.SystemClassId = Entity.SystemClassId;
item.SystemClassName= Entity.SystemClassName;
item.ModuleClassId = Entity.ModuleClassId;
item.ModuleClassName = Entity.ModuleClassName;
DC.AddEntity(item);
}
if (IsEdit)
{
//DC.UpdateEntity(Entity);
}
else
{
DC.AddEntity(Entity);
}
DC.SaveChanges();
//事务提交
trans.Commit();
IsOk=true;
((Window)View).Close();//这里的View在DialogWindow窗体创建的时候,就通过框架绑定了,所以此处可直接这样使用进行窗体的关闭
}
catch (Exception ex)
{
Dialog.ShowPopupWindow(ex.Message, (Window)View, Vampirewal.Core.WpfTheme.WindowStyle.MessageType.Error);
trans.Rollback();
}
}
}
}
});
/// <summary>
/// 选择系统之后的数据变更命令
/// </summary>
public RelayCommand<SystemClass> SelectedSystemChanged => new RelayCommand<SystemClass>(SelectedSystemChangedCommand);
/// <summary>
/// 选择系统之后的数据变更命令
/// </summary>
/// <param name="s"></param>
private void SelectedSystemChangedCommand(SystemClass s)
{
//判断一下传入的SystemClass是否为空
if (s != null)
{
//清空模块列表
Modules.Clear();
//根据传入的SystemClass的id去数据库查关联的模块
var modules = DC.Set<ModuleClass>().Where(w => w.SystemClassId == s.ID).ToList();
//添加进模块列表中
foreach (var module in modules)
{
Modules.Add(module);
}
}
}
/// <summary>
/// 点击新增的时候,会new一个methodclass类覆盖掉之前的
/// </summary>
public RelayCommand AddNewMethodCommand => new RelayCommand(() =>
{
NewMethodClass = new MethodClass();
});
/// <summary>
/// 插入新的方法命令
/// </summary>
public RelayCommand InsertNewMethodCommand => new RelayCommand(() =>
{
//针对新增的方法,依次赋值
NewMethodClass.FunctionClassId = Entity.ID;
NewMethodClass.FunctionClassName = Entity.FunctionName;
if (!string.IsNullOrEmpty(NewMethodClass.MethodName))
{
if (!Entity.methods.Any(a => a.ID == NewMethodClass.ID))
{
Entity.methods.Add(NewMethodClass);
}
}
});
#endregion
}
}
| 28.776952 | 141 | 0.458726 | [
"MIT"
] | vampirewal/InterfaceCallRelationship | InterfaceCallRelationship.ViewModel/AddNewFunctionViewModel.cs | 8,721 | C# |
using Molder.Controllers;
using Molder.Web.Extensions;
using Molder.Web.Infrastructures;
using Molder.Web.Models.PageObjects.Attributes;
using Molder.Web.Models.PageObjects.Blocks;
using Molder.Web.Models.PageObjects.Elements;
using Molder.Web.Models.PageObjects.Frames;
using Molder.Web.Models.PageObjects.Pages;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Molder.Helpers;
namespace Molder.Web.Models
{
[ExcludeFromCodeCoverage]
public class PageObject
{
private VariableController _variableController;
public IEnumerable<Node> Pages { get; } = null;
public PageObject(VariableController variableController)
{
_variableController = variableController;
Pages = Initialize(GetPages());
}
private IEnumerable<Node> GetPages()
{
var projects = GetAssembly();
if (projects is null) return null;
var pages = new List<Node>();
foreach (var project in projects)
{
var classes = project.GetTypes().Where(t => t.IsClass).Where(t => t.GetCustomAttribute(typeof(PageAttribute), true) != null);
foreach (var cl in classes)
{
var pageAttribute = cl.GetCustomAttribute<PageAttribute>();
var page = (Page)Activator.CreateInstance(cl);
page.SetVariables(_variableController);
pages.Add(new Node
{
Name = pageAttribute.Name,
Object = page,
Type = ObjectType.Page,
Childrens = new List<Node>()
});
}
}
return pages;
}
private IEnumerable<Node> Initialize(IEnumerable<Node> pages)
{
var _pages = pages;
foreach(var page in _pages)
{
var elements = page.Object.GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.GetCustomAttribute<ElementAttribute>() != null);
page.Childrens = GetChildrens(elements);
}
return _pages;
}
private IEnumerable<Node> GetChildrens(IEnumerable<FieldInfo> elements, (object root, ObjectType type)? rootObject = null)
{
var childrens = new List<Node>();
foreach(var element in elements)
{
var (name, type, obj) = GetElement(element);
switch(type)
{
case ObjectType.Element:
{
if (rootObject is {type: ObjectType.Block})
{
var locator = (rootObject.Value.root as Block)?.Locator + (obj as Element)?.Locator;
((Element) obj).Locator = locator;
}
childrens.Add(new Node
{
Name = name,
Object = obj,
Type = type,
Childrens = null
});
break;
}
case ObjectType.Block:
{
var subElements = obj.GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.GetCustomAttribute<ElementAttribute>() != null);
if (rootObject is {type: ObjectType.Block})
{
var locator = (rootObject.Value.root as Block)?.Locator + (obj as Block)?.Locator;
((Block) obj).Locator = locator;
}
childrens.Add(new Node
{
Name = name,
Object = obj,
Type = type,
Childrens = GetChildrens(subElements, (obj, ObjectType.Block))
});
break;
}
case ObjectType.Frame:
{
var subElements = obj.GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.GetCustomAttribute<ElementAttribute>() != null);
if (rootObject is {type: ObjectType.Block})
{
var locator = (rootObject.Value.root as Block)?.Locator + (obj as Frame)?.Locator;
((Frame) obj).Locator = locator;
}
childrens.Add(new Node
{
Name = name,
Object = obj,
Type = type,
Childrens = GetChildrens(subElements)
});
break;
}
case ObjectType.Page:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return childrens;
}
private (string, ObjectType, object) GetElement(FieldInfo fieldInfo)
{
Attribute attribute;
string name;
object element;
var objectType = ObjectType.Element;
if (fieldInfo.CheckAttribute(typeof(BlockAttribute)))
{
attribute = fieldInfo.GetCustomAttribute<BlockAttribute>();
name = ((BlockAttribute)attribute).Name;
element = Activator.CreateInstance(fieldInfo.FieldType, ((BlockAttribute)attribute).Name, ((BlockAttribute)attribute).Locator, ((BlockAttribute)attribute).Optional);
objectType = ObjectType.Block;
}
else
{
if (fieldInfo.CheckAttribute(typeof(FrameAttribute)))
{
attribute = fieldInfo.GetCustomAttribute<FrameAttribute>();
name = ((FrameAttribute)attribute).Name;
element = Activator.CreateInstance(fieldInfo.FieldType, ((FrameAttribute)attribute).Name, ((FrameAttribute)attribute).FrameName, ((FrameAttribute)attribute).Number, ((FrameAttribute)attribute).Locator, ((FrameAttribute)attribute).Optional);
objectType = ObjectType.Frame;
}
else
{
attribute = fieldInfo.GetCustomAttribute<ElementAttribute>();
name = ((ElementAttribute)attribute).Name;
element = Activator.CreateInstance(fieldInfo.FieldType, ((ElementAttribute)attribute).Name, ((ElementAttribute)attribute).Locator, ((ElementAttribute)attribute).Optional);
}
}
return (name, objectType, element);
}
private IEnumerable<Assembly> GetAssembly()
{
try
{
return AppDomain.CurrentDomain.GetAssemblies().ToList();
}
catch (Exception ex)
{
Log.Logger().LogError($@"Loading all assembly is failed, because {ex.Message}");
return null;
}
/// TODO исправить получение Assembly так как необходимо, чтобы PageObjects был в текущей сборке (CurrentDomain)
/*
var assemblies = new List<System.Reflection.Assembly>();
BaseDirectory.Create();
if (BaseDirectory.Exists())
{
var files = BaseDirectory.GetFiles("*.dll");
assemblies.AddRange(files.Select(file => System.Reflection.Assembly.Load(File.ReadAllBytes(file.FullName))));
//assemblies.AddRange(files.Select(file => CustomAssembly.LoadFile(file.FullName)));
return assemblies;
}
else
{
throw new DirectoryException($"BaseDirectory from path \"{BaseDirectory}\" is not exist");
}
*/
}
}
} | 40.686916 | 260 | 0.488343 | [
"MIT"
] | YojikR/Molder | src/Molder.Web/Models/PageObjects/Models/PageObject.cs | 8,765 | C# |
// 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.Runtime.InteropServices;
namespace ManagedDll1
{
public class Class1
{
[DllImport(
@"MAWSPINative",
EntryPoint = "GetInt",
CallingConvention = CallingConvention.StdCall
)]
private static extern int GetIntNative();
public static int GetInt()
{
return GetIntNative();
}
}
}
| 22.791667 | 71 | 0.616088 | [
"MIT"
] | belav/runtime | src/tests/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/ManagedDll1/ManagedDll1.cs | 547 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Net;
namespace Squidex.Infrastructure.Net
{
public sealed class IPAddressComparer : IComparer<IPAddress>
{
public static readonly IPAddressComparer Instance = new IPAddressComparer();
private IPAddressComparer()
{
}
public int Compare(IPAddress? x, IPAddress? y)
{
if (x == null || y == null)
{
return 0;
}
var lbytes = x.GetAddressBytes();
var rbytes = y.GetAddressBytes();
if (lbytes.Length != rbytes.Length)
{
return lbytes.Length - rbytes.Length;
}
for (var i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] - rbytes[i];
}
}
return 0;
}
}
}
| 27.148936 | 84 | 0.402038 | [
"MIT"
] | Appleseed/squidex | backend/src/Squidex.Infrastructure/Net/IPAddressComparer.cs | 1,278 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Primrose
{
// A grammar for a BASIC-like language.
internal class BasicGrammar : Grammar
{
internal BasicGrammar()
: base("BASIC",
// Grammar rules are applied in the order they are specified.
new (string, Regex)[]{
// BASIC programs used to require the programmer type in her own line numbers. The start at the beginning of the line.
("lineNumbers", new Regex("^\\d+\\s+", RegexOptions.Compiled)),
// Comments were lines that started with the keyword "REM" (for REMARK) and ran to the end of the line. They did not have to be numbered, because they were not executable and were stripped out by the interpreter.
("startLineComments", new Regex("^REM\\s ", RegexOptions.Compiled)),
// Both double-quoted and single-quoted strings were not always supported, but in this case, I'm just demonstrating how it would be done for both.
("stringDelim", new Regex("(\"|')", RegexOptions.Compiled)),
// Numbers are an optional dash, followed by a optional digits, followed by optional period, followed by 1 or more required digits. This allows us to match both integers and decimal numbers, both positive and negative, with or without leading zeroes for decimal numbers between (-1, 1).
("numbers", new Regex("-?(?:(?:\\b\\d*)?\\.)?\\b\\d+\\b", RegexOptions.Compiled)),
// Keywords are really just a list of different words we want to match, surrounded by the "word boundary" selector "\b".
("keywords", new Regex("\\b(?:RESTORE|REPEAT|RETURN|LOAD|LABEL|DATA|READ|THEN|ELSE|FOR|DIM|LET|IF|TO|STEP|NEXT|WHILE|WEND|UNTIL|GOTO|GOSUB|ON|TAB|AT|END|STOP|PRINT|INPUT|RND|INT|CLS|CLK|LEN)\\b", RegexOptions.Compiled)),
// Sometimes things we want to treat as keywords have different meanings in different locations. We can specify rules for tokens more than once.
("keywords", new Regex("^DEF FN", RegexOptions.Compiled)),
// These are all treated as mathematical operations.
("operators", new Regex("(?:\\+|;|,|-|\\*\\*|\\*|\\/|>=|<=|=|<>|<|>|OR|AND|NOT|MOD|\\(|\\)|\\[|\\])", RegexOptions.Compiled)),
// Once everything else has been matched, the left over blocks of words are treated as variable and function names.
("members", new Regex("\\w+\\$?", RegexOptions.Compiled))
})
{ }
public override List<Token> tokenize(string code)
{
return base.tokenize(code.ToUpperInvariant());
}
}
public partial class Grammar
{
public static readonly Grammar Basic = new BasicGrammar();
}
}
| 67.813953 | 306 | 0.611454 | [
"MIT"
] | NotionTheory/Primrose | csharp/Primrose.NETStandard2/Grammars/Basic.cs | 2,916 | C# |
using OnlineShop.Common.Constants;
namespace OnlineShop.Models.Products.Components
{
public abstract class Component : Product, IComponent
{
protected Component(int id, string manufacturer, string model, decimal price, double overallPerformance, int generation)
: base(id, manufacturer, model, price, overallPerformance)
{
this.Generation = generation;
}
public int Generation { get; }
public override string ToString()
{
return base.ToString() + string.Format(SuccessMessages.ComponentToString, this.Generation);
}
}
}
| 27.391304 | 128 | 0.65873 | [
"MIT"
] | PetroslavGochev/CSharpAdvancedModule | OOP Module C#/09.ExamPreparation/2020August16/OnlineShop/OnlineShop-Skeleton/OnlineShop/Models/Products/Components/Component.cs | 632 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" +
"tory, Microsoft.AspNetCore.Mvc.Razor")]
[assembly: System.Reflection.AssemblyCompanyAttribute("Insurance.Web")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyProductAttribute("Insurance.Web")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyTitleAttribute("Insurance.Web.Views")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 46.846154 | 177 | 0.687192 | [
"MIT"
] | halilibrahimcakir/Bupa-Acibadem-Sigorta-Task | src/Presentation/Insurance.Web/obj/Debug/net5.0/Insurance.Web.RazorTargetAssemblyInfo.cs | 1,218 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
int[] arr = new int[] {4, 2, -1, 1, -5, 6, -4};
//findtriplet(arr, 0);
//findtripleteff(arr, 0);
int[] A = new int[6] {1, 4, 45, 6, 10, 8};
int n = 16;
//findpairs(A, n);
int[] arr3 = new int[8] {15, 2, 4, 8, 9, 5, 10, 23};
int sum = 23;
contsum(arr3, sum);
}
public static void contsumeff(int[] arr, int sum)
{
int length = arr.Length;
int curr_sum =0;
int i = 0;
int j = 0;
for(i=0; i<length; i++)
{
while(j < length && curr_sum < sum)
{
curr_sum = curr_sum + arr[j];
j++;
}
if(curr_sum == sum)
{
Console.WriteLine("found sum");
}
curr_sum = curr_sum - arr[i]; //start over from next element
}
Console.WriteLine("not found sum");
}
public static void contsum(int[] arr, int sum)
{
int length = arr.Length;
int curr_sum = 0;
int i=0;
int j=0;
for(i=0; i<length; i++)
{
curr_sum = arr[i];
for(j=i+1; j<length; j++)
{
if(curr_sum == sum)
{
Console.WriteLine("index: " + i + "-" + (j-1));
}
if(curr_sum > sum)
{
break;
}
curr_sum = curr_sum + arr[j];
}
}
}
public static void findpairseff(int[] arr, int sum)
{
int length = arr.Length;
HashSet<int> hset = new HashSet<int>();
for(int i=0; i<length; i++)
{
int z = sum - arr[i];
if(hset.Contains(z))
{
Console.Write(arr[i] + "," + z + " ");
}
else
{
hset.Add(arr[i]);
}
}
}
public static void findpairs(int[] arr, int sum)
{
int length = arr.Length;
for(int i=0; i<length; i++)
{
for(int j=i+1; j<length; j++)
{
if(arr[i] + arr[j] == sum)
{
Console.Write("(" + arr[i] + "," + arr[j] + ")");
}
}
}
}
public static int fib(int n)
{
int[] f = new int[n+2];
f[0] = 0;
f[1] = 1;
for(int i=2; i<=n; i++)
{
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
public static int[] fibo(int n)
{
int[] f = new int[n+2];
f[0] = 0;
f[1] = 1;
for(int i=2; i<=n; i++)
{
f[i] = f[i-1] + f[i-2];
}
return f;
}
public static void findtripleteff(int[] arr, int sum)
{
int length = arr.Length;
for(int i=0; i<length; i++)
{
HashSet<int> missing_elem_col = new HashSet<int>();
for(int j=i+1; j<length; j++)
{
int missing_elem = sum -(arr[i] + arr[j]);
if(missing_elem_col.Contains(missing_elem))
{
Console.WriteLine(arr[i] + " " + arr[j] + " " + missing_elem);
}
else
{
missing_elem_col.Add(arr[j]);
}
}
}
}
public static void findtriplet(int[] arr, int val)
{
int length = arr.Length;
for(int i=0; i<length; i++)
{
for(int j=i+1; j<length; j++)
{
for(int k = j+1; k<length; k++)
{
if(arr[i] + arr[j] + arr[k] == val)
{
Console.WriteLine(arr[i] + " " + arr[j] + " " + arr[k]);
}
}
}
}
}
}
| 23.147368 | 82 | 0.351978 | [
"MIT"
] | prlabs/PrLabs | facebookplayground.cs | 4,398 | C# |
using System;
using ClearHl7.V290.Segments;
using ClearHl7.V290.Types;
using FluentAssertions;
using Xunit;
namespace ClearHl7.Tests.SegmentsTests
{
public class ScpSegmentTests
{
/// <summary>
/// Validates that FromDelimitedString() returns the object instance with all properties correctly initialized.
/// </summary>
[Fact]
public void FromDelimitedString_WithAllProperties_ReturnsCorrectlyInitializedFields()
{
ISegment expected = new ScpSegment
{
NumberOfDecontaminationSterilizationDevices = 1,
LaborCalculationType = new CodedWithExceptions
{
Identifier = "2"
},
DateFormat = new CodedWithExceptions
{
Identifier = "3"
},
DeviceNumber = new EntityIdentifier
{
EntityId = "4"
},
DeviceName = "5",
DeviceModelName = "6",
DeviceType = new CodedWithExceptions
{
Identifier = "7"
},
LotControl = new CodedWithExceptions
{
Identifier = "8"
}
};
ISegment actual = new ScpSegment();
actual.FromDelimitedString("SCP|1|2|3|4|5|6|7|8");
expected.Should().BeEquivalentTo(actual);
}
/// <summary>
/// Validates that calling FromDelimitedString() with a string input containing an incorrect segment ID results in an ArgumentException being thrown.
/// </summary>
[Fact]
public void FromDelimitedString_WithIncorrectSegmentId_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() =>
{
ISegment hl7Segment = new ScpSegment();
hl7Segment.FromDelimitedString("SCA|^~&|3|4|5|6");
});
}
/// <summary>
/// Validates that ToDelimitedString() returns output with all properties populated and in the correct sequence.
/// </summary>
[Fact]
public void ToDelimitedString_WithAllProperties_ReturnsCorrectlySequencedFields()
{
ISegment hl7Segment = new ScpSegment
{
NumberOfDecontaminationSterilizationDevices = 1,
LaborCalculationType = new CodedWithExceptions
{
Identifier = "2"
},
DateFormat = new CodedWithExceptions
{
Identifier = "3"
},
DeviceNumber = new EntityIdentifier
{
EntityId = "4"
},
DeviceName = "5",
DeviceModelName = "6",
DeviceType = new CodedWithExceptions
{
Identifier = "7"
},
LotControl = new CodedWithExceptions
{
Identifier = "8"
}
};
string expected = "SCP|1|2|3|4|5|6|7|8";
string actual = hl7Segment.ToDelimitedString();
Assert.Equal(expected, actual);
}
}
}
| 32.572816 | 157 | 0.499255 | [
"MIT"
] | davebronson/clear-hl7-net | test/ClearHl7.Tests/SegmentsTests/ScpSegmentTests.cs | 3,357 | C# |
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Controls;
namespace NegativeEncoder.Presets
{
[AddINotifyPropertyChangedInterface]
public class PresetContext
{
/// <summary>
/// 当前使用的预设(保存编辑中状态)
/// </summary>
public Preset CurrentPreset { get; set; } = new Preset();
/// <summary>
/// 输入文件路径
/// </summary>
public string InputFile { get; set; } = string.Empty;
public event SelectionChangedEventHandler InputFileChanged;
public void NotifyInputFileChange(object sender, SelectionChangedEventArgs e)
{
InputFileChanged?.Invoke(sender, e);
}
/// <summary>
/// 输出文件路径
/// </summary>
public string OutputFile { get; set; } = string.Empty;
public string AudioOutputFile { get; set; } = string.Empty;
public string MuxAudioInputFile { get; set; } = string.Empty;
public string MuxOutputFile { get; set; } = string.Empty;
/// <summary>
/// 已存储的预设
/// </summary>
public ObservableCollection<Preset> PresetList { get; set; }
/// <summary>
/// 下拉框可选项列表
/// </summary>
public PresetOption PresetOption { get; set; } = new PresetOption();
/// <summary>
/// VS脚本生成器界面元素
/// </summary>
public VsScriptBuilder.VsScript VsScript { get; set; } = new VsScriptBuilder.VsScript();
}
}
| 30.372549 | 96 | 0.599096 | [
"MIT"
] | BingLingGroup/NegativeEncoder | NegativeEncoder/Presets/PresetContext.cs | 1,653 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.V20171201.Inputs
{
/// <summary>
/// Describes the uri of a disk.
/// </summary>
public sealed class VirtualHardDiskArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the virtual hard disk's uri.
/// </summary>
[Input("uri")]
public Input<string>? Uri { get; set; }
public VirtualHardDiskArgs()
{
}
}
}
| 25.344828 | 81 | 0.635374 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20171201/Inputs/VirtualHardDiskArgs.cs | 735 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Z.EntityFramework.Plus
{
/// <summary>A query include optimized by path.</summary>
public static class QueryIncludeOptimizedByPath
{
/// <summary>Include optimized by path.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="query">The query.</param>
/// <param name="navigationPath">Full pathname of the navigation file.</param>
/// <returns>An IQueryable<T></returns>
public static IQueryable<T> IncludeOptimizedByPath<T>(IQueryable<T> query, string navigationPath)
{
var elementType = typeof (T);
var paths = navigationPath.Split('.');
// CREATE expression x => x.Right
var expression = CreateLambdaExpression(elementType, paths, 0);
var method = typeof (QueryIncludeOptimizedExtensions)
.GetMethod("IncludeOptimizedSingle", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
.MakeGenericMethod(typeof (T), expression.Type.GetGenericArguments()[1]);
query = (IQueryable<T>) method.Invoke(null, new object[] {query, expression});
return query;
}
/// <summary>Creates lambda expression.</summary>
/// <param name="parameterType">Type of the parameter.</param>
/// <param name="paths">The paths.</param>
/// <param name="currentIndex">The current index.</param>
/// <returns>The new lambda expression.</returns>
public static Expression CreateLambdaExpression(Type parameterType, string[] paths, int currentIndex)
{
// CREATE expression [x => x.Right]
// ADD parameter [x =>]
var parameter = Expression.Parameter(parameterType);
Expression expression = parameter;
// ADD property [x.Right]
expression = AppendPropertyPath(expression, paths, currentIndex);
// GET function generic type
var funcGenericType = typeof (Func<,>).MakeGenericType(parameterType, expression.Type);
// GET lambda method
var lambdaMethod = typeof (Expression).GetMethods()
.Single(x => x.Name == "Lambda"
&& x.IsGenericMethod
&& x.GetParameters().Length == 2
&& !x.GetParameters()[1].ParameterType.IsArray)
.MakeGenericMethod(funcGenericType);
// CREATE lambda expression
expression = (Expression) lambdaMethod.Invoke(null, new object[] {expression, new List<ParameterExpression> {parameter}});
return expression;
}
/// <summary>Appends a path.</summary>
/// <param name="expression">The expression.</param>
/// <param name="paths">The paths.</param>
/// <param name="currentIndex">The current index.</param>
/// <returns>An Expression.</returns>
public static Expression AppendPath(Expression expression, string[] paths, int currentIndex)
{
expression = expression.Type.GetGenericArguments().Length == 0 ?
AppendPropertyPath(expression, paths, currentIndex) :
AppendSelectPath(expression, paths, currentIndex);
return expression;
}
/// <summary>Appends a property path.</summary>
/// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
/// <param name="expression">The expression.</param>
/// <param name="paths">The paths.</param>
/// <param name="currentIndex">The current index.</param>
/// <returns>An Expression.</returns>
public static Expression AppendPropertyPath(Expression expression, string[] paths, int currentIndex)
{
// APPEND [x.PropertyName]
var elementType = expression.Type;
var property = elementType.GetProperty(paths[currentIndex], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// ENSURE property exists
if (property == null)
{
throw new Exception(string.Format(ExceptionMessage.QueryIncludeOptimized_ByPath_MissingPath, elementType.FullName, paths[currentIndex]));
}
expression = Expression.Property(expression, property);
// APPEND path childs
currentIndex++;
if (currentIndex < paths.Length)
{
expression = AppendPath(expression, paths, currentIndex);
}
return expression;
}
/// <summary>Appends a select path.</summary>
/// <param name="expression">The expression.</param>
/// <param name="paths">The paths.</param>
/// <param name="currentIndex">The current index.</param>
/// <returns>An Expression.</returns>
public static Expression AppendSelectPath(Expression expression, string[] paths, int currentIndex)
{
// APPEND x => x.Rights[.Select(y => y.Right)]
var elementType = expression.Type.GetGenericArguments()[0];
// CREATE lambda expression [y => y.Right]
var lambdaExpression = CreateLambdaExpression(elementType, paths, currentIndex);
// APPEND Method [.Select(y => y.Right)]
var selectMethod = typeof (Enumerable).GetMethods()
.Single(x => x.Name == "Select"
&& x.GetParameters().Length == 2
&& x.GetParameters()[1].ParameterType.GetGenericArguments().Length == 2)
.MakeGenericMethod(elementType, lambdaExpression.Type.GetGenericArguments()[1]);
expression = Expression.Call(null, selectMethod, expression, lambdaExpression);
return expression;
}
}
} | 44.540741 | 153 | 0.606852 | [
"MIT"
] | borismod/EntityFramework-Plus | src/Z.EntityFramework.Plus.EF5.NET40/QueryIncludeOptimized/QueryIncludeOptimizedByPath.cs | 6,015 | C# |
/*
* 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.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.polardb.Model.V20170801
{
public class DescribeBackupPolicyResponse : AcsResponse
{
private string preferredBackupPeriod;
private string dataLevel1BackupRetentionPeriod;
private string requestId;
private string backupRetentionPolicyOnClusterDeletion;
private string preferredBackupTime;
private string backupFrequency;
private string preferredNextBackupTime;
private int? backupRetentionPeriod;
private string dataLevel2BackupRetentionPeriod;
public string PreferredBackupPeriod
{
get
{
return preferredBackupPeriod;
}
set
{
preferredBackupPeriod = value;
}
}
public string DataLevel1BackupRetentionPeriod
{
get
{
return dataLevel1BackupRetentionPeriod;
}
set
{
dataLevel1BackupRetentionPeriod = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string BackupRetentionPolicyOnClusterDeletion
{
get
{
return backupRetentionPolicyOnClusterDeletion;
}
set
{
backupRetentionPolicyOnClusterDeletion = value;
}
}
public string PreferredBackupTime
{
get
{
return preferredBackupTime;
}
set
{
preferredBackupTime = value;
}
}
public string BackupFrequency
{
get
{
return backupFrequency;
}
set
{
backupFrequency = value;
}
}
public string PreferredNextBackupTime
{
get
{
return preferredNextBackupTime;
}
set
{
preferredNextBackupTime = value;
}
}
public int? BackupRetentionPeriod
{
get
{
return backupRetentionPeriod;
}
set
{
backupRetentionPeriod = value;
}
}
public string DataLevel2BackupRetentionPeriod
{
get
{
return dataLevel2BackupRetentionPeriod;
}
set
{
dataLevel2BackupRetentionPeriod = value;
}
}
}
}
| 18.767742 | 63 | 0.669302 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-polardb/Polardb/Model/V20170801/DescribeBackupPolicyResponse.cs | 2,909 | C# |
// ------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------------------------------------------------------------------------------
/* This code was partially ported from: https://github.com/tavis-software/Tavis.UriTemplates;
* From the following class: UriTemplateTableTests.cs
* Some code refactoring, renaming and updates have been applied.
*/
using System;
using Xunit;
namespace UriMatchingService.Test
{
public class UriTemplateMatcherShould
{
[Theory,
InlineData("/", "root"),
InlineData("/baz/fod/burg", ""),
InlineData("/baz/kit", "kit"),
InlineData("/games/monopoly/Setup/23", "gamessetup"),
InlineData("http://www.example.com/baz/fod", "baz"),
InlineData("/baz/fod/blob", "blob"),
InlineData("/glah/flid/blob", "goo"),
InlineData("/settings/12345", "set"),
InlineData("/organization/54321/settings/iteminsights", "org"),
InlineData("/games/monopoly/22/State/33", "state"),
InlineData("/foo?x=1&y=2", "fooxy3")]
public void MatchPathToUriTemplates(string uri, string key)
{
// Arrange
var table = new UriTemplateMatcher();
table.Add("root", "/");
table.Add("foo", "/foo/{bar}");
table.Add("kit", "/baz/kit");
table.Add("fooxy3", "/foo?x={x}&y={y}");
table.Add("baz", "/baz/{bar}");
table.Add("blob", "/baz/{bar}/blob");
table.Add("goo", "/{goo}/{bar}/blob");
table.Add("set", "/settings/{id}");
table.Add("state", "/games/{gametitle}/{gameid}/State/{stateid}");
table.Add("org", "/organization/{id}/settings/iteminsights");
table.Add("gamessetup", "/games/{gametitle}/Setup/{gamesid}");
// Act
var result = table.Match(new Uri(uri, UriKind.RelativeOrAbsolute));
// Assert
if (string.IsNullOrEmpty(key))
{
Assert.Null(result);
}
else
{
Assert.Equal(key, result?.Key);
}
Assert.NotNull(table["goo"]);
Assert.Null(table["goo1"]);
}
[Fact]
public void ThrowArgumentNullExceptionForEmptyOrNullKeyValueInAdd()
{
// Arrange
var table = new UriTemplateMatcher();
// Act and Assert
Assert.Throws<ArgumentNullException>(() => table.Add("", "/settings/{id}"));
Assert.Throws<ArgumentNullException>(() => table.Add(null, "/settings/{id}"));
}
[Fact]
public void ThrowArgumentNullExceptionForEmptyOrNullTemplateValueInAdd()
{
// Arrange
var table = new UriTemplateMatcher();
// Act and Assert
Assert.Throws<ArgumentNullException>(() => table.Add("set", ""));
Assert.Throws<ArgumentNullException>(() => table.Add("set", null));
}
[Fact]
public void ThrowArgumentNullExceptionForNullUriValueInMatch()
{
// Arrange
var table = new UriTemplateMatcher();
table.Add("goo", "/{goo}/{bar}/blob");
table.Add("set", "/settings/{id}");
table.Add("org", "/organization/{id}/settings/iteminsights");
// Act and Assert
Assert.Throws<ArgumentNullException>(() =>
table.Match(null));
}
[Fact]
public void ThrowArgumentNullExceptionForEmptyOrNullKeyIndexerInTemplateTable()
{
// Arrange
var table = new UriTemplateMatcher();
// Act and Assert
Assert.Throws<ArgumentNullException>(() => table[""]);
Assert.Throws<ArgumentNullException>(() => table[null]);
}
}
}
| 37.709091 | 153 | 0.510849 | [
"MIT"
] | LokiLabs/microsoft-graph-devx-api | UriMatchService.Test/UriTemplateMatcherShould.cs | 4,148 | C# |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function initializeConvexEditor()
{
echo(" % - Initializing Sketch Tool");
exec( "./convexEditor.cs" );
exec( "./convexEditorGui.gui" );
exec( "./convexEditorToolbar.ed.gui" );
exec( "./convexEditorGui.cs" );
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
EditorGui.add( ConvexEditorGui );
EditorGui.add( ConvexEditorOptionsWindow );
EditorGui.add( ConvexEditorTreeWindow );
EditorGui.add( ConvexEditorToolbar );
new ScriptObject( ConvexEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = ConvexEditorGui;
};
// Note that we use the WorldEditor's Toolbar.
%map = new ActionMap();
%map.bindCmd( keyboard, "1", "ConvexEditorNoneModeBtn.performClick();", "" ); // Select
%map.bindCmd( keyboard, "2", "ConvexEditorMoveModeBtn.performClick();", "" ); // Move
%map.bindCmd( keyboard, "3", "ConvexEditorRotateModeBtn.performClick();", "" );// Rotate
%map.bindCmd( keyboard, "4", "ConvexEditorScaleModeBtn.performClick();", "" ); // Scale
ConvexEditorPlugin.map = %map;
ConvexEditorPlugin.initSettings();
}
function ConvexEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Sketch Tool", "", ConvexEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Sketch Tool (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "ConvexEditorPlugin", "ConvexEditorPalette", expandFilename("tools/convexEditor/images/convex-editor-btn"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( ConvexEditorOptionsWindow, ConvexEditorTreeWindow);
// Allocate our special menu.
// It will be added/removed when this editor is activated/deactivated.
if ( !isObject( ConvexActionsMenu ) )
{
singleton PopupMenu( ConvexActionsMenu )
{
superClass = "MenuBuilder";
barTitle = "Sketch";
Item[0] = "Hollow Selected Shape" TAB "" TAB "ConvexEditorGui.hollowSelection();";
item[1] = "Recenter Selected Shape" TAB "" TAB "ConvexEditorGui.recenterSelection();";
};
}
%this.popupMenu = ConvexActionsMenu;
exec( "./convexEditorSettingsTab.ed.gui" );
ESettingsWindow.addTabPage( EConvexEditorSettingsPage );
}
function ConvexEditorPlugin::onActivated( %this )
{
%this.readSettings();
EditorGui.bringToFront( ConvexEditorGui );
ConvexEditorGui.setVisible( true );
ConvexEditorToolbar.setVisible( true );
ConvexEditorGui.makeFirstResponder( true );
%this.map.push();
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo( "Sketch Tool." );
EditorGuiStatusBar.setSelection( "" );
// Add our menu.
EditorGui.menuBar.insert( ConvexActionsMenu, EditorGui.menuBar.dynamicItemInsertPos );
// Sync the pallete button state with the gizmo mode.
%mode = GlobalGizmoProfile.mode;
switch$ (%mode)
{
case "None":
ConvexEditorNoneModeBtn.performClick();
case "Move":
ConvexEditorMoveModeBtn.performClick();
case "Rotate":
ConvexEditorRotateModeBtn.performClick();
case "Scale":
ConvexEditorScaleModeBtn.performClick();
}
Parent::onActivated( %this );
}
function ConvexEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
%this.map.pop();
// Remove our menu.
EditorGui.menuBar.remove( ConvexActionsMenu );
Parent::onDeactivated( %this );
}
function ConvexEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if ( ConvexEditorGui.hasSelection() )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, %hasSelection ); // Deselect
}
function ConvexEditorPlugin::handleDelete( %this )
{
ConvexEditorGui.handleDelete();
}
function ConvexEditorPlugin::handleDeselect( %this )
{
ConvexEditorGui.handleDeselect();
}
function ConvexEditorPlugin::handleCut( %this )
{
//WorldEditorInspectorPlugin.handleCut();
}
function ConvexEditorPlugin::handleCopy( %this )
{
//WorldEditorInspectorPlugin.handleCopy();
}
function ConvexEditorPlugin::handlePaste( %this )
{
//WorldEditorInspectorPlugin.handlePaste();
}
function ConvexEditorPlugin::isDirty( %this )
{
return ConvexEditorGui.isDirty;
}
function ConvexEditorPlugin::onSaveMission( %this, %missionFile )
{
if( ConvexEditorGui.isDirty )
{
MissionGroup.save( %missionFile );
ConvexEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function ConvexEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setDefaultValue( "MaterialName", "Grid512_OrangeLines_Mat" );
EditorSettings.endGroup();
}
function ConvexEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
ConvexEditorGui.materialName = EditorSettings.value("MaterialName");
EditorSettings.endGroup();
}
function ConvexEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setValue( "MaterialName", ConvexEditorGui.materialName );
EditorSettings.endGroup();
} | 33.840909 | 152 | 0.645534 | [
"MIT"
] | 7erj1/RPG_Starter | Templates/RPGDemo/game/tools/convexEditor/main.cs | 7,226 | C# |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Mechsoft.GeneralUtilities;
using AccessControlUnit;
using log4net;
using System.IO;
using System.Net;
public partial class MasterPage : System.Web.UI.MasterPage
{
//declare and initialize logger object
static ILog logger = LogManager.GetLogger(typeof(MasterPage));
Boolean flag = false;
//void get()
//{
// DataTable dt = null;
// System.Data.Common.DbCommand objCmd = null;
// try
// {
// //Get command object
// string LastSyncDateTime = Cls_DataAccess.getInstance().ExecuteScaler(CommandType.Text, "Select Distinct LastSyncDatetime from tblSyncDataHolder").ToString();
// //objCmd = Cls_DataAccess.getInstance().GetCommand(CommandType.Text, "Select * from tblSyncDataHolder");
// dt = Cls_DataAccess.getInstance().GetDataTable(CommandType.Text, "Select * from tblSyncDataHolder order by EditedDate desc ");
// DataView dv = dt.DefaultView;
// dv.RowFilter = "EditedDate > '" + Convert.ToDateTime(LastSyncDateTime) + "'";
// dt = dv.ToTable();
// }
// catch (Exception ex)
// {
// }
// finally
// {
// objCmd = null;
// logger.Debug("Method End : GetAllMakesNormalDealers");
// }
//}
protected void Page_Init(object sender, EventArgs e)
{
if (Session[Cls_Constants.USER_NAME] != null)
{
if (String.IsNullOrEmpty(Session[Cls_Constants.USER_NAME].ToString()))
{
Response.Redirect("index.aspx", true);
}
}
else
{
Response.Redirect("index.aspx", true);
}
}
protected void Page_Load(object sender, EventArgs e)
{
// get();
try
{
if (!IsPostBack)
{
string filename = Path.GetFileName(Request.Path);
if (filename != "QuoteRequest_1.aspx" && filename != "QuoteRequest_2.aspx" && filename != "QuoteRequest_3.aspx")
RemoveSessions();
}
if (Session[Cls_Constants.USER_NAME] != null)
{
if (String.IsNullOrEmpty(Session[Cls_Constants.USER_NAME].ToString()))
Response.Redirect("index.aspx", false);
if (!IsPostBack)
{
// statrt of new code 11/01/2011 by sachin
//purpose if Dealer doesnot update its status then send mail to it and make menu links in accesssiable
if (Convert.ToString(Session[Cls_Constants.ROLE_ID]) == "2")
{
Cls_Login objCls_Login = new Cls_Login();
objCls_Login.UserName = Session[Cls_Constants.USER_NAME].ToString();
objCls_Login.Flag = 1;
DataTable dt = new DataTable();
dt = objCls_Login.GetDealerRespone();
// Int32 nonResponse_LowerLimit = 0;
Int32 nonResponse_UppeLimit = 0;
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ConfigValues objConfigue = new ConfigValues();
//objConfigue.Key = "VDT_STATUS_REMINDER_TIME_IN_DAYS";
//nonResponse_LowerLimit = Convert.ToInt32(objConfigue.GetValue(objConfigue.Key).ToString());
objConfigue.Key = "VDT_ACCOUNT_LOCK_TIME_IN_DAYS";
nonResponse_UppeLimit = Convert.ToInt32(objConfigue.GetValue(objConfigue.Key).ToString());
//objCls_Login.Dealer_Non_Response_LowerLimit = nonResponse_LowerLimit;
//objCls_Login.Dealer_Non_Response_UpperLimit = nonResponse_UppeLimit;
foreach (DataRow drow in dt.Rows)
{
DataTable dt1 = new DataTable();
DataView dv1 = new DataView(dt);
dv1.RowFilter = "Customerid=" + Convert.ToString(drow["customerid"]);
dt1 = dv1.ToTable();
if (Convert.ToInt32(drow["nonResponseDate"]) >= nonResponse_UppeLimit)
{
flag = true;
}
}
}
}
}
// end by sachin
//generate menu items to which logged in user has access
GenerateMenu();
lblUser.Text = "Welcome : " + Session[Cls_Constants.USER_NAME].ToString() + " ( " + Session[Cls_Constants.Role_Name].ToString() + " ) ";
}
//used to deduct dealer point and make dealer as normal
//if (System.DateTime.Now.Hour == 11 && System.DateTime.Now.Minute < 15)
//{
// Cls_DealAging.HandleDealAgingFactor();
// Cls_DealAging.MakeHotDealerAsNormalDealer();
//}
//end
}
else
Response.Redirect("index.aspx", false);
}
catch (Exception ex)
{
logger.Error("Page_Load Event : " + ex.Message);
}
}
//public void page_PreRender(object sender,EventArgs e)
//{
// if (flag == true)
// {
// modal.TargetControlID = "test";
// }
// else
// {
// modal.TargetControlID = "lblinvoke";
// }
//}
protected void imgbtnLogOut_Click(object sender, ImageClickEventArgs e)
{
Session.Abandon();
Session.Clear();
Session["tempURL"] = null;
Response.Redirect("index.aspx", false);
}
//used to remove session on the page quote requests
public void RemoveSessions()
{
//remove session of QR_1
Session.Remove("Make_Model_Series");
Session.Remove("ConsultantNotes");
Session.Remove("chkBox");
Session.Remove("dtParameters");
Session.Remove("SELECT_ACC");
//Session.Remove("dtAccessories");
//remove Session of QR_2
Session.Remove("PCode_Suburb");
Session.Remove("dtAllDealers");
Session.Remove("DEALER_SELECTED");
}
private void GenerateMenu()
{
Cls_Access objAccess = new Cls_Access();
DataTable dtPages = null;
try
{
objAccess.AccessFor = Convert.ToInt32(Session[Cls_Constants.ROLE_ID]);
objAccess.AccessTypeId = 1;
if (Session["dtPages"] == null)
{
dtPages = objAccess.GetPageAccess();
Session["dtPages"] = dtPages;
}
else
dtPages = (DataTable)Session["dtPages"];
int index = Request.Url.Segments.Length - 1;
string strCurrentPage = Request.Url.Segments[index];
// to check loged in user have access of this page or not
// 24 aug 2012
DataView dvTemp = dtPages.DefaultView;
dvTemp.RowFilter = "ParentID<>0";
DataTable dtChkAuthorization = dvTemp.ToTable();
if (strCurrentPage == "ConsultantTradeIn2Report.aspx")
strCurrentPage += Request.Url.Query;
dtChkAuthorization.PrimaryKey = new DataColumn[] { dtChkAuthorization.Columns["PageUrl"] };
DataRow dr = dtChkAuthorization.Rows.Find(strCurrentPage);
/*
if (dr == null)
{
logger.Error("No Access :-");
logger.Error("ID - " + Convert.ToString(Session[Cls_Constants.LOGGED_IN_USERID]) + " :: User Name - " + Convert.ToString(Session[Cls_Constants.USER_NAME]));
logger.Error("Name - " + Convert.ToString(Session[Cls_Constants.CONSULTANT_NAME]) + ":: Page - " + strCurrentPage + " :: Role ID - " + Convert.ToString(Session[Cls_Constants.ROLE_ID]));
trContent.Visible = false;
divNoAccess.Visible = false;
}
* */
//end
//if(Convert .ToString (Request .QueryString .ToString())!="")
//{
// strCurrentPage =strCurrentPage +"?"+Convert .ToString (Request .QueryString .ToString());
//}
Session["tempURL"] = strCurrentPage;
string strActive = "";
DataTable dtParent = null;
if (dtPages != null)
{
DataView dv = dtPages.DefaultView;
dv.RowFilter = "IsInternalLink=0 AND ParentID=0";
dtParent = dv.ToTable();
}
GenerateMenuHtml(dtPages, dtParent, strCurrentPage, ref strActive);
}
catch (Exception ex)
{
throw ex;
}
}
private void GenerateMenuHtml(DataTable dtPages, DataTable dtParent, string strCurrentPage, ref string strActive)
{
DataTable dtChild = null;
tdMenu.InnerHtml += "<div class='menumain' style='float:left;'><div id='firstpane' class='menu_list'>";
foreach (DataRow drParent in dtParent.Rows)
{
DataView dvChild = dtPages.DefaultView;
dvChild.RowFilter = "IsInternalLink=0 AND ParentID=" + drParent["ID"].ToString();
dtChild = dvChild.ToTable();
if (strActive == "noaccess")
strActive = "activemenu";
else
strActive = "";
if (strCurrentPage.Contains(drParent["PageUrl"].ToString()) == true)
//if (drParent["PageUrl"].ToString().Contains (strCurrentPage)==true)
// if (drParent["PageUrl"].ToString() == strCurrentPage)
{
strActive = "activemenu";
}
else
{
dvChild = dtChild.DefaultView;
dvChild.RowFilter = "IsInternalLink=0 AND PageUrl = '" + strCurrentPage + "'";
if (dvChild.ToTable().Rows.Count > 0)
strActive = "activemenu";
}
//add all parent menus first
// tdMenu.InnerHtml += "<div class='menu_head " + strActive + "'>" + drParent["PageName"].ToString() + "</div>";
if (Convert.ToString(Session[Cls_Constants.ROLE_ID]) == "2")
{
if (Convert.ToString(drParent["PageName"]) == "Quotation")
{
//Note:for restricted user
if (flag == true)
{
// tdMenu.InnerHtml += "<div class='menu_head " + strActive + "' onClick='go_toDashboard()'>" + drParent["PageName"].ToString() + "</div>";
// tdMenu.InnerHtml += "<div class='menu_head_1" + strActive + "' onClick='go_toDashboard()'>" + drParent["PageName"].ToString() + "</div>";
tdMenu.InnerHtml += "<div class='menu_head " + strActive + "' >" + drParent["PageName"].ToString() + "</div>";
}
else
{
tdMenu.InnerHtml += "<div class='menu_head " + strActive + "' >" + drParent["PageName"].ToString() + "</div>";
}
}
else
{
tdMenu.InnerHtml += "<div class='menu_head " + strActive + "'>" + drParent["PageName"].ToString() + "</div>";
}
if (dtChild.Rows.Count > 0)
{
tdMenu.InnerHtml += "<div class='menu_body'>";
//add child menus for this parent menu
foreach (DataRow drChild in dtChild.Rows)
{
string strSelected = "";
if (strCurrentPage.Contains(drChild["PageUrl"].ToString()) == true)
// if (drChild["PageUrl"].ToString() == strCurrentPage)
strSelected = "class = 'selectedMenu'";
else
strSelected = "";
tdMenu.InnerHtml += "<a href='" + drChild["PageUrl"].ToString() + "' " + strSelected + ">" + drChild["PageName"].ToString() + "</a>";
}
tdMenu.InnerHtml += "</div>";
}
}
else
{
tdMenu.InnerHtml += "<div class='menu_head " + strActive + "'>" + drParent["PageName"].ToString() + "</div>";
if (dtChild.Rows.Count > 0)
{
tdMenu.InnerHtml += "<div class='menu_body'>";
//add child menus for this parent menu
foreach (DataRow drChild in dtChild.Rows)
{
string strSelected = "";
if (strCurrentPage.Contains(drChild["PageUrl"].ToString()) == true)
//if (drChild["PageUrl"].ToString() == strCurrentPage)
strSelected = "class = 'selectedMenu'";
else
strSelected = "";
tdMenu.InnerHtml += "<a href='" + drChild["PageUrl"].ToString() + "' " + strSelected + ">" + drChild["PageName"].ToString() + "</a>";
}
tdMenu.InnerHtml += "</div>";
}
}
}
/*Added By Pravin For Showing CRM's Menue To Consultant*/
if (Convert.ToString(Session[Cls_Constants.ROLE_ID]) == "3" || Convert.ToString(Session[Cls_Constants.ROLE_ID]) == "1" || Convert.ToString(Session[Cls_Constants.ROLE_ID]) == "5")
{
string strSelected = "";
//if (strCurrentPage.Contains("http://180.235.129.33/PFSales/UserLogin.aspx") == true)
if (strCurrentPage.Contains("http://122.99.112.75/PFSales/UserLogin.aspx") == true)
//if (strCurrentPage.Contains("http://localhost:2831/PFSalesWeb/UserLogin.aspx") == true)122.99.112.75
//if (drChild["PageUrl"].ToString() == strCurrentPage)
strSelected = "class = 'selectedMenu'";
else
strSelected = "";
//string strHref = "http://localhost:2831/PFSalesWeb/UserLogin.aspx?UserId=" + Session[Cls_Constants.LOGGED_IN_USERID].ToString().Trim();
//string strHref = "http://180.235.129.33/PFSales/UserLogin.aspx?UserId=" + Session[Cls_Constants.LOGGED_IN_USERID].ToString().Trim();
string strHref = "http://122.99.112.75/PFSales/UserLogin.aspx?UserId=" + Session[Cls_Constants.LOGGED_IN_USERID].ToString().Trim();
tdMenu.InnerHtml += "<div class='menu_head' style='color:white;' " + strActive + "'>" + "<a target='_blank' href='" + strHref + "'" + ">" + "CRM </a></div>";
//tdMenu.InnerHtml += "<div class='menu_body'>";
//tdMenu.InnerHtml += "<a target='_blank' href='" + strHref + "'" + ">Get Lead Information</a>";
//tdMenu.InnerHtml += "</div>";
}
/*------------------------------ END ---------------------------------- */
tdMenu.InnerHtml += "</div></div>";
}
public void Restart()
{
logger.Error("Restarting application at : " + DateTime.Now.ToString());
logger.Debug("Restarting application at : " + DateTime.Now.ToString());
System.Web.HttpRuntime.UnloadAppDomain();
WebClient myWebClient = null;
try
{
string url = "http://localhost:1264/PrivateFleet.Web_New/index.aspx";
myWebClient = new WebClient();
byte[] stuff = myWebClient.DownloadData(url);
}
catch
{
}
finally
{
logger.Error("Restarting application End : " + DateTime.Now.ToString());
logger.Debug("Restarting application End : " + DateTime.Now.ToString());
myWebClient.Dispose();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
//logger.Error("Timer1_Tick at : " + DateTime.Now.ToString());
int hour = DateTime.Now.TimeOfDay.Hours;
int min = DateTime.Now.TimeOfDay.Minutes;
int sec = DateTime.Now.TimeOfDay.Seconds;
TimeSpan tm = new TimeSpan(hour, min, sec);
string miniutes = "";
string hours = "";
if (hour >= 0 && hour <= 9)
{
hours = "0" + min.ToString();
}
else
{
hours = hour.ToString();
}
if (min >= 0 && min <= 9)
{
miniutes = "0" + min.ToString();
}
else
{
miniutes = min.ToString();
}
string str = hour.ToString() + ":" + miniutes;
string str1 = "17:48";
if (str == str1)
{
Restart();
}
// logger.Error("Timer1_Tick at : " + DateTime.Now.ToString());
}
public void btnModalInvoke_Click(object sender, EventArgs e)
{
try
{
pnlmodal.Visible = true;
modal.Enabled = true;
modal.Show();
}
catch (Exception ex)
{
logger.Error(Convert.ToString(ex.Message));
}
}
public void btnClose_Click(object sender, EventArgs e)
{
try
{
pnlmodal.Visible = false;
modal.Enabled = false;
modal.Hide();
Response.Redirect("ClinetIfo_ForDealer.aspx");
}
catch (Exception ex)
{
logger.Error(Convert.ToString(ex.Message));
}
}
protected void btnPrevious_Click(object sender, ImageClickEventArgs e)
{
try
{
Response.Redirect("Welcome.aspx");
}
catch (Exception ex)
{
logger.Error("Back No Access err - " + ex.Message);
}
}
}
| 37.770961 | 201 | 0.50536 | [
"MIT"
] | mileslee1987/PrivateFleet | PrivateFleet.New/MasterPage.master.cs | 18,470 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinIoTEPDInk")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WinIoTEPDInk")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.896552 | 84 | 0.741595 | [
"MIT"
] | Inokinoki/SharpEInk | WinIoTEPDInk/Properties/AssemblyInfo.cs | 1,044 | C# |
using System;
using System.Text;
using Newtonsoft.Json;
using Topos.Serialization;
namespace TileWatcher.Serialize
{
internal class FileNotificationSerializer : IMessageSerializer
{
public ReceivedLogicalMessage Deserialize(ReceivedTransportMessage message)
{
if (message is null)
throw new ArgumentNullException($"{nameof(ReceivedTransportMessage)} is null");
var messageBody = Encoding.UTF8.GetString(message.Body, 0, message.Body.Length);
var fileChangedEvent = JsonConvert.DeserializeObject<FileChangedEvent>(messageBody);
if (fileChangedEvent is null)
throw new ArgumentNullException($"{nameof(FileChangedEvent)} cannot be null.");
return new ReceivedLogicalMessage(message.Headers, fileChangedEvent, message.Position);
}
public TransportMessage Serialize(LogicalMessage message)
{
throw new System.NotImplementedException();
}
}
}
| 32.483871 | 99 | 0.689176 | [
"MIT"
] | DAXGRID/tile-watcher | src/TileWatcher/Serialize/FileNotificationSerializer.cs | 1,007 | C# |
using Microsoft.EntityFrameworkCore;
namespace DiFrameworkRefactoring
{
public class WeatherForecastDbContext : DbContext
{
public WeatherForecastDbContext(DbContextOptions<WeatherForecastDbContext> options)
: base(options) { }
public DbSet<PersistentWeatherForecastDto> WeatherForecasts { get; set; }
}
} | 27.25 | 87 | 0.785933 | [
"MIT"
] | grzesiek-galezowski/vanilla-dependency-injection | DiFrameworksVsVanillaDi/DiFrameworkRefactoring/DiFrameworkRefactoring/WeatherForecastDbContext.cs | 327 | C# |
using System.Collections.Generic;
using Microsoft.Management.Infrastructure;
namespace DeviceId.Windows.Mmi.Components;
/// <summary>
/// An implementation of <see cref="IDeviceIdComponent"/> that retrieves data from a WQL query
/// </summary>
public class MmiWqlDeviceIdComponent : IDeviceIdComponent
{
/// <summary>
/// The class name.
/// </summary>
private readonly string _className;
/// <summary>
/// The property name.
/// </summary>
private readonly string _propertyName;
/// <summary>
/// Initializes a new instance of the <see cref="MmiWqlDeviceIdComponent"/> class.
/// </summary>
/// <param name="className">The class name.</param>
/// <param name="propertyName">The property name.</param>
public MmiWqlDeviceIdComponent(string className, string propertyName)
{
_className = className;
_propertyName = propertyName;
}
/// <summary>
/// Gets the component value.
/// </summary>
/// <returns>The component value.</returns>
public string GetValue()
{
var values = new List<string>();
try
{
using var session = CimSession.Create(null);
var instances = session.QueryInstances(@"root\cimv2", "WQL", $"SELECT {_propertyName} FROM {_className}");
foreach (var instance in instances)
{
try
{
if (instance.CimInstanceProperties[_propertyName].Value is string value)
{
values.Add(value);
}
}
finally
{
instance.Dispose();
}
}
}
catch
{
}
values.Sort();
return values.Count > 0
? string.Join(",", values.ToArray())
: null;
}
}
| 26.416667 | 118 | 0.54469 | [
"MIT"
] | AlexSchuetz/DeviceId | src/DeviceId.Windows.Mmi/Components/MmiWqlDeviceIdComponent.cs | 1,904 | C# |
namespace Skybrud.Social.Meetup.Scopes {
/// <summary>
/// Static class with properties representing scopes of available for the Meetup API.
/// </summary>
/// <see>
/// <cref>https://www.meetup.com/meetup_api/auth/#oauth2-scopes</cref>
/// </see>
public static class MeetupScopes {
/// <summary>
/// Granted by default. Gives access to basic Meetup group info and creating and editing Events and RSVP's, posting photos in version 2 API's and below.
/// </summary>
public static readonly MeetupScope Basic = new MeetupScope(
"basic",
"Gives access to basic Meetup group info and creating and editing Events and RSVP's, posting photos in version 2 API's and below."
);
/// <summary>
/// Replaces the <strong>one hour</strong> expiry time from oauth2 tokens with a limit of up to <strong>two weeks</strong>.
/// </summary>
public static readonly MeetupScope Ageless = new MeetupScope(
"ageless",
"Replaces the <strong>one hour</strong> expiry time from oauth2 tokens with a limit of up to <strong>two weeks</strong>."
);
/// <summary>
/// Allows the authorized application to create and make modifications to events in your Meetup groups on your behalf.
/// </summary>
public static readonly MeetupScope EventManagement = new MeetupScope(
"event_management",
"Allows the authorized application to create and make modifications to events in your Meetup groups on your behalf."
);
/// <summary>
/// Allows the authorized application to edit the settings of groups you organize on your behalf.
/// </summary>
public static readonly MeetupScope GroupEdit = new MeetupScope(
"group_edit",
"Allows the authorized application to edit the settings of groups you organize on your behalf."
);
/// <summary>
/// Allows the authorized application to create, modify and delete group content on your behalf.
/// </summary>
public static readonly MeetupScope GroupContentEdit = new MeetupScope(
"group_content_edit",
"Allows the authorized application to create, modify and delete group content on your behalf."
);
/// <summary>
/// Allows the authorized application to join new Meetup groups on your behalf.
/// </summary>
public static readonly MeetupScope GroupJoin = new MeetupScope(
"group_join",
"Allows the authorized application to join new Meetup groups on your behalf."
);
/// <summary>
/// Enables Member to Member messaging (this is now deprecated).
/// </summary>
public static readonly MeetupScope Messaging = new MeetupScope(
"messaging",
"Enables Member to Member messaging (this is now deprecated)."
);
/// <summary>
/// Allows the authorized application to edit your profile information on your behalf.
/// </summary>
public static readonly MeetupScope ProfileEdit = new MeetupScope(
"profile_edit",
"Allows the authorized application to edit your profile information on your behalf."
);
/// <summary>
/// Allows the authorized application to block and unblock other members and submit abuse reports on your behalf.
/// </summary>
public static readonly MeetupScope Reporting = new MeetupScope(
"reporting",
"Allows the authorized application to block and unblock other members and submit abuse reports on your behalf."
);
/// <summary>
/// Allows the authorized application to RSVP you to events on your behalf.
/// </summary>
public static readonly MeetupScope Rsvp = new MeetupScope(
"rsvp",
"Allows the authorized application to RSVP you to events on your behalf."
);
}
} | 43.308511 | 160 | 0.629084 | [
"MIT"
] | abjerner/Skybrud.Social.Meetup | src/Skybrud.Social.Meetup/Scopes/MeetupScopes.cs | 4,073 | C# |
/*
* Author : Maxime JUMELLE
* Namespace : MorePPEffects
* Project : More Post-Processing Effects Package
*
* If you have any suggestion or comment, you can write me at webmaster[at]hardgames3d.com
*
* File : Posterization.cs
* Abstract : Applies a posterization effect on camera.
*
* */
using System;
using UnityEngine;
using UnityStandardAssets.ImageEffects;
namespace MorePPEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/More Effects/Posterization")]
public class Posterization : PostEffectsBase
{
// The different variations of tones
public float tonesAmount = 25.0f;
// The gamma factor
public float gamma = 0.5f;
public Shader posterizationShader = null;
private Material posterizationMaterial = null;
public override bool CheckResources ()
{
posterizationShader = Shader.Find ("MorePPEffects/Posterization");
CheckSupport (false);
posterizationMaterial = CheckShaderAndCreateMaterial(posterizationShader, posterizationMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources()==false)
{
Graphics.Blit (source, destination);
return;
}
posterizationMaterial.SetFloat ("tonesAmount", tonesAmount);
posterizationMaterial.SetFloat ("gammaFactor", gamma);
Graphics.Blit (source, destination, posterizationMaterial);
}
}
}
| 26.105263 | 100 | 0.738575 | [
"MIT"
] | Anarchy-Massacre-Studio/TheFPSGame | Assets/Effects/More PostProcessing Effects/Scripts/Posterization.cs | 1,490 | C# |
using System.Collections.Generic;
using MSFramework.EventBus;
namespace MSFramework.Domain
{
/// <summary>
/// Represents an aggregate root.
/// </summary>
public interface IAggregateRoot
{
/// <summary>
/// the id as string of the aggregate root.
/// </summary>
/// <returns></returns>
string GetId();
int Version { get; }
IEnumerable<IAggregateRootChangedEvent> GetChanges();
void ClearChanges();
IReadOnlyCollection<IEvent> DomainEvents { get; }
void ClearDomainEvents();
void LoadFromHistory(params IAggregateRootChangedEvent[] histories);
}
} | 20.241379 | 70 | 0.705281 | [
"MIT"
] | jackical/MSFramework | src/MSFramework/Domain/IAggregateRoot.cs | 589 | C# |
namespace _5.Card_CompareTo__.Enums
{
public enum Suit
{
Clubs = 0,
Diamonds = 13,
Hearts = 26,
Spades = 39
}
} | 15.6 | 36 | 0.5 | [
"MIT"
] | alexandrateneva/CSharp-Fundamentals-SoftUni | CSharp OOP Advanced/Enumerations and Attributes/5. Card CompareTo()/Enums/Suit.cs | 158 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Asuka.Configuration;
using Discord;
using Discord.WebSocket;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Asuka.Services;
/// <summary>
/// Starts the client and logs into discord using bot token.
/// </summary>
public class StartupService : IHostedService
{
private readonly DiscordSocketClient _client;
private readonly IOptions<DiscordOptions> _discord;
private readonly ILogger<StartupService> _logger;
private readonly IOptions<TokenOptions> _tokens;
public StartupService(
DiscordSocketClient client,
IOptions<DiscordOptions> discord,
ILogger<StartupService> logger,
IOptions<TokenOptions> tokens)
{
_client = client;
_discord = discord;
_logger = logger;
_tokens = tokens;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
string token = _tokens.Value.Discord;
if (string.IsNullOrWhiteSpace(token))
{
throw new Exception(
"Enter bot token into the `appsettings.json` file found in the application's root directory.");
}
// Login to the discord client using bot token.
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
await _client.SetActivityAsync(new Game(
_discord.Value.Status.Game,
_discord.Value.Status.Activity));
_logger.LogInformation($"{GetType().Name} started");
await Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"{GetType().Name} stopped");
await Task.CompletedTask;
}
}
| 29.967213 | 111 | 0.684354 | [
"MIT"
] | blai30/Asuka.Net | src/Client/Services/StartupService.cs | 1,830 | C# |
using Co.Id.Moonlay.Simple.Auth.Service.Lib;
using Co.Id.Moonlay.Simple.Auth.Service.Lib.Models;
using Co.Id.Moonlay.Simple.Auth.Service.Lib.Services.IdentityService;
using Co.Id.Moonlay.Simple.Auth.Service.Lib.Services.ValidateService;
using Co.Id.Moonlay.Simple.Auth.Service.Lib.ViewModels.Forms;
using Com.Moonlay.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Co.Id.Moonlay.Simple.Auth.Service.WebApi.Controllers.v1
{
[Produces("application/json")]
[ApiVersion("1.0")]
[Route("v{version:apiVersion}/payroll/payslip")]
[Authorize]
public class PayslipController : Controller
{
private const string UserAgent = "auth-service";
private readonly AuthDbContext _context;
public static readonly string ApiVersion = "1.0.0";
private readonly IIdentityService _identityService;
private readonly IValidateService _validateService;
public PayslipController(IIdentityService identityService, IValidateService validateService, AuthDbContext dbContext)
{
_identityService = identityService;
_validateService = validateService;
_context = dbContext;
}
protected void VerifyUser()
{
_identityService.Username = User.Claims.ToArray().SingleOrDefault(p => p.Type.Equals("username")).Value;
_identityService.Token = Request.Headers["Authorization"].FirstOrDefault().Replace("Bearer ", "");
_identityService.TimezoneOffset = Convert.ToInt32(Request.Headers["x-timezone-offset"]);
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Payroll>>> GetPayslips()
{
return await _context.Payrolls.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Payroll>> GetPayslips(int id)
{
var payslip = await _context.Payrolls.FindAsync(id);
if (payslip == null)
{
return NotFound();
}
return payslip;
}
[HttpPost]
public async Task<ActionResult<Payroll>> PostPayslips([FromBody] PayslipFormViewModel payslip)
{
VerifyUser();
var model = new Payroll()
{
SalaryPeriod = payslip.SalaryPeriod,
Bank = payslip.Bank,
BankAccountNumber = payslip.BankAccountNumber,
Salary = payslip.Salary,
BackDatedPayment = payslip.BackDatedPayment,
Allowance = payslip.Allowance,
Incentive = payslip.Incentive,
PaidLeave = payslip.PaidLeave,
BPJSKesehatan = payslip.BPJSKesehatan,
BPJSTenagaKerja = payslip.BPJSTenagaKerja,
};
EntityExtension.FlagForCreate(model, _identityService.Username, UserAgent);
_context.Payrolls.Add(model);
await _context.SaveChangesAsync();
return Created("", model);
}
[HttpDelete("{id}")]
public async Task<ActionResult<Payroll>> DeletePayslip(int id)
{
VerifyUser();
var payslip = await _context.Payrolls.FindAsync(id);
if (payslip == null)
{
return NotFound();
}
_context.Payrolls.Remove(payslip);
await _context.SaveChangesAsync();
return payslip;
}
[HttpPut("{id}")]
public async Task<IActionResult> PutPayslips(int id, [FromBody] PayslipFormViewModel payslip)
{
/*if (id != familyData.Id)
{
return BadRequest();
}*/
try
{
VerifyUser();
var model = await _context.Payrolls.FindAsync(id);
{
model.SalaryPeriod = payslip.SalaryPeriod;
model.Bank = payslip.Bank;
model.BankAccountNumber = payslip.BankAccountNumber;
model.Salary = payslip.Salary;
model.BackDatedPayment = payslip.BackDatedPayment;
model.Allowance = payslip.Allowance;
model.Incentive = payslip.Incentive;
model.PaidLeave = payslip.PaidLeave;
model.BPJSKesehatan = payslip.BPJSKesehatan;
model.BPJSTenagaKerja = payslip.BPJSTenagaKerja;
};
EntityExtension.FlagForUpdate(model, _identityService.Username, UserAgent);
_context.Payrolls.Update(model);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PayrollsExist(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool PayrollsExist(int id)
{
throw new NotImplementedException();
}
}
}
| 35.389262 | 125 | 0.578039 | [
"MIT"
] | Sidel17/E-Workplace-API | Co.Id.Moonlay.Simple.Auth.Service.WebApi/Controllers/v1/PayslipController.cs | 5,275 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Outputs.Keda.V1Alpha1
{
[OutputType]
public sealed class ScaledObjectSpecJobTargetRefTemplateSpecInitContainersVolumeMounts
{
/// <summary>
/// Path within the container at which the volume should be mounted. Must not contain ':'.
/// </summary>
public readonly string MountPath;
/// <summary>
/// mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10.
/// </summary>
public readonly string MountPropagation;
/// <summary>
/// This must match the Name of a Volume.
/// </summary>
public readonly string Name;
/// <summary>
/// Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.
/// </summary>
public readonly bool ReadOnly;
/// <summary>
/// Path within the volume from which the container's volume should be mounted. Defaults to "" (volume's root).
/// </summary>
public readonly string SubPath;
/// <summary>
/// Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to "" (volume's root). SubPathExpr and SubPath are mutually exclusive. This field is alpha in 1.14.
/// </summary>
public readonly string SubPathExpr;
[OutputConstructor]
private ScaledObjectSpecJobTargetRefTemplateSpecInitContainersVolumeMounts(
string mountPath,
string mountPropagation,
string name,
bool readOnly,
string subPath,
string subPathExpr)
{
MountPath = mountPath;
MountPropagation = mountPropagation;
Name = name;
ReadOnly = readOnly;
SubPath = subPath;
SubPathExpr = subPathExpr;
}
}
}
| 37.671875 | 330 | 0.64579 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/keda/dotnet/Kubernetes/Crds/Operators/Keda/Keda/V1Alpha1/Outputs/ScaledObjectSpecJobTargetRefTemplateSpecInitContainersVolumeMounts.cs | 2,411 | C# |
using System.Collections.Generic;
namespace Root.Coding.Code.Models.E01D.Base.Configurational.Settings
{
public interface SettingNode_I
{
/// <summary>
/// Gets or sets the key of this node.
/// </summary>
string Key { get; set; }
/// <summary>
/// Gets or sets the value of this node. It is used if the path terminates on this node.
/// </summary>
object Value { get; set; }
SettingNode_I Parent { get; set; }
/// <summary>
/// Gets or sets the source that contributed the value of this node.
/// </summary>
SettingSourceNode_I SourceNode { get; }
Dictionary<string, SettingNode_I> ChildNodes { get; set; }
}
}
| 27.555556 | 97 | 0.586022 | [
"Apache-2.0"
] | E01D/Base | src/E01D.Base.Configurational.Settings.Models/Coding/Code/Models/E01D/Base/Configurational/Settings/SettingNode_I.cs | 746 | C# |
using Aiursoft.Archon.SDK.Models;
using Aiursoft.Scanner.Interfaces;
using Aiursoft.XelNaga.Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
namespace Aiursoft.Archon.Services
{
public class TokenGenerator : IScopedDependency
{
private readonly RSASignService _rsa;
public TokenGenerator(RSASignService rsa)
{
_rsa = rsa;
}
public (string tokenString, DateTime expireTime) GenerateAccessToken(string appId)
{
var token = new ACToken
{
AppId = appId,
Expires = DateTime.UtcNow + new TimeSpan(0, 20, 0)
};
var tokenJson = JsonConvert.SerializeObject(token, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
});
var tokenBase64 = tokenJson.StringToBase64();
var tokenSign = _rsa.SignData(tokenJson);
return ($"{tokenBase64}.{tokenSign}", token.Expires);
}
}
}
| 31.333333 | 90 | 0.5982 | [
"MIT"
] | AiursoftWeb/Infrastructures | src/WebServices/Basic/Archon/Services/TokenGenerator.cs | 1,224 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Kore.Infrastructure;
using Kore.Web.ContentManagement.Areas.Admin.ContentBlocks.Services;
namespace Kore.Web.ContentManagement.Areas.Admin.ContentBlocks
{
public interface IContentBlockProvider
{
IEnumerable<IContentBlock> GetContentBlocks(string zoneName);
}
public class DefaultContentBlockProvider : IContentBlockProvider
{
private readonly IContentBlockService contentBlockService;
public DefaultContentBlockProvider(IContentBlockService contentBlockService)
{
this.contentBlockService = contentBlockService;
}
public virtual IEnumerable<IContentBlock> GetContentBlocks(string zoneName)
{
var workContext = EngineContext.Current.Resolve<IWebWorkContext>();
Guid? pageId = workContext.GetState<Guid?>("CurrentPageId");
var contentBlocks = contentBlockService.GetContentBlocks(zoneName, workContext.CurrentCultureCode, pageId: pageId);
return contentBlocks.Where(x => IsVisible(x)).ToList();
}
protected bool IsVisible(IContentBlock contentBlock)
{
if (contentBlock == null || !contentBlock.Enabled)
{
return false;
}
return true;
}
}
} | 33.52381 | 128 | 0.65767 | [
"MIT"
] | artinite21/KoreCMS | Kore.Web.ContentManagement/Areas/Admin/ContentBlocks/IContentBlockProvider.cs | 1,410 | C# |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using _01.InitialSetup;
namespace _08._Increase_Minion_Age
{
public class Program
{
public static void Main()
{
var selectedIds = Console.ReadLine().Split().Select(int.Parse).ToArray();
var connectionString = Configuration.ConnectionString;
var sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
var minionIds = new List<int>();
var minionaNames = new List<string>();
var minionAges = new List<int>();
using (sqlConnection)
{
SqlCommand command =
new SqlCommand($"SELECT * FROM Minions WHERE Id IN ({String.Join(", ", selectedIds)})", sqlConnection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
if (!reader.HasRows)
{
reader.Close();
sqlConnection.Close();
return;
}
while (reader.Read())
{
minionIds.Add((int)reader["Id"]);
minionaNames.Add((string)reader["Name"]);
minionAges.Add((int)reader["Age"]);
}
}
for (int i = 0; i < minionIds.Count; i++)
{
int id = minionIds[i];
string name = String.Join(" ",
minionaNames[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList()
.Select(n => n = char.ToUpper(n.First()) + n.Substring(1).ToLower()).ToArray());
int age = minionAges[i] + 1;
command = new SqlCommand("UPDATE Minions SET Name = @name, Age = @age WHERE Id = @Id", sqlConnection);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@age", age);
command.Parameters.AddWithValue("@id", id);
command.ExecuteNonQuery();
}
command = new SqlCommand($"SELECT * FROM Minions", sqlConnection);
reader = command.ExecuteReader();
using (reader)
{
if (!reader.HasRows)
{
reader.Close();
sqlConnection.Close();
return;
}
while (reader.Read())
{
Console.WriteLine($"{(int)reader["Id"]} {(string)reader["Name"]} {(int)reader["Age"]}");
}
}
}
}
}
} | 35.597561 | 123 | 0.449469 | [
"Apache-2.0"
] | Warglaive/Databases-Advanced---Entity-Framework---2018 | Introduction to Entity Framework/08. Increase Minion Age/Program.cs | 2,921 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\dwrite_2.h(525,1)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
/// <summary>
/// A font fallback definition used for mapping characters to fonts capable of supporting them.
/// </summary>
[ComImport, Guid("efa008f9-f7a1-48bf-b05c-f224713cc0ff"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IDWriteFontFallback
{
[PreserveSig]
HRESULT MapCharacters(IDWriteTextAnalysisSource analysisSource, uint textPosition, uint textLength, /* _In_opt_ */ IDWriteFontCollection baseFontCollection, /* _In_opt_z_ */ [MarshalAs(UnmanagedType.LPWStr)] string baseFamilyName, DWRITE_FONT_WEIGHT baseWeight, DWRITE_FONT_STYLE baseStyle, DWRITE_FONT_STRETCH baseStretch, /* _Out_range_(0, textLength) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 0)] uint[] mappedLength, /* _COM_Outptr_result_maybenull_ */ out IDWriteFont mappedFont, /* _Out_ */ out float scale);
}
}
| 61.529412 | 535 | 0.750478 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/IDWriteFontFallback.cs | 1,048 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.SecurityCenter.V1P1Beta1.Snippets
{
// [START securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async_flattened]
using Google.Api.Gax;
using Google.Cloud.SecurityCenter.V1P1Beta1;
using System;
using System.Linq;
using System.Threading.Tasks;
public sealed partial class GeneratedSecurityCenterClientSnippets
{
/// <summary>Snippet for ListFindingsAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task ListFindingsAsync()
{
// Create client
SecurityCenterClient securityCenterClient = await SecurityCenterClient.CreateAsync();
// Initialize request argument(s)
string parent = "organizations/[ORGANIZATION]/sources/[SOURCE]";
// Make the request
PagedAsyncEnumerable<ListFindingsResponse, ListFindingsResponse.Types.ListFindingsResult> response = securityCenterClient.ListFindingsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ListFindingsResponse.Types.ListFindingsResult item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListFindingsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ListFindingsResponse.Types.ListFindingsResult item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ListFindingsResponse.Types.ListFindingsResult> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ListFindingsResponse.Types.ListFindingsResult item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async_flattened]
}
| 45.012987 | 160 | 0.659838 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.SecurityCenter.V1P1Beta1/Google.Cloud.SecurityCenter.V1P1Beta1.GeneratedSnippets/SecurityCenterClient.ListFindingsAsyncSnippet.g.cs | 3,466 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BBDown
{
interface IFetcher
{
Task<BBDownVInfo> FetchAsync(string id);
}
}
| 15.692308 | 48 | 0.710784 | [
"MIT"
] | 1714513528/BBDown | BBDown/IFetcher.cs | 206 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float HP;
public float MaxHP;
public GameObject self;
public GameObject explosion;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(HP<=0){
GameObject Explosion = Instantiate(explosion) as GameObject;
Explosion.transform.position = transform.position;
Destroy(self);
}
}
}
| 20.37931 | 72 | 0.624365 | [
"MIT"
] | TannerMadsen/Untitled-Wizard-Demo | Assets/Scripts/EnemyHealth.cs | 593 | C# |
namespace CodeFirstExistingDatabase.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class PopulateCategoriesTable : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
| 18.176471 | 62 | 0.582524 | [
"MIT"
] | AndriesDeKock/c-sharp-code-first-entity-framework-existing-database | Migrations/201907311222093_PopulateCategoriesTable.cs | 309 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="urn:hl7-org:v3", IsNullable=false)]
public enum RegistrationReason_displayName {
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient birth")]
Patientbirth,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient first acceptance")]
Patientfirstacceptance,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient transfer in from another NHAIS area")]
PatienttransferinfromanotherNHAISarea,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient immigrant")]
Patientimmigrant,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient ex-services")]
Patientexservices,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("Patient internal transfer within the NHAIS area")]
PatientinternaltransferwithintheNHAISarea,
}
}
| 64.183673 | 1,358 | 0.72337 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/RegistrationReason_displayName.cs | 3,145 | C# |
using Amazon.Lambda.TestTool.Runtime;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
namespace Amazon.Lambda.TestTool
{
public static class Utils
{
public const string DEFAULT_CONFIG_FILE = "aws-lambda-tools-defaults.json";
public static string DetermineToolVersion()
{
AssemblyInformationalVersionAttribute attribute = null;
try
{
var assembly = Assembly.GetEntryAssembly();
if (assembly == null)
return null;
attribute = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>();
}
catch (Exception)
{
// ignored
}
return attribute?.InformationalVersion;
}
/// <summary>
/// A collection of known paths for common utilities that are usually not found in the path
/// </summary>
static readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe" },
{"dotnet", @"/usr/local/share/dotnet/dotnet" }
};
/// <summary>
/// Search the path environment variable for the command given.
/// </summary>
/// <param name="command">The command to search for in the path</param>
/// <returns>The full path to the command if found otherwise it will return null</returns>
public static string FindExecutableInPath(string command)
{
if (File.Exists(command))
return Path.GetFullPath(command);
if (string.Equals(command, "dotnet.exe"))
{
if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
command = "dotnet";
}
var mainModule = Process.GetCurrentProcess().MainModule;
if (!string.IsNullOrEmpty(mainModule?.FileName)
&& Path.GetFileName(mainModule.FileName).Equals(command, StringComparison.OrdinalIgnoreCase))
{
return mainModule.FileName;
}
}
Func<string, string> quoteRemover = x =>
{
if (x.StartsWith("\""))
x = x.Substring(1);
if (x.EndsWith("\""))
x = x.Substring(0, x.Length - 1);
return x;
};
var envPath = Environment.GetEnvironmentVariable("PATH");
foreach (var path in envPath.Split(Path.PathSeparator))
{
try
{
var fullPath = Path.Combine(quoteRemover(path), command);
if (File.Exists(fullPath))
return fullPath;
}
catch (Exception)
{
// Catch exceptions and continue if there are invalid characters in the user's path.
}
}
if (KNOWN_LOCATIONS.ContainsKey(command) && File.Exists(KNOWN_LOCATIONS[command]))
return KNOWN_LOCATIONS[command];
return null;
}
public static bool IsProjectDirectory(string directory)
{
if(Directory.GetFiles(directory, "*.csproj").Length > 0 ||
Directory.GetFiles(directory, "*.fsproj").Length > 0 ||
Directory.GetFiles(directory, "*.vbproj").Length > 0)
{
return true;
}
return false;
}
public static string FindLambdaProjectDirectory(string lambdaAssemblyDirectory)
{
if (string.IsNullOrEmpty(lambdaAssemblyDirectory))
return null;
if (IsProjectDirectory(lambdaAssemblyDirectory))
return lambdaAssemblyDirectory;
return FindLambdaProjectDirectory(Directory.GetParent(lambdaAssemblyDirectory)?.FullName);
}
public static IList<string> SearchForConfigFiles(string lambdaFunctionDirectory)
{
var configFiles = new List<string>();
// Look for JSON files that are .NET Lambda config files like aws-lambda-tools-defaults.json. The parameter
// lambdaFunctionDirectory will be set to the build directory so the search goes up the directory hierarchy.
do
{
foreach (var file in Directory.GetFiles(lambdaFunctionDirectory, "*.json", SearchOption.TopDirectoryOnly))
{
try
{
var configFile = System.Text.Json.JsonSerializer.Deserialize<LambdaConfigFile>(File.ReadAllText(file), new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
configFile.ConfigFileLocation = file;
if (!string.IsNullOrEmpty(configFile.DetermineHandler()))
{
Console.WriteLine($"Found Lambda config file {file}");
configFiles.Add(file);
}
else if(!string.IsNullOrEmpty(configFile.Template) && File.Exists(Path.Combine(lambdaFunctionDirectory, configFile.Template)))
{
var config = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);
if(config.FunctionInfos?.Count > 0)
{
Console.WriteLine($"Found Lambda config file {file}");
configFiles.Add(file);
}
}
}
catch
{
Console.WriteLine($"Error parsing JSON file: {file}");
}
}
lambdaFunctionDirectory = Directory.GetParent(lambdaFunctionDirectory)?.FullName;
} while (lambdaFunctionDirectory != null && configFiles.Count == 0);
return configFiles;
}
public static void PrintToolTitle(string productName)
{
var sb = new StringBuilder(productName);
var version = Utils.DetermineToolVersion();
if (!string.IsNullOrEmpty(version))
{
sb.Append($" ({version})");
}
Console.WriteLine(sb.ToString());
}
/// <summary>
/// Attempt to pretty print the input string. If pretty print fails return back the input string in its original form.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string TryPrettyPrintJson(string data)
{
try
{
var doc = JsonDocument.Parse(data);
var prettyPrintJson = System.Text.Json.JsonSerializer.Serialize(doc, new JsonSerializerOptions()
{
WriteIndented = true
});
return prettyPrintJson;
}
catch (Exception)
{
return data;
}
}
public static bool IsExecutableAssembliesSupported
{
get
{
#if NET6_0_OR_GREATER
return true;
#else
return false;
#endif
}
}
}
} | 36.171296 | 169 | 0.522719 | [
"Apache-2.0"
] | Otimie/aws-lambda-dotnet | Tools/LambdaTestTool/src/Amazon.Lambda.TestTool/Utils.cs | 7,815 | C# |
namespace Torshia.Models.Enums
{
public enum Role
{
User = 0,
Admin = 1
}
} | 13 | 31 | 0.5 | [
"MIT"
] | MihailDobrev/SoftUni | C# Web/C# Web Development Basics/Exam Preparation I - Torshia/Torshia.Models/Enums/Role.cs | 106 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4016
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Web.Investor {
public partial class MyInvestments {
/// <summary>
/// mvProjects control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.MultiView mvProjects;
/// <summary>
/// vList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.View vList;
/// <summary>
/// ltMyInvestments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltMyInvestments;
/// <summary>
/// gvListe control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvListe;
/// <summary>
/// rtpRaporum control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Microsoft.Reporting.WebForms.ReportViewer rtpRaporum;
/// <summary>
/// vProjectDetail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.View vProjectDetail;
/// <summary>
/// ltProjeOnizlemeSayfasi control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltProjeOnizlemeSayfasi;
/// <summary>
/// exltLogo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal exltLogo;
/// <summary>
/// lblProjectName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblProjectName;
/// <summary>
/// extxtName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtName;
/// <summary>
/// lblProjectAcronym control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblProjectAcronym;
/// <summary>
/// extxtAcronym control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtAcronym;
/// <summary>
/// lblProjectOneLinePitch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblProjectOneLinePitch;
/// <summary>
/// extxtProjectOneLinePitch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtProjectOneLinePitch;
/// <summary>
/// lblSector control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblSector;
/// <summary>
/// exltSektor control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal exltSektor;
/// <summary>
/// lblBusinessSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblBusinessSummary;
/// <summary>
/// extxtBusinessSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtBusinessSummary;
/// <summary>
/// lblManagement control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblManagement;
/// <summary>
/// extxtManagement control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtManagement;
/// <summary>
/// lblCustomErProblem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblCustomErProblem;
/// <summary>
/// extxtCustomerProblem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtCustomerProblem;
/// <summary>
/// lblProductorServices control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblProductorServices;
/// <summary>
/// extxtProductorServices control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtProductorServices;
/// <summary>
/// lblTargetMarket control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblTargetMarket;
/// <summary>
/// extxtTargetMarket control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtTargetMarket;
/// <summary>
/// lblCustomers control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblCustomers;
/// <summary>
/// extxtCustomers control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtCustomers;
/// <summary>
/// lblStrategy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblStrategy;
/// <summary>
/// extxtStrategy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtStrategy;
/// <summary>
/// lblBusinessModelType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblBusinessModelType;
/// <summary>
/// exltBusinessModelType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal exltBusinessModelType;
/// <summary>
/// lblCompetitors control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblCompetitors;
/// <summary>
/// extxtComptetitors control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtComptetitors;
/// <summary>
/// lblComptetitiveAdvange control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblComptetitiveAdvange;
/// <summary>
/// extxtComptetitiveAdvange control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal extxtComptetitiveAdvange;
/// <summary>
/// ltinvestmentAmount3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltinvestmentAmount3;
/// <summary>
/// exltInvestmenAmount control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal exltInvestmenAmount;
/// <summary>
/// btnSendMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSendMessage;
/// <summary>
/// btnReturnProjectList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnReturnProjectList;
/// <summary>
/// pnlMail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlMail;
/// <summary>
/// ltMessageFromProjectAcceptionPage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltMessageFromProjectAcceptionPage;
/// <summary>
/// exbtnVazgec2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button exbtnVazgec2;
/// <summary>
/// ucMail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Web.ASCX.WriteMessage ucMail;
/// <summary>
/// mpMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender mpMessage;
}
}
| 36.609005 | 94 | 0.56023 | [
"MIT"
] | onuraltun/BusinessAngelNetwork | Web/Investor/MyInvestments.aspx.designer.cs | 15,451 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Common;
using Lykke.Job.TradelogBridge.Core.Services;
namespace Lykke.Job.TradelogBridge.Services
{
public class ShutdownManager : IShutdownManager
{
private readonly List<IStartStop> _startStops = new List<IStartStop>();
private readonly List<IStopable> _stopables = new List<IStopable>();
public ShutdownManager(IEnumerable<IStartStop> startStops, IEnumerable<IStopable> stopables)
{
_startStops.AddRange(startStops);
_stopables.AddRange(stopables);
}
public Task StopAsync()
{
Parallel.ForEach(_startStops, i => i.Stop());
Parallel.ForEach(_stopables, i => i.Stop());
return Task.CompletedTask;
}
}
}
| 30.148148 | 100 | 0.660934 | [
"MIT"
] | LykkeCity/Lykke.Job.TradelogBridge | src/Lykke.Job.TradelogBridge.Services/ShutdownManager.cs | 816 | C# |
namespace BDSA2019.Lecture06.Models
{
public class SuperheroListDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string AlterEgo { get; set; }
}
}
| 17.5 | 44 | 0.590476 | [
"MIT"
] | ondfisk/BDSA2019 | BDSA2019.Lecture06/BDSA2019.Lecture06.Models/SuperheroListDTO.cs | 210 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Model.Dtos
{
public class ClientCreateDto
{
public string Name { get; set; }
}
}
| 15 | 40 | 0.672222 | [
"MIT"
] | JaimeAndresSalas/ASP.NET-CORE-3-VUEJS | ProjectSpaSolution/src/Model.Dtos/ClientDto.cs | 182 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A physical host
/// First published in XenServer 4.0.
/// </summary>
public partial class Host : XenObject<Host>
{
#region Constructors
public Host()
{
}
public Host(string uuid,
string name_label,
string name_description,
long memory_overhead,
List<host_allowed_operations> allowed_operations,
Dictionary<string, host_allowed_operations> current_operations,
long API_version_major,
long API_version_minor,
string API_version_vendor,
Dictionary<string, string> API_version_vendor_implementation,
bool enabled,
Dictionary<string, string> software_version,
Dictionary<string, string> other_config,
string[] capabilities,
Dictionary<string, string> cpu_configuration,
string sched_policy,
string[] supported_bootloaders,
List<XenRef<VM>> resident_VMs,
Dictionary<string, string> logging,
List<XenRef<PIF>> PIFs,
XenRef<SR> suspend_image_sr,
XenRef<SR> crash_dump_sr,
List<XenRef<Host_crashdump>> crashdumps,
List<XenRef<Host_patch>> patches,
List<XenRef<Pool_update>> updates,
List<XenRef<PBD>> PBDs,
List<XenRef<Host_cpu>> host_CPUs,
Dictionary<string, string> cpu_info,
string hostname,
string address,
XenRef<Host_metrics> metrics,
Dictionary<string, string> license_params,
string[] ha_statefiles,
string[] ha_network_peers,
Dictionary<string, XenRef<Blob>> blobs,
string[] tags,
string external_auth_type,
string external_auth_service_name,
Dictionary<string, string> external_auth_configuration,
string edition,
Dictionary<string, string> license_server,
Dictionary<string, string> bios_strings,
string power_on_mode,
Dictionary<string, string> power_on_config,
XenRef<SR> local_cache_sr,
Dictionary<string, string> chipset_info,
List<XenRef<PCI>> PCIs,
List<XenRef<PGPU>> PGPUs,
List<XenRef<PUSB>> PUSBs,
bool ssl_legacy,
Dictionary<string, string> guest_VCPUs_params,
host_display display,
long[] virtual_hardware_platform_versions,
XenRef<VM> control_domain,
List<XenRef<Pool_update>> updates_requiring_reboot,
List<XenRef<Feature>> features,
string iscsi_iqn,
bool multipathing,
string uefi_certificates,
List<XenRef<Certificate>> certificates,
string[] editions,
List<update_guidances> pending_guidances,
bool tls_verification_enabled)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.memory_overhead = memory_overhead;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.API_version_major = API_version_major;
this.API_version_minor = API_version_minor;
this.API_version_vendor = API_version_vendor;
this.API_version_vendor_implementation = API_version_vendor_implementation;
this.enabled = enabled;
this.software_version = software_version;
this.other_config = other_config;
this.capabilities = capabilities;
this.cpu_configuration = cpu_configuration;
this.sched_policy = sched_policy;
this.supported_bootloaders = supported_bootloaders;
this.resident_VMs = resident_VMs;
this.logging = logging;
this.PIFs = PIFs;
this.suspend_image_sr = suspend_image_sr;
this.crash_dump_sr = crash_dump_sr;
this.crashdumps = crashdumps;
this.patches = patches;
this.updates = updates;
this.PBDs = PBDs;
this.host_CPUs = host_CPUs;
this.cpu_info = cpu_info;
this.hostname = hostname;
this.address = address;
this.metrics = metrics;
this.license_params = license_params;
this.ha_statefiles = ha_statefiles;
this.ha_network_peers = ha_network_peers;
this.blobs = blobs;
this.tags = tags;
this.external_auth_type = external_auth_type;
this.external_auth_service_name = external_auth_service_name;
this.external_auth_configuration = external_auth_configuration;
this.edition = edition;
this.license_server = license_server;
this.bios_strings = bios_strings;
this.power_on_mode = power_on_mode;
this.power_on_config = power_on_config;
this.local_cache_sr = local_cache_sr;
this.chipset_info = chipset_info;
this.PCIs = PCIs;
this.PGPUs = PGPUs;
this.PUSBs = PUSBs;
this.ssl_legacy = ssl_legacy;
this.guest_VCPUs_params = guest_VCPUs_params;
this.display = display;
this.virtual_hardware_platform_versions = virtual_hardware_platform_versions;
this.control_domain = control_domain;
this.updates_requiring_reboot = updates_requiring_reboot;
this.features = features;
this.iscsi_iqn = iscsi_iqn;
this.multipathing = multipathing;
this.uefi_certificates = uefi_certificates;
this.certificates = certificates;
this.editions = editions;
this.pending_guidances = pending_guidances;
this.tls_verification_enabled = tls_verification_enabled;
}
/// <summary>
/// Creates a new Host from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Host(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Host from a Proxy_Host.
/// </summary>
/// <param name="proxy"></param>
public Host(Proxy_Host proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Host.
/// </summary>
public override void UpdateFrom(Host record)
{
uuid = record.uuid;
name_label = record.name_label;
name_description = record.name_description;
memory_overhead = record.memory_overhead;
allowed_operations = record.allowed_operations;
current_operations = record.current_operations;
API_version_major = record.API_version_major;
API_version_minor = record.API_version_minor;
API_version_vendor = record.API_version_vendor;
API_version_vendor_implementation = record.API_version_vendor_implementation;
enabled = record.enabled;
software_version = record.software_version;
other_config = record.other_config;
capabilities = record.capabilities;
cpu_configuration = record.cpu_configuration;
sched_policy = record.sched_policy;
supported_bootloaders = record.supported_bootloaders;
resident_VMs = record.resident_VMs;
logging = record.logging;
PIFs = record.PIFs;
suspend_image_sr = record.suspend_image_sr;
crash_dump_sr = record.crash_dump_sr;
crashdumps = record.crashdumps;
patches = record.patches;
updates = record.updates;
PBDs = record.PBDs;
host_CPUs = record.host_CPUs;
cpu_info = record.cpu_info;
hostname = record.hostname;
address = record.address;
metrics = record.metrics;
license_params = record.license_params;
ha_statefiles = record.ha_statefiles;
ha_network_peers = record.ha_network_peers;
blobs = record.blobs;
tags = record.tags;
external_auth_type = record.external_auth_type;
external_auth_service_name = record.external_auth_service_name;
external_auth_configuration = record.external_auth_configuration;
edition = record.edition;
license_server = record.license_server;
bios_strings = record.bios_strings;
power_on_mode = record.power_on_mode;
power_on_config = record.power_on_config;
local_cache_sr = record.local_cache_sr;
chipset_info = record.chipset_info;
PCIs = record.PCIs;
PGPUs = record.PGPUs;
PUSBs = record.PUSBs;
ssl_legacy = record.ssl_legacy;
guest_VCPUs_params = record.guest_VCPUs_params;
display = record.display;
virtual_hardware_platform_versions = record.virtual_hardware_platform_versions;
control_domain = record.control_domain;
updates_requiring_reboot = record.updates_requiring_reboot;
features = record.features;
iscsi_iqn = record.iscsi_iqn;
multipathing = record.multipathing;
uefi_certificates = record.uefi_certificates;
certificates = record.certificates;
editions = record.editions;
pending_guidances = record.pending_guidances;
tls_verification_enabled = record.tls_verification_enabled;
}
internal void UpdateFrom(Proxy_Host proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
memory_overhead = proxy.memory_overhead == null ? 0 : long.Parse(proxy.memory_overhead);
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<host_allowed_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_host_allowed_operations(proxy.current_operations);
API_version_major = proxy.API_version_major == null ? 0 : long.Parse(proxy.API_version_major);
API_version_minor = proxy.API_version_minor == null ? 0 : long.Parse(proxy.API_version_minor);
API_version_vendor = proxy.API_version_vendor == null ? null : proxy.API_version_vendor;
API_version_vendor_implementation = proxy.API_version_vendor_implementation == null ? null : Maps.convert_from_proxy_string_string(proxy.API_version_vendor_implementation);
enabled = (bool)proxy.enabled;
software_version = proxy.software_version == null ? null : Maps.convert_from_proxy_string_string(proxy.software_version);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
capabilities = proxy.capabilities == null ? new string[] {} : (string [])proxy.capabilities;
cpu_configuration = proxy.cpu_configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.cpu_configuration);
sched_policy = proxy.sched_policy == null ? null : proxy.sched_policy;
supported_bootloaders = proxy.supported_bootloaders == null ? new string[] {} : (string [])proxy.supported_bootloaders;
resident_VMs = proxy.resident_VMs == null ? null : XenRef<VM>.Create(proxy.resident_VMs);
logging = proxy.logging == null ? null : Maps.convert_from_proxy_string_string(proxy.logging);
PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs);
suspend_image_sr = proxy.suspend_image_sr == null ? null : XenRef<SR>.Create(proxy.suspend_image_sr);
crash_dump_sr = proxy.crash_dump_sr == null ? null : XenRef<SR>.Create(proxy.crash_dump_sr);
crashdumps = proxy.crashdumps == null ? null : XenRef<Host_crashdump>.Create(proxy.crashdumps);
patches = proxy.patches == null ? null : XenRef<Host_patch>.Create(proxy.patches);
updates = proxy.updates == null ? null : XenRef<Pool_update>.Create(proxy.updates);
PBDs = proxy.PBDs == null ? null : XenRef<PBD>.Create(proxy.PBDs);
host_CPUs = proxy.host_CPUs == null ? null : XenRef<Host_cpu>.Create(proxy.host_CPUs);
cpu_info = proxy.cpu_info == null ? null : Maps.convert_from_proxy_string_string(proxy.cpu_info);
hostname = proxy.hostname == null ? null : proxy.hostname;
address = proxy.address == null ? null : proxy.address;
metrics = proxy.metrics == null ? null : XenRef<Host_metrics>.Create(proxy.metrics);
license_params = proxy.license_params == null ? null : Maps.convert_from_proxy_string_string(proxy.license_params);
ha_statefiles = proxy.ha_statefiles == null ? new string[] {} : (string [])proxy.ha_statefiles;
ha_network_peers = proxy.ha_network_peers == null ? new string[] {} : (string [])proxy.ha_network_peers;
blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs);
tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags;
external_auth_type = proxy.external_auth_type == null ? null : proxy.external_auth_type;
external_auth_service_name = proxy.external_auth_service_name == null ? null : proxy.external_auth_service_name;
external_auth_configuration = proxy.external_auth_configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.external_auth_configuration);
edition = proxy.edition == null ? null : proxy.edition;
license_server = proxy.license_server == null ? null : Maps.convert_from_proxy_string_string(proxy.license_server);
bios_strings = proxy.bios_strings == null ? null : Maps.convert_from_proxy_string_string(proxy.bios_strings);
power_on_mode = proxy.power_on_mode == null ? null : proxy.power_on_mode;
power_on_config = proxy.power_on_config == null ? null : Maps.convert_from_proxy_string_string(proxy.power_on_config);
local_cache_sr = proxy.local_cache_sr == null ? null : XenRef<SR>.Create(proxy.local_cache_sr);
chipset_info = proxy.chipset_info == null ? null : Maps.convert_from_proxy_string_string(proxy.chipset_info);
PCIs = proxy.PCIs == null ? null : XenRef<PCI>.Create(proxy.PCIs);
PGPUs = proxy.PGPUs == null ? null : XenRef<PGPU>.Create(proxy.PGPUs);
PUSBs = proxy.PUSBs == null ? null : XenRef<PUSB>.Create(proxy.PUSBs);
ssl_legacy = (bool)proxy.ssl_legacy;
guest_VCPUs_params = proxy.guest_VCPUs_params == null ? null : Maps.convert_from_proxy_string_string(proxy.guest_VCPUs_params);
display = proxy.display == null ? (host_display) 0 : (host_display)Helper.EnumParseDefault(typeof(host_display), (string)proxy.display);
virtual_hardware_platform_versions = proxy.virtual_hardware_platform_versions == null ? null : Helper.StringArrayToLongArray(proxy.virtual_hardware_platform_versions);
control_domain = proxy.control_domain == null ? null : XenRef<VM>.Create(proxy.control_domain);
updates_requiring_reboot = proxy.updates_requiring_reboot == null ? null : XenRef<Pool_update>.Create(proxy.updates_requiring_reboot);
features = proxy.features == null ? null : XenRef<Feature>.Create(proxy.features);
iscsi_iqn = proxy.iscsi_iqn == null ? null : proxy.iscsi_iqn;
multipathing = (bool)proxy.multipathing;
uefi_certificates = proxy.uefi_certificates == null ? null : proxy.uefi_certificates;
certificates = proxy.certificates == null ? null : XenRef<Certificate>.Create(proxy.certificates);
editions = proxy.editions == null ? new string[] {} : (string [])proxy.editions;
pending_guidances = proxy.pending_guidances == null ? null : Helper.StringArrayToEnumList<update_guidances>(proxy.pending_guidances);
tls_verification_enabled = (bool)proxy.tls_verification_enabled;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Host
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("memory_overhead"))
memory_overhead = Marshalling.ParseLong(table, "memory_overhead");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<host_allowed_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_host_allowed_operations(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("API_version_major"))
API_version_major = Marshalling.ParseLong(table, "API_version_major");
if (table.ContainsKey("API_version_minor"))
API_version_minor = Marshalling.ParseLong(table, "API_version_minor");
if (table.ContainsKey("API_version_vendor"))
API_version_vendor = Marshalling.ParseString(table, "API_version_vendor");
if (table.ContainsKey("API_version_vendor_implementation"))
API_version_vendor_implementation = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "API_version_vendor_implementation"));
if (table.ContainsKey("enabled"))
enabled = Marshalling.ParseBool(table, "enabled");
if (table.ContainsKey("software_version"))
software_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "software_version"));
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("capabilities"))
capabilities = Marshalling.ParseStringArray(table, "capabilities");
if (table.ContainsKey("cpu_configuration"))
cpu_configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cpu_configuration"));
if (table.ContainsKey("sched_policy"))
sched_policy = Marshalling.ParseString(table, "sched_policy");
if (table.ContainsKey("supported_bootloaders"))
supported_bootloaders = Marshalling.ParseStringArray(table, "supported_bootloaders");
if (table.ContainsKey("resident_VMs"))
resident_VMs = Marshalling.ParseSetRef<VM>(table, "resident_VMs");
if (table.ContainsKey("logging"))
logging = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "logging"));
if (table.ContainsKey("PIFs"))
PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs");
if (table.ContainsKey("suspend_image_sr"))
suspend_image_sr = Marshalling.ParseRef<SR>(table, "suspend_image_sr");
if (table.ContainsKey("crash_dump_sr"))
crash_dump_sr = Marshalling.ParseRef<SR>(table, "crash_dump_sr");
if (table.ContainsKey("crashdumps"))
crashdumps = Marshalling.ParseSetRef<Host_crashdump>(table, "crashdumps");
if (table.ContainsKey("patches"))
patches = Marshalling.ParseSetRef<Host_patch>(table, "patches");
if (table.ContainsKey("updates"))
updates = Marshalling.ParseSetRef<Pool_update>(table, "updates");
if (table.ContainsKey("PBDs"))
PBDs = Marshalling.ParseSetRef<PBD>(table, "PBDs");
if (table.ContainsKey("host_CPUs"))
host_CPUs = Marshalling.ParseSetRef<Host_cpu>(table, "host_CPUs");
if (table.ContainsKey("cpu_info"))
cpu_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "cpu_info"));
if (table.ContainsKey("hostname"))
hostname = Marshalling.ParseString(table, "hostname");
if (table.ContainsKey("address"))
address = Marshalling.ParseString(table, "address");
if (table.ContainsKey("metrics"))
metrics = Marshalling.ParseRef<Host_metrics>(table, "metrics");
if (table.ContainsKey("license_params"))
license_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "license_params"));
if (table.ContainsKey("ha_statefiles"))
ha_statefiles = Marshalling.ParseStringArray(table, "ha_statefiles");
if (table.ContainsKey("ha_network_peers"))
ha_network_peers = Marshalling.ParseStringArray(table, "ha_network_peers");
if (table.ContainsKey("blobs"))
blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs"));
if (table.ContainsKey("tags"))
tags = Marshalling.ParseStringArray(table, "tags");
if (table.ContainsKey("external_auth_type"))
external_auth_type = Marshalling.ParseString(table, "external_auth_type");
if (table.ContainsKey("external_auth_service_name"))
external_auth_service_name = Marshalling.ParseString(table, "external_auth_service_name");
if (table.ContainsKey("external_auth_configuration"))
external_auth_configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "external_auth_configuration"));
if (table.ContainsKey("edition"))
edition = Marshalling.ParseString(table, "edition");
if (table.ContainsKey("license_server"))
license_server = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "license_server"));
if (table.ContainsKey("bios_strings"))
bios_strings = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "bios_strings"));
if (table.ContainsKey("power_on_mode"))
power_on_mode = Marshalling.ParseString(table, "power_on_mode");
if (table.ContainsKey("power_on_config"))
power_on_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "power_on_config"));
if (table.ContainsKey("local_cache_sr"))
local_cache_sr = Marshalling.ParseRef<SR>(table, "local_cache_sr");
if (table.ContainsKey("chipset_info"))
chipset_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "chipset_info"));
if (table.ContainsKey("PCIs"))
PCIs = Marshalling.ParseSetRef<PCI>(table, "PCIs");
if (table.ContainsKey("PGPUs"))
PGPUs = Marshalling.ParseSetRef<PGPU>(table, "PGPUs");
if (table.ContainsKey("PUSBs"))
PUSBs = Marshalling.ParseSetRef<PUSB>(table, "PUSBs");
if (table.ContainsKey("ssl_legacy"))
ssl_legacy = Marshalling.ParseBool(table, "ssl_legacy");
if (table.ContainsKey("guest_VCPUs_params"))
guest_VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "guest_VCPUs_params"));
if (table.ContainsKey("display"))
display = (host_display)Helper.EnumParseDefault(typeof(host_display), Marshalling.ParseString(table, "display"));
if (table.ContainsKey("virtual_hardware_platform_versions"))
virtual_hardware_platform_versions = Marshalling.ParseLongArray(table, "virtual_hardware_platform_versions");
if (table.ContainsKey("control_domain"))
control_domain = Marshalling.ParseRef<VM>(table, "control_domain");
if (table.ContainsKey("updates_requiring_reboot"))
updates_requiring_reboot = Marshalling.ParseSetRef<Pool_update>(table, "updates_requiring_reboot");
if (table.ContainsKey("features"))
features = Marshalling.ParseSetRef<Feature>(table, "features");
if (table.ContainsKey("iscsi_iqn"))
iscsi_iqn = Marshalling.ParseString(table, "iscsi_iqn");
if (table.ContainsKey("multipathing"))
multipathing = Marshalling.ParseBool(table, "multipathing");
if (table.ContainsKey("uefi_certificates"))
uefi_certificates = Marshalling.ParseString(table, "uefi_certificates");
if (table.ContainsKey("certificates"))
certificates = Marshalling.ParseSetRef<Certificate>(table, "certificates");
if (table.ContainsKey("editions"))
editions = Marshalling.ParseStringArray(table, "editions");
if (table.ContainsKey("pending_guidances"))
pending_guidances = Helper.StringArrayToEnumList<update_guidances>(Marshalling.ParseStringArray(table, "pending_guidances"));
if (table.ContainsKey("tls_verification_enabled"))
tls_verification_enabled = Marshalling.ParseBool(table, "tls_verification_enabled");
}
public Proxy_Host ToProxy()
{
Proxy_Host result_ = new Proxy_Host();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.memory_overhead = memory_overhead.ToString();
result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations);
result_.current_operations = Maps.convert_to_proxy_string_host_allowed_operations(current_operations);
result_.API_version_major = API_version_major.ToString();
result_.API_version_minor = API_version_minor.ToString();
result_.API_version_vendor = API_version_vendor ?? "";
result_.API_version_vendor_implementation = Maps.convert_to_proxy_string_string(API_version_vendor_implementation);
result_.enabled = enabled;
result_.software_version = Maps.convert_to_proxy_string_string(software_version);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.capabilities = capabilities;
result_.cpu_configuration = Maps.convert_to_proxy_string_string(cpu_configuration);
result_.sched_policy = sched_policy ?? "";
result_.supported_bootloaders = supported_bootloaders;
result_.resident_VMs = resident_VMs == null ? new string[] {} : Helper.RefListToStringArray(resident_VMs);
result_.logging = Maps.convert_to_proxy_string_string(logging);
result_.PIFs = PIFs == null ? new string[] {} : Helper.RefListToStringArray(PIFs);
result_.suspend_image_sr = suspend_image_sr ?? "";
result_.crash_dump_sr = crash_dump_sr ?? "";
result_.crashdumps = crashdumps == null ? new string[] {} : Helper.RefListToStringArray(crashdumps);
result_.patches = patches == null ? new string[] {} : Helper.RefListToStringArray(patches);
result_.updates = updates == null ? new string[] {} : Helper.RefListToStringArray(updates);
result_.PBDs = PBDs == null ? new string[] {} : Helper.RefListToStringArray(PBDs);
result_.host_CPUs = host_CPUs == null ? new string[] {} : Helper.RefListToStringArray(host_CPUs);
result_.cpu_info = Maps.convert_to_proxy_string_string(cpu_info);
result_.hostname = hostname ?? "";
result_.address = address ?? "";
result_.metrics = metrics ?? "";
result_.license_params = Maps.convert_to_proxy_string_string(license_params);
result_.ha_statefiles = ha_statefiles;
result_.ha_network_peers = ha_network_peers;
result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs);
result_.tags = tags;
result_.external_auth_type = external_auth_type ?? "";
result_.external_auth_service_name = external_auth_service_name ?? "";
result_.external_auth_configuration = Maps.convert_to_proxy_string_string(external_auth_configuration);
result_.edition = edition ?? "";
result_.license_server = Maps.convert_to_proxy_string_string(license_server);
result_.bios_strings = Maps.convert_to_proxy_string_string(bios_strings);
result_.power_on_mode = power_on_mode ?? "";
result_.power_on_config = Maps.convert_to_proxy_string_string(power_on_config);
result_.local_cache_sr = local_cache_sr ?? "";
result_.chipset_info = Maps.convert_to_proxy_string_string(chipset_info);
result_.PCIs = PCIs == null ? new string[] {} : Helper.RefListToStringArray(PCIs);
result_.PGPUs = PGPUs == null ? new string[] {} : Helper.RefListToStringArray(PGPUs);
result_.PUSBs = PUSBs == null ? new string[] {} : Helper.RefListToStringArray(PUSBs);
result_.ssl_legacy = ssl_legacy;
result_.guest_VCPUs_params = Maps.convert_to_proxy_string_string(guest_VCPUs_params);
result_.display = host_display_helper.ToString(display);
result_.virtual_hardware_platform_versions = virtual_hardware_platform_versions == null ? new string[] {} : Helper.LongArrayToStringArray(virtual_hardware_platform_versions);
result_.control_domain = control_domain ?? "";
result_.updates_requiring_reboot = updates_requiring_reboot == null ? new string[] {} : Helper.RefListToStringArray(updates_requiring_reboot);
result_.features = features == null ? new string[] {} : Helper.RefListToStringArray(features);
result_.iscsi_iqn = iscsi_iqn ?? "";
result_.multipathing = multipathing;
result_.uefi_certificates = uefi_certificates ?? "";
result_.certificates = certificates == null ? new string[] {} : Helper.RefListToStringArray(certificates);
result_.editions = editions;
result_.pending_guidances = pending_guidances == null ? new string[] {} : Helper.ObjectListToStringArray(pending_guidances);
result_.tls_verification_enabled = tls_verification_enabled;
return result_;
}
public bool DeepEquals(Host other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._memory_overhead, other._memory_overhead) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._API_version_major, other._API_version_major) &&
Helper.AreEqual2(this._API_version_minor, other._API_version_minor) &&
Helper.AreEqual2(this._API_version_vendor, other._API_version_vendor) &&
Helper.AreEqual2(this._API_version_vendor_implementation, other._API_version_vendor_implementation) &&
Helper.AreEqual2(this._enabled, other._enabled) &&
Helper.AreEqual2(this._software_version, other._software_version) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._capabilities, other._capabilities) &&
Helper.AreEqual2(this._cpu_configuration, other._cpu_configuration) &&
Helper.AreEqual2(this._sched_policy, other._sched_policy) &&
Helper.AreEqual2(this._supported_bootloaders, other._supported_bootloaders) &&
Helper.AreEqual2(this._resident_VMs, other._resident_VMs) &&
Helper.AreEqual2(this._logging, other._logging) &&
Helper.AreEqual2(this._PIFs, other._PIFs) &&
Helper.AreEqual2(this._suspend_image_sr, other._suspend_image_sr) &&
Helper.AreEqual2(this._crash_dump_sr, other._crash_dump_sr) &&
Helper.AreEqual2(this._crashdumps, other._crashdumps) &&
Helper.AreEqual2(this._patches, other._patches) &&
Helper.AreEqual2(this._updates, other._updates) &&
Helper.AreEqual2(this._PBDs, other._PBDs) &&
Helper.AreEqual2(this._host_CPUs, other._host_CPUs) &&
Helper.AreEqual2(this._cpu_info, other._cpu_info) &&
Helper.AreEqual2(this._hostname, other._hostname) &&
Helper.AreEqual2(this._address, other._address) &&
Helper.AreEqual2(this._metrics, other._metrics) &&
Helper.AreEqual2(this._license_params, other._license_params) &&
Helper.AreEqual2(this._ha_statefiles, other._ha_statefiles) &&
Helper.AreEqual2(this._ha_network_peers, other._ha_network_peers) &&
Helper.AreEqual2(this._blobs, other._blobs) &&
Helper.AreEqual2(this._tags, other._tags) &&
Helper.AreEqual2(this._external_auth_type, other._external_auth_type) &&
Helper.AreEqual2(this._external_auth_service_name, other._external_auth_service_name) &&
Helper.AreEqual2(this._external_auth_configuration, other._external_auth_configuration) &&
Helper.AreEqual2(this._edition, other._edition) &&
Helper.AreEqual2(this._license_server, other._license_server) &&
Helper.AreEqual2(this._bios_strings, other._bios_strings) &&
Helper.AreEqual2(this._power_on_mode, other._power_on_mode) &&
Helper.AreEqual2(this._power_on_config, other._power_on_config) &&
Helper.AreEqual2(this._local_cache_sr, other._local_cache_sr) &&
Helper.AreEqual2(this._chipset_info, other._chipset_info) &&
Helper.AreEqual2(this._PCIs, other._PCIs) &&
Helper.AreEqual2(this._PGPUs, other._PGPUs) &&
Helper.AreEqual2(this._PUSBs, other._PUSBs) &&
Helper.AreEqual2(this._ssl_legacy, other._ssl_legacy) &&
Helper.AreEqual2(this._guest_VCPUs_params, other._guest_VCPUs_params) &&
Helper.AreEqual2(this._display, other._display) &&
Helper.AreEqual2(this._virtual_hardware_platform_versions, other._virtual_hardware_platform_versions) &&
Helper.AreEqual2(this._control_domain, other._control_domain) &&
Helper.AreEqual2(this._updates_requiring_reboot, other._updates_requiring_reboot) &&
Helper.AreEqual2(this._features, other._features) &&
Helper.AreEqual2(this._iscsi_iqn, other._iscsi_iqn) &&
Helper.AreEqual2(this._multipathing, other._multipathing) &&
Helper.AreEqual2(this._uefi_certificates, other._uefi_certificates) &&
Helper.AreEqual2(this._certificates, other._certificates) &&
Helper.AreEqual2(this._editions, other._editions) &&
Helper.AreEqual2(this._pending_guidances, other._pending_guidances) &&
Helper.AreEqual2(this._tls_verification_enabled, other._tls_verification_enabled);
}
public override string SaveChanges(Session session, string opaqueRef, Host server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Host.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Host.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_logging, server._logging))
{
Host.set_logging(session, opaqueRef, _logging);
}
if (!Helper.AreEqual2(_suspend_image_sr, server._suspend_image_sr))
{
Host.set_suspend_image_sr(session, opaqueRef, _suspend_image_sr);
}
if (!Helper.AreEqual2(_crash_dump_sr, server._crash_dump_sr))
{
Host.set_crash_dump_sr(session, opaqueRef, _crash_dump_sr);
}
if (!Helper.AreEqual2(_hostname, server._hostname))
{
Host.set_hostname(session, opaqueRef, _hostname);
}
if (!Helper.AreEqual2(_address, server._address))
{
Host.set_address(session, opaqueRef, _address);
}
if (!Helper.AreEqual2(_tags, server._tags))
{
Host.set_tags(session, opaqueRef, _tags);
}
if (!Helper.AreEqual2(_license_server, server._license_server))
{
Host.set_license_server(session, opaqueRef, _license_server);
}
if (!Helper.AreEqual2(_guest_VCPUs_params, server._guest_VCPUs_params))
{
Host.set_guest_VCPUs_params(session, opaqueRef, _guest_VCPUs_params);
}
if (!Helper.AreEqual2(_display, server._display))
{
Host.set_display(session, opaqueRef, _display);
}
if (!Helper.AreEqual2(_ssl_legacy, server._ssl_legacy))
{
Host.set_ssl_legacy(session, opaqueRef, _ssl_legacy);
}
if (!Helper.AreEqual2(_iscsi_iqn, server._iscsi_iqn))
{
Host.set_iscsi_iqn(session, opaqueRef, _iscsi_iqn);
}
if (!Helper.AreEqual2(_multipathing, server._multipathing))
{
Host.set_multipathing(session, opaqueRef, _multipathing);
}
if (!Helper.AreEqual2(_uefi_certificates, server._uefi_certificates))
{
Host.set_uefi_certificates(session, opaqueRef, _uefi_certificates);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Host get_record(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_record(session.opaque_ref, _host);
else
return new Host(session.XmlRpcProxy.host_get_record(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get a reference to the host instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Host> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Host>.Create(session.XmlRpcProxy.host_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the host instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Host>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Host>.Create(session.XmlRpcProxy.host_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_uuid(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_uuid(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_uuid(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_name_label(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_name_label(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_name_label(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_name_description(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_name_description(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_name_description(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the memory/overhead field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long get_memory_overhead(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_memory_overhead(session.opaque_ref, _host);
else
return long.Parse(session.XmlRpcProxy.host_get_memory_overhead(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the allowed_operations field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<host_allowed_operations> get_allowed_operations(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_allowed_operations(session.opaque_ref, _host);
else
return Helper.StringArrayToEnumList<host_allowed_operations>(session.XmlRpcProxy.host_get_allowed_operations(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, host_allowed_operations> get_current_operations(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_current_operations(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_host_allowed_operations(session.XmlRpcProxy.host_get_current_operations(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the API_version/major field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long get_API_version_major(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_api_version_major(session.opaque_ref, _host);
else
return long.Parse(session.XmlRpcProxy.host_get_api_version_major(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the API_version/minor field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long get_API_version_minor(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_api_version_minor(session.opaque_ref, _host);
else
return long.Parse(session.XmlRpcProxy.host_get_api_version_minor(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the API_version/vendor field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_API_version_vendor(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_api_version_vendor(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_api_version_vendor(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the API_version/vendor_implementation field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_API_version_vendor_implementation(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_api_version_vendor_implementation(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_api_version_vendor_implementation(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the enabled field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static bool get_enabled(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_enabled(session.opaque_ref, _host);
else
return (bool)session.XmlRpcProxy.host_get_enabled(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the software_version field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_software_version(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_software_version(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_software_version(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_other_config(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_other_config(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_other_config(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the capabilities field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_capabilities(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_capabilities(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_capabilities(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the cpu_configuration field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_cpu_configuration(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_cpu_configuration(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_cpu_configuration(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the sched_policy field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_sched_policy(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_sched_policy(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_sched_policy(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the supported_bootloaders field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_supported_bootloaders(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_supported_bootloaders(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_supported_bootloaders(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the resident_VMs field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<VM>> get_resident_VMs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_resident_vms(session.opaque_ref, _host);
else
return XenRef<VM>.Create(session.XmlRpcProxy.host_get_resident_vms(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the logging field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_logging(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_logging(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_logging(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the PIFs field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<PIF>> get_PIFs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pifs(session.opaque_ref, _host);
else
return XenRef<PIF>.Create(session.XmlRpcProxy.host_get_pifs(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the suspend_image_sr field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<SR> get_suspend_image_sr(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_suspend_image_sr(session.opaque_ref, _host);
else
return XenRef<SR>.Create(session.XmlRpcProxy.host_get_suspend_image_sr(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the crash_dump_sr field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<SR> get_crash_dump_sr(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_crash_dump_sr(session.opaque_ref, _host);
else
return XenRef<SR>.Create(session.XmlRpcProxy.host_get_crash_dump_sr(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the crashdumps field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Host_crashdump>> get_crashdumps(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_crashdumps(session.opaque_ref, _host);
else
return XenRef<Host_crashdump>.Create(session.XmlRpcProxy.host_get_crashdumps(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the patches field of the given host.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Host_patch>> get_patches(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_patches(session.opaque_ref, _host);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.host_get_patches(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the updates field of the given host.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Pool_update>> get_updates(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_updates(session.opaque_ref, _host);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.host_get_updates(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the PBDs field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<PBD>> get_PBDs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pbds(session.opaque_ref, _host);
else
return XenRef<PBD>.Create(session.XmlRpcProxy.host_get_pbds(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the host_CPUs field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Host_cpu>> get_host_CPUs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_host_cpus(session.opaque_ref, _host);
else
return XenRef<Host_cpu>.Create(session.XmlRpcProxy.host_get_host_cpus(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the cpu_info field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_cpu_info(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_cpu_info(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_cpu_info(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the hostname field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_hostname(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_hostname(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_hostname(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the address field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_address(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_address(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_address(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the metrics field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Host_metrics> get_metrics(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_metrics(session.opaque_ref, _host);
else
return XenRef<Host_metrics>.Create(session.XmlRpcProxy.host_get_metrics(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the license_params field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_license_params(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_license_params(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_license_params(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the ha_statefiles field of the given host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_ha_statefiles(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_ha_statefiles(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_ha_statefiles(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the ha_network_peers field of the given host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_ha_network_peers(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_ha_network_peers(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_ha_network_peers(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the blobs field of the given host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_blobs(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_XenRefBlob(session.XmlRpcProxy.host_get_blobs(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the tags field of the given host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_tags(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_tags(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_tags(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the external_auth_type field of the given host.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_external_auth_type(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_external_auth_type(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_external_auth_type(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the external_auth_service_name field of the given host.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_external_auth_service_name(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_external_auth_service_name(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_external_auth_service_name(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the external_auth_configuration field of the given host.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_external_auth_configuration(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_external_auth_configuration(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_external_auth_configuration(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the edition field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_edition(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_edition(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_edition(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the license_server field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_license_server(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_license_server(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_license_server(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the bios_strings field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_bios_strings(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_bios_strings(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_bios_strings(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the power_on_mode field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_power_on_mode(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_power_on_mode(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_power_on_mode(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the power_on_config field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_power_on_config(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_power_on_config(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_power_on_config(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the local_cache_sr field of the given host.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<SR> get_local_cache_sr(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_local_cache_sr(session.opaque_ref, _host);
else
return XenRef<SR>.Create(session.XmlRpcProxy.host_get_local_cache_sr(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the chipset_info field of the given host.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_chipset_info(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_chipset_info(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_chipset_info(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the PCIs field of the given host.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<PCI>> get_PCIs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pcis(session.opaque_ref, _host);
else
return XenRef<PCI>.Create(session.XmlRpcProxy.host_get_pcis(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the PGPUs field of the given host.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<PGPU>> get_PGPUs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pgpus(session.opaque_ref, _host);
else
return XenRef<PGPU>.Create(session.XmlRpcProxy.host_get_pgpus(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the PUSBs field of the given host.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<PUSB>> get_PUSBs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pusbs(session.opaque_ref, _host);
else
return XenRef<PUSB>.Create(session.XmlRpcProxy.host_get_pusbs(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the ssl_legacy field of the given host.
/// First published in XenServer 7.0.
/// Deprecated since Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("Citrix Hypervisor 8.2")]
public static bool get_ssl_legacy(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_ssl_legacy(session.opaque_ref, _host);
else
return (bool)session.XmlRpcProxy.host_get_ssl_legacy(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the guest_VCPUs_params field of the given host.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<string, string> get_guest_VCPUs_params(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_guest_vcpus_params(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_get_guest_vcpus_params(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the display field of the given host.
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static host_display get_display(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_display(session.opaque_ref, _host);
else
return (host_display)Helper.EnumParseDefault(typeof(host_display), (string)session.XmlRpcProxy.host_get_display(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the virtual_hardware_platform_versions field of the given host.
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long[] get_virtual_hardware_platform_versions(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_virtual_hardware_platform_versions(session.opaque_ref, _host);
else
return Helper.StringArrayToLongArray(session.XmlRpcProxy.host_get_virtual_hardware_platform_versions(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the control_domain field of the given host.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<VM> get_control_domain(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_control_domain(session.opaque_ref, _host);
else
return XenRef<VM>.Create(session.XmlRpcProxy.host_get_control_domain(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the updates_requiring_reboot field of the given host.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Pool_update>> get_updates_requiring_reboot(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_updates_requiring_reboot(session.opaque_ref, _host);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.host_get_updates_requiring_reboot(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the features field of the given host.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Feature>> get_features(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_features(session.opaque_ref, _host);
else
return XenRef<Feature>.Create(session.XmlRpcProxy.host_get_features(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the iscsi_iqn field of the given host.
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_iscsi_iqn(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_iscsi_iqn(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_iscsi_iqn(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the multipathing field of the given host.
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static bool get_multipathing(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_multipathing(session.opaque_ref, _host);
else
return (bool)session.XmlRpcProxy.host_get_multipathing(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the uefi_certificates field of the given host.
/// First published in Citrix Hypervisor 8.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_uefi_certificates(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_uefi_certificates(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_uefi_certificates(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the certificates field of the given host.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<XenRef<Certificate>> get_certificates(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_certificates(session.opaque_ref, _host);
else
return XenRef<Certificate>.Create(session.XmlRpcProxy.host_get_certificates(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the editions field of the given host.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string[] get_editions(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_editions(session.opaque_ref, _host);
else
return (string [])session.XmlRpcProxy.host_get_editions(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the pending_guidances field of the given host.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<update_guidances> get_pending_guidances(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_pending_guidances(session.opaque_ref, _host);
else
return Helper.StringArrayToEnumList<update_guidances>(session.XmlRpcProxy.host_get_pending_guidances(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the tls_verification_enabled field of the given host.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static bool get_tls_verification_enabled(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_tls_verification_enabled(session.opaque_ref, _host);
else
return (bool)session.XmlRpcProxy.host_get_tls_verification_enabled(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Set the name/label field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _host, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_name_label(session.opaque_ref, _host, _label);
else
session.XmlRpcProxy.host_set_name_label(session.opaque_ref, _host ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _host, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_name_description(session.opaque_ref, _host, _description);
else
session.XmlRpcProxy.host_set_name_description(session.opaque_ref, _host ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_other_config(session.opaque_ref, _host, _other_config);
else
session.XmlRpcProxy.host_set_other_config(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_add_to_other_config(session.opaque_ref, _host, _key, _value);
else
session.XmlRpcProxy.host_add_to_other_config(session.opaque_ref, _host ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_remove_from_other_config(session.opaque_ref, _host, _key);
else
session.XmlRpcProxy.host_remove_from_other_config(session.opaque_ref, _host ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the logging field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_logging">New value to set</param>
public static void set_logging(Session session, string _host, Dictionary<string, string> _logging)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_logging(session.opaque_ref, _host, _logging);
else
session.XmlRpcProxy.host_set_logging(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_logging)).parse();
}
/// <summary>
/// Add the given key-value pair to the logging field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_logging(Session session, string _host, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_add_to_logging(session.opaque_ref, _host, _key, _value);
else
session.XmlRpcProxy.host_add_to_logging(session.opaque_ref, _host ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the logging field of the given host. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_logging(Session session, string _host, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_remove_from_logging(session.opaque_ref, _host, _key);
else
session.XmlRpcProxy.host_remove_from_logging(session.opaque_ref, _host ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the suspend_image_sr field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_suspend_image_sr">New value to set</param>
public static void set_suspend_image_sr(Session session, string _host, string _suspend_image_sr)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_suspend_image_sr(session.opaque_ref, _host, _suspend_image_sr);
else
session.XmlRpcProxy.host_set_suspend_image_sr(session.opaque_ref, _host ?? "", _suspend_image_sr ?? "").parse();
}
/// <summary>
/// Set the crash_dump_sr field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_crash_dump_sr">New value to set</param>
public static void set_crash_dump_sr(Session session, string _host, string _crash_dump_sr)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_crash_dump_sr(session.opaque_ref, _host, _crash_dump_sr);
else
session.XmlRpcProxy.host_set_crash_dump_sr(session.opaque_ref, _host ?? "", _crash_dump_sr ?? "").parse();
}
/// <summary>
/// Set the hostname field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_hostname">New value to set</param>
public static void set_hostname(Session session, string _host, string _hostname)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_hostname(session.opaque_ref, _host, _hostname);
else
session.XmlRpcProxy.host_set_hostname(session.opaque_ref, _host ?? "", _hostname ?? "").parse();
}
/// <summary>
/// Set the address field of the given host.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_address">New value to set</param>
public static void set_address(Session session, string _host, string _address)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_address(session.opaque_ref, _host, _address);
else
session.XmlRpcProxy.host_set_address(session.opaque_ref, _host ?? "", _address ?? "").parse();
}
/// <summary>
/// Set the tags field of the given host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_tags">New value to set</param>
public static void set_tags(Session session, string _host, string[] _tags)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_tags(session.opaque_ref, _host, _tags);
else
session.XmlRpcProxy.host_set_tags(session.opaque_ref, _host ?? "", _tags).parse();
}
/// <summary>
/// Add the given value to the tags field of the given host. If the value is already in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">New value to add</param>
public static void add_tags(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_add_tags(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_add_tags(session.opaque_ref, _host ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given value from the tags field of the given host. If the value is not in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">Value to remove</param>
public static void remove_tags(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_remove_tags(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_remove_tags(session.opaque_ref, _host ?? "", _value ?? "").parse();
}
/// <summary>
/// Set the license_server field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_license_server">New value to set</param>
public static void set_license_server(Session session, string _host, Dictionary<string, string> _license_server)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_license_server(session.opaque_ref, _host, _license_server);
else
session.XmlRpcProxy.host_set_license_server(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_license_server)).parse();
}
/// <summary>
/// Add the given key-value pair to the license_server field of the given host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_license_server(Session session, string _host, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_add_to_license_server(session.opaque_ref, _host, _key, _value);
else
session.XmlRpcProxy.host_add_to_license_server(session.opaque_ref, _host ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the license_server field of the given host. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_license_server(Session session, string _host, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_remove_from_license_server(session.opaque_ref, _host, _key);
else
session.XmlRpcProxy.host_remove_from_license_server(session.opaque_ref, _host ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the guest_VCPUs_params field of the given host.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_guest_vcpus_params">New value to set</param>
public static void set_guest_VCPUs_params(Session session, string _host, Dictionary<string, string> _guest_vcpus_params)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_guest_vcpus_params(session.opaque_ref, _host, _guest_vcpus_params);
else
session.XmlRpcProxy.host_set_guest_vcpus_params(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_guest_vcpus_params)).parse();
}
/// <summary>
/// Add the given key-value pair to the guest_VCPUs_params field of the given host.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_guest_VCPUs_params(Session session, string _host, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_add_to_guest_vcpus_params(session.opaque_ref, _host, _key, _value);
else
session.XmlRpcProxy.host_add_to_guest_vcpus_params(session.opaque_ref, _host ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the guest_VCPUs_params field of the given host. If the key is not in that Map, then do nothing.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_guest_VCPUs_params(Session session, string _host, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_remove_from_guest_vcpus_params(session.opaque_ref, _host, _key);
else
session.XmlRpcProxy.host_remove_from_guest_vcpus_params(session.opaque_ref, _host ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the display field of the given host.
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_display">New value to set</param>
public static void set_display(Session session, string _host, host_display _display)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_display(session.opaque_ref, _host, _display);
else
session.XmlRpcProxy.host_set_display(session.opaque_ref, _host ?? "", host_display_helper.ToString(_display)).parse();
}
/// <summary>
/// Puts the host into a state in which no new VMs can be started. Currently active VMs on the host continue to execute.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void disable(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_disable(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_disable(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Puts the host into a state in which no new VMs can be started. Currently active VMs on the host continue to execute.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_disable(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_disable(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_disable(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Puts the host into a state in which new VMs can be started.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void enable(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_enable(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_enable(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Puts the host into a state in which new VMs can be started.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_enable(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_enable(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_enable(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Shutdown the host. (This function can only be called if there are no currently running VMs on the host and it is disabled.)
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void shutdown(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_shutdown(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_shutdown(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Shutdown the host. (This function can only be called if there are no currently running VMs on the host and it is disabled.)
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_shutdown(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_shutdown(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_shutdown(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Reboot the host. (This function can only be called if there are no currently running VMs on the host and it is disabled.)
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void reboot(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_reboot(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_reboot(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Reboot the host. (This function can only be called if there are no currently running VMs on the host and it is disabled.)
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_reboot(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_reboot(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_reboot(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the host xen dmesg.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string dmesg(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_dmesg(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_dmesg(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the host xen dmesg.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_dmesg(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_dmesg(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_dmesg(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the host xen dmesg, and clear the buffer.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string dmesg_clear(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_dmesg_clear(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_dmesg_clear(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the host xen dmesg, and clear the buffer.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_dmesg_clear(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_dmesg_clear(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_dmesg_clear(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the host's log file
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_log(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_log(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_log(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the host's log file
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_get_log(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_log(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_log(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Inject the given string as debugging keys into Xen
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_keys">The keys to send</param>
public static void send_debug_keys(Session session, string _host, string _keys)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_send_debug_keys(session.opaque_ref, _host, _keys);
else
session.XmlRpcProxy.host_send_debug_keys(session.opaque_ref, _host ?? "", _keys ?? "").parse();
}
/// <summary>
/// Inject the given string as debugging keys into Xen
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_keys">The keys to send</param>
public static XenRef<Task> async_send_debug_keys(Session session, string _host, string _keys)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_send_debug_keys(session.opaque_ref, _host, _keys);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_send_debug_keys(session.opaque_ref, _host ?? "", _keys ?? "").parse());
}
/// <summary>
/// Run xen-bugtool --yestoall and upload the output to support
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static void bugreport_upload(Session session, string _host, string _url, Dictionary<string, string> _options)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_bugreport_upload(session.opaque_ref, _host, _url, _options);
else
session.XmlRpcProxy.host_bugreport_upload(session.opaque_ref, _host ?? "", _url ?? "", Maps.convert_to_proxy_string_string(_options)).parse();
}
/// <summary>
/// Run xen-bugtool --yestoall and upload the output to support
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static XenRef<Task> async_bugreport_upload(Session session, string _host, string _url, Dictionary<string, string> _options)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_bugreport_upload(session.opaque_ref, _host, _url, _options);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_bugreport_upload(session.opaque_ref, _host ?? "", _url ?? "", Maps.convert_to_proxy_string_string(_options)).parse());
}
/// <summary>
/// List all supported methods
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static string[] list_methods(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_list_methods(session.opaque_ref);
else
return (string [])session.XmlRpcProxy.host_list_methods(session.opaque_ref).parse();
}
/// <summary>
/// Apply a new license to a host
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_contents">The contents of the license file, base64 encoded</param>
public static void license_apply(Session session, string _host, string _contents)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_license_apply(session.opaque_ref, _host, _contents);
else
session.XmlRpcProxy.host_license_apply(session.opaque_ref, _host ?? "", _contents ?? "").parse();
}
/// <summary>
/// Apply a new license to a host
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_contents">The contents of the license file, base64 encoded</param>
public static XenRef<Task> async_license_apply(Session session, string _host, string _contents)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_license_apply(session.opaque_ref, _host, _contents);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_license_apply(session.opaque_ref, _host ?? "", _contents ?? "").parse());
}
/// <summary>
/// Apply a new license to a host
/// First published in XenServer 6.5 SP1 Hotfix 31.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_contents">The contents of the license file, base64 encoded</param>
public static void license_add(Session session, string _host, string _contents)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_license_add(session.opaque_ref, _host, _contents);
else
session.XmlRpcProxy.host_license_add(session.opaque_ref, _host ?? "", _contents ?? "").parse();
}
/// <summary>
/// Apply a new license to a host
/// First published in XenServer 6.5 SP1 Hotfix 31.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_contents">The contents of the license file, base64 encoded</param>
public static XenRef<Task> async_license_add(Session session, string _host, string _contents)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_license_add(session.opaque_ref, _host, _contents);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_license_add(session.opaque_ref, _host ?? "", _contents ?? "").parse());
}
/// <summary>
/// Remove any license file from the specified host, and switch that host to the unlicensed edition
/// First published in XenServer 6.5 SP1 Hotfix 31.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void license_remove(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_license_remove(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_license_remove(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Remove any license file from the specified host, and switch that host to the unlicensed edition
/// First published in XenServer 6.5 SP1 Hotfix 31.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_license_remove(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_license_remove(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_license_remove(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Destroy specified host record in database
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void destroy(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_destroy(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_destroy(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Destroy specified host record in database
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_destroy(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_destroy(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_destroy(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Attempt to power-on the host (if the capability exists).
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void power_on(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_power_on(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_power_on(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Attempt to power-on the host (if the capability exists).
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_power_on(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_power_on(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_power_on(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// This call disables HA on the local host. This should only be used with extreme care.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_soft">Disable HA temporarily, revert upon host reboot or further changes, idempotent First published in XenServer 7.1.</param>
public static void emergency_ha_disable(Session session, bool _soft)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_emergency_ha_disable(session.opaque_ref, _soft);
else
session.XmlRpcProxy.host_emergency_ha_disable(session.opaque_ref, _soft).parse();
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static List<Data_source> get_data_sources(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_data_sources(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_data_sources(session.opaque_ref, _host ?? "").parse().Select(p => new Data_source(p)).ToList();
}
/// <summary>
/// Start recording the specified data source
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_data_source">The data source to record</param>
public static void record_data_source(Session session, string _host, string _data_source)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_record_data_source(session.opaque_ref, _host, _data_source);
else
session.XmlRpcProxy.host_record_data_source(session.opaque_ref, _host ?? "", _data_source ?? "").parse();
}
/// <summary>
/// Query the latest value of the specified data source
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_data_source">The data source to query</param>
public static double query_data_source(Session session, string _host, string _data_source)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_query_data_source(session.opaque_ref, _host, _data_source);
else
return Convert.ToDouble(session.XmlRpcProxy.host_query_data_source(session.opaque_ref, _host ?? "", _data_source ?? "").parse());
}
/// <summary>
/// Forget the recorded statistics related to the specified data source
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_data_source">The data source whose archives are to be forgotten</param>
public static void forget_data_source_archives(Session session, string _host, string _data_source)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_forget_data_source_archives(session.opaque_ref, _host, _data_source);
else
session.XmlRpcProxy.host_forget_data_source_archives(session.opaque_ref, _host ?? "", _data_source ?? "").parse();
}
/// <summary>
/// Check this host can be evacuated.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void assert_can_evacuate(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_assert_can_evacuate(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_assert_can_evacuate(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Check this host can be evacuated.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_assert_can_evacuate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_assert_can_evacuate(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_assert_can_evacuate(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Return a set of VMs which prevent the host being evacuated, with per-VM error codes
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<XenRef<VM>, string[]> get_vms_which_prevent_evacuation(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_vms_which_prevent_evacuation(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_XenRefVM_string_array(session.XmlRpcProxy.host_get_vms_which_prevent_evacuation(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Return a set of VMs which prevent the host being evacuated, with per-VM error codes
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_get_vms_which_prevent_evacuation(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_vms_which_prevent_evacuation(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_vms_which_prevent_evacuation(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Return a set of VMs which are not co-operating with the host's memory control system
/// First published in XenServer 5.6.
/// Deprecated since XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("XenServer 6.1")]
public static List<XenRef<VM>> get_uncooperative_resident_VMs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_uncooperative_resident_vms(session.opaque_ref, _host);
else
return XenRef<VM>.Create(session.XmlRpcProxy.host_get_uncooperative_resident_vms(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Return a set of VMs which are not co-operating with the host's memory control system
/// First published in XenServer 5.6.
/// Deprecated since XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("XenServer 6.1")]
public static XenRef<Task> async_get_uncooperative_resident_VMs(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_uncooperative_resident_vms(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_uncooperative_resident_vms(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Migrate all VMs off of this host, where possible.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void evacuate(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_evacuate(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_evacuate(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Migrate all VMs off of this host, where possible.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_network">Optional preferred network for migration First published in Unreleased.</param>
public static void evacuate(Session session, string _host, string _network)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_evacuate(session.opaque_ref, _host, _network);
else
session.XmlRpcProxy.host_evacuate(session.opaque_ref, _host ?? "", _network ?? "").parse();
}
/// <summary>
/// Migrate all VMs off of this host, where possible.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_evacuate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_evacuate(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_evacuate(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Migrate all VMs off of this host, where possible.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_network">Optional preferred network for migration First published in Unreleased.</param>
public static XenRef<Task> async_evacuate(Session session, string _host, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_evacuate(session.opaque_ref, _host, _network);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_evacuate(session.opaque_ref, _host ?? "", _network ?? "").parse());
}
/// <summary>
/// Re-configure syslog logging
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void syslog_reconfigure(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_syslog_reconfigure(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_syslog_reconfigure(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Re-configure syslog logging
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_syslog_reconfigure(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_syslog_reconfigure(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_syslog_reconfigure(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Reconfigure the management network interface
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pif">reference to a PIF object corresponding to the management interface</param>
public static void management_reconfigure(Session session, string _pif)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_management_reconfigure(session.opaque_ref, _pif);
else
session.XmlRpcProxy.host_management_reconfigure(session.opaque_ref, _pif ?? "").parse();
}
/// <summary>
/// Reconfigure the management network interface
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pif">reference to a PIF object corresponding to the management interface</param>
public static XenRef<Task> async_management_reconfigure(Session session, string _pif)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_management_reconfigure(session.opaque_ref, _pif);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_management_reconfigure(session.opaque_ref, _pif ?? "").parse());
}
/// <summary>
/// Reconfigure the management network interface. Should only be used if Host.management_reconfigure is impossible because the network configuration is broken.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_interface">name of the interface to use as a management interface</param>
public static void local_management_reconfigure(Session session, string _interface)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_local_management_reconfigure(session.opaque_ref, _interface);
else
session.XmlRpcProxy.host_local_management_reconfigure(session.opaque_ref, _interface ?? "").parse();
}
/// <summary>
/// Disable the management network interface
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static void management_disable(Session session)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_management_disable(session.opaque_ref);
else
session.XmlRpcProxy.host_management_disable(session.opaque_ref).parse();
}
/// <summary>
/// Returns the management interface for the specified host
/// Experimental. First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<PIF> get_management_interface(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_management_interface(session.opaque_ref, _host);
else
return XenRef<PIF>.Create(session.XmlRpcProxy.host_get_management_interface(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Returns the management interface for the specified host
/// Experimental. First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_get_management_interface(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_management_interface(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_management_interface(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_system_status_capabilities(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_system_status_capabilities(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_system_status_capabilities(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Restarts the agent after a 10 second pause. WARNING: this is a dangerous operation. Any operations in progress will be aborted, and unrecoverable data loss may occur. The caller is responsible for ensuring that there are no operations in progress when this method is called.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void restart_agent(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_restart_agent(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_restart_agent(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Restarts the agent after a 10 second pause. WARNING: this is a dangerous operation. Any operations in progress will be aborted, and unrecoverable data loss may occur. The caller is responsible for ensuring that there are no operations in progress when this method is called.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_restart_agent(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_restart_agent(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_restart_agent(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Shuts the agent down after a 10 second pause. WARNING: this is a dangerous operation. Any operations in progress will be aborted, and unrecoverable data loss may occur. The caller is responsible for ensuring that there are no operations in progress when this method is called.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static void shutdown_agent(Session session)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_shutdown_agent(session.opaque_ref);
else
session.XmlRpcProxy.host_shutdown_agent(session.opaque_ref).parse();
}
/// <summary>
/// Sets the host name to the specified string. Both the API and lower-level system hostname are changed immediately.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_hostname">The new host name</param>
public static void set_hostname_live(Session session, string _host, string _hostname)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_hostname_live(session.opaque_ref, _host, _hostname);
else
session.XmlRpcProxy.host_set_hostname_live(session.opaque_ref, _host ?? "", _hostname ?? "").parse();
}
/// <summary>
/// Computes the amount of free memory on the host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long compute_free_memory(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_compute_free_memory(session.opaque_ref, _host);
else
return long.Parse(session.XmlRpcProxy.host_compute_free_memory(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Computes the amount of free memory on the host.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_compute_free_memory(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_compute_free_memory(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_compute_free_memory(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Computes the virtualization memory overhead of a host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static long compute_memory_overhead(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_compute_memory_overhead(session.opaque_ref, _host);
else
return long.Parse(session.XmlRpcProxy.host_compute_memory_overhead(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Computes the virtualization memory overhead of a host.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_compute_memory_overhead(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_compute_memory_overhead(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_compute_memory_overhead(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// This causes the synchronisation of the non-database data (messages, RRDs and so on) stored on the master to be synchronised with the host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void sync_data(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_sync_data(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_sync_data(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// This causes the RRDs to be backed up to the master
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_delay">Delay in seconds from when the call is received to perform the backup</param>
public static void backup_rrds(Session session, string _host, double _delay)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_backup_rrds(session.opaque_ref, _host, _delay);
else
session.XmlRpcProxy.host_backup_rrds(session.opaque_ref, _host ?? "", _delay).parse();
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Blob> create_new_blob(Session session, string _host, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_create_new_blob(session.opaque_ref, _host, _name, _mime_type);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.host_create_new_blob(session.opaque_ref, _host ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Task> async_create_new_blob(Session session, string _host, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_create_new_blob(session.opaque_ref, _host, _name, _mime_type);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_create_new_blob(session.opaque_ref, _host ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create_new_blob(Session session, string _host, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_create_new_blob(session.opaque_ref, _host, _name, _mime_type, _public);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.host_create_new_blob(session.opaque_ref, _host ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Task> async_create_new_blob(Session session, string _host, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_create_new_blob(session.opaque_ref, _host, _name, _mime_type, _public);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_create_new_blob(session.opaque_ref, _host ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Call an API plugin on this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_plugin">The name of the plugin</param>
/// <param name="_fn">The name of the function within the plugin</param>
/// <param name="_args">Arguments for the function</param>
public static string call_plugin(Session session, string _host, string _plugin, string _fn, Dictionary<string, string> _args)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_call_plugin(session.opaque_ref, _host, _plugin, _fn, _args);
else
return session.XmlRpcProxy.host_call_plugin(session.opaque_ref, _host ?? "", _plugin ?? "", _fn ?? "", Maps.convert_to_proxy_string_string(_args)).parse();
}
/// <summary>
/// Call an API plugin on this host
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_plugin">The name of the plugin</param>
/// <param name="_fn">The name of the function within the plugin</param>
/// <param name="_args">Arguments for the function</param>
public static XenRef<Task> async_call_plugin(Session session, string _host, string _plugin, string _fn, Dictionary<string, string> _args)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_call_plugin(session.opaque_ref, _host, _plugin, _fn, _args);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_call_plugin(session.opaque_ref, _host ?? "", _plugin ?? "", _fn ?? "", Maps.convert_to_proxy_string_string(_args)).parse());
}
/// <summary>
/// Return true if the extension is available on the host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name of the API call</param>
public static bool has_extension(Session session, string _host, string _name)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_has_extension(session.opaque_ref, _host, _name);
else
return (bool)session.XmlRpcProxy.host_has_extension(session.opaque_ref, _host ?? "", _name ?? "").parse();
}
/// <summary>
/// Return true if the extension is available on the host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_name">The name of the API call</param>
public static XenRef<Task> async_has_extension(Session session, string _host, string _name)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_has_extension(session.opaque_ref, _host, _name);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_has_extension(session.opaque_ref, _host ?? "", _name ?? "").parse());
}
/// <summary>
/// Call an API extension on this host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_call">Rpc call for the extension</param>
public static string call_extension(Session session, string _host, string _call)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_call_extension(session.opaque_ref, _host, _call);
else
return session.XmlRpcProxy.host_call_extension(session.opaque_ref, _host ?? "", _call ?? "").parse();
}
/// <summary>
/// This call queries the host's clock for the current time
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static DateTime get_servertime(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_servertime(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_servertime(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// This call queries the host's clock for the current time in the host's local timezone
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static DateTime get_server_localtime(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_server_localtime(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_server_localtime(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// This call enables external authentication on a host
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_config">A list of key-values containing the configuration data</param>
/// <param name="_service_name">The name of the service</param>
/// <param name="_auth_type">The type of authentication (e.g. AD for Active Directory)</param>
public static void enable_external_auth(Session session, string _host, Dictionary<string, string> _config, string _service_name, string _auth_type)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_enable_external_auth(session.opaque_ref, _host, _config, _service_name, _auth_type);
else
session.XmlRpcProxy.host_enable_external_auth(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_config), _service_name ?? "", _auth_type ?? "").parse();
}
/// <summary>
/// This call disables external authentication on the local host
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_config">Optional parameters as a list of key-values containing the configuration data</param>
public static void disable_external_auth(Session session, string _host, Dictionary<string, string> _config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_disable_external_auth(session.opaque_ref, _host, _config);
else
session.XmlRpcProxy.host_disable_external_auth(session.opaque_ref, _host ?? "", Maps.convert_to_proxy_string_string(_config)).parse();
}
/// <summary>
/// Retrieves recommended host migrations to perform when evacuating the host from the wlb server. If a VM cannot be migrated from the host the reason is listed instead of a recommendation.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static Dictionary<XenRef<VM>, string[]> retrieve_wlb_evacuate_recommendations(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_retrieve_wlb_evacuate_recommendations(session.opaque_ref, _host);
else
return Maps.convert_from_proxy_XenRefVM_string_array(session.XmlRpcProxy.host_retrieve_wlb_evacuate_recommendations(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Retrieves recommended host migrations to perform when evacuating the host from the wlb server. If a VM cannot be migrated from the host the reason is listed instead of a recommendation.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_retrieve_wlb_evacuate_recommendations(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_retrieve_wlb_evacuate_recommendations(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_retrieve_wlb_evacuate_recommendations(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Get the installed server public TLS certificate.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static string get_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_server_certificate(session.opaque_ref, _host);
else
return session.XmlRpcProxy.host_get_server_certificate(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Get the installed server public TLS certificate.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_get_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_server_certificate(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_server_certificate(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Replace the internal self-signed host certficate with a new one.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void refresh_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_refresh_server_certificate(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_refresh_server_certificate(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Replace the internal self-signed host certficate with a new one.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_refresh_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_refresh_server_certificate(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_refresh_server_certificate(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Install the TLS server certificate.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_certificate">The server certificate, in PEM form</param>
/// <param name="_private_key">The unencrypted private key used to sign the certificate, in PKCS#8 form</param>
/// <param name="_certificate_chain">The certificate chain, in PEM form</param>
public static void install_server_certificate(Session session, string _host, string _certificate, string _private_key, string _certificate_chain)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_install_server_certificate(session.opaque_ref, _host, _certificate, _private_key, _certificate_chain);
else
session.XmlRpcProxy.host_install_server_certificate(session.opaque_ref, _host ?? "", _certificate ?? "", _private_key ?? "", _certificate_chain ?? "").parse();
}
/// <summary>
/// Install the TLS server certificate.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_certificate">The server certificate, in PEM form</param>
/// <param name="_private_key">The unencrypted private key used to sign the certificate, in PKCS#8 form</param>
/// <param name="_certificate_chain">The certificate chain, in PEM form</param>
public static XenRef<Task> async_install_server_certificate(Session session, string _host, string _certificate, string _private_key, string _certificate_chain)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_install_server_certificate(session.opaque_ref, _host, _certificate, _private_key, _certificate_chain);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_install_server_certificate(session.opaque_ref, _host ?? "", _certificate ?? "", _private_key ?? "", _certificate_chain ?? "").parse());
}
/// <summary>
/// Delete the current TLS server certificate and replace by a new, self-signed one. This should only be used with extreme care.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
public static void emergency_reset_server_certificate(Session session)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_emergency_reset_server_certificate(session.opaque_ref);
else
session.XmlRpcProxy.host_emergency_reset_server_certificate(session.opaque_ref).parse();
}
/// <summary>
/// Delete the current TLS server certificate and replace by a new, self-signed one. This should only be used with extreme care.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void reset_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_reset_server_certificate(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_reset_server_certificate(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Delete the current TLS server certificate and replace by a new, self-signed one. This should only be used with extreme care.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_reset_server_certificate(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_reset_server_certificate(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_reset_server_certificate(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Change to another edition, or reactivate the current edition after a license has expired. This may be subject to the successful checkout of an appropriate license.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_edition">The requested edition</param>
public static void apply_edition(Session session, string _host, string _edition)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_apply_edition(session.opaque_ref, _host, _edition);
else
session.XmlRpcProxy.host_apply_edition(session.opaque_ref, _host ?? "", _edition ?? "").parse();
}
/// <summary>
/// Change to another edition, or reactivate the current edition after a license has expired. This may be subject to the successful checkout of an appropriate license.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_edition">The requested edition</param>
/// <param name="_force">Update the license params even if the apply call fails First published in XenServer 6.2.</param>
public static void apply_edition(Session session, string _host, string _edition, bool _force)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_apply_edition(session.opaque_ref, _host, _edition, _force);
else
session.XmlRpcProxy.host_apply_edition(session.opaque_ref, _host ?? "", _edition ?? "", _force).parse();
}
/// <summary>
/// Refresh the list of installed Supplemental Packs.
/// First published in XenServer 5.6.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("XenServer 7.1")]
public static void refresh_pack_info(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_refresh_pack_info(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_refresh_pack_info(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Refresh the list of installed Supplemental Packs.
/// First published in XenServer 5.6.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_refresh_pack_info(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_refresh_pack_info(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_refresh_pack_info(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Set the power-on-mode, host, user and password
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_power_on_mode">power-on-mode can be empty, wake-on-lan, DRAC or other</param>
/// <param name="_power_on_config">Power on config</param>
public static void set_power_on_mode(Session session, string _host, string _power_on_mode, Dictionary<string, string> _power_on_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_power_on_mode(session.opaque_ref, _host, _power_on_mode, _power_on_config);
else
session.XmlRpcProxy.host_set_power_on_mode(session.opaque_ref, _host ?? "", _power_on_mode ?? "", Maps.convert_to_proxy_string_string(_power_on_config)).parse();
}
/// <summary>
/// Set the power-on-mode, host, user and password
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_power_on_mode">power-on-mode can be empty, wake-on-lan, DRAC or other</param>
/// <param name="_power_on_config">Power on config</param>
public static XenRef<Task> async_set_power_on_mode(Session session, string _host, string _power_on_mode, Dictionary<string, string> _power_on_config)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_power_on_mode(session.opaque_ref, _host, _power_on_mode, _power_on_config);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_power_on_mode(session.opaque_ref, _host ?? "", _power_on_mode ?? "", Maps.convert_to_proxy_string_string(_power_on_config)).parse());
}
/// <summary>
/// Set the CPU features to be used after a reboot, if the given features string is valid.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_features">The features string (32 hexadecimal digits)</param>
public static void set_cpu_features(Session session, string _host, string _features)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_cpu_features(session.opaque_ref, _host, _features);
else
session.XmlRpcProxy.host_set_cpu_features(session.opaque_ref, _host ?? "", _features ?? "").parse();
}
/// <summary>
/// Remove the feature mask, such that after a reboot all features of the CPU are enabled.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void reset_cpu_features(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_reset_cpu_features(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_reset_cpu_features(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Enable the use of a local SR for caching purposes
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_sr">The SR to use as a local cache</param>
public static void enable_local_storage_caching(Session session, string _host, string _sr)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_enable_local_storage_caching(session.opaque_ref, _host, _sr);
else
session.XmlRpcProxy.host_enable_local_storage_caching(session.opaque_ref, _host ?? "", _sr ?? "").parse();
}
/// <summary>
/// Disable the use of a local SR for caching purposes
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void disable_local_storage_caching(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_disable_local_storage_caching(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_disable_local_storage_caching(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Prepare to receive a VM, returning a token which can be passed to VM.migrate.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_network">The network through which migration traffic should be received.</param>
/// <param name="_options">Extra configuration operations</param>
public static Dictionary<string, string> migrate_receive(Session session, string _host, string _network, Dictionary<string, string> _options)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_migrate_receive(session.opaque_ref, _host, _network, _options);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_migrate_receive(session.opaque_ref, _host ?? "", _network ?? "", Maps.convert_to_proxy_string_string(_options)).parse());
}
/// <summary>
/// Prepare to receive a VM, returning a token which can be passed to VM.migrate.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_network">The network through which migration traffic should be received.</param>
/// <param name="_options">Extra configuration operations</param>
public static XenRef<Task> async_migrate_receive(Session session, string _host, string _network, Dictionary<string, string> _options)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_migrate_receive(session.opaque_ref, _host, _network, _options);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_migrate_receive(session.opaque_ref, _host ?? "", _network ?? "", Maps.convert_to_proxy_string_string(_options)).parse());
}
/// <summary>
/// Declare that a host is dead. This is a dangerous operation, and should only be called if the administrator is absolutely sure the host is definitely dead
/// First published in XenServer 6.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static void declare_dead(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_declare_dead(session.opaque_ref, _host);
else
session.XmlRpcProxy.host_declare_dead(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
/// Declare that a host is dead. This is a dangerous operation, and should only be called if the administrator is absolutely sure the host is definitely dead
/// First published in XenServer 6.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_declare_dead(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_declare_dead(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_declare_dead(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Enable console output to the physical display device next time this host boots
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static host_display enable_display(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_enable_display(session.opaque_ref, _host);
else
return (host_display)Helper.EnumParseDefault(typeof(host_display), (string)session.XmlRpcProxy.host_enable_display(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Enable console output to the physical display device next time this host boots
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_enable_display(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_enable_display(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_enable_display(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Disable console output to the physical display device next time this host boots
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static host_display disable_display(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_disable_display(session.opaque_ref, _host);
else
return (host_display)Helper.EnumParseDefault(typeof(host_display), (string)session.XmlRpcProxy.host_disable_display(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Disable console output to the physical display device next time this host boots
/// First published in XenServer 6.5 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_disable_display(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_disable_display(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_disable_display(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Enable/disable SSLv3 for interoperability with older server versions. When this is set to a different value, the host immediately restarts its SSL/TLS listening service; typically this takes less than a second but existing connections to it will be broken. API login sessions will remain valid.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">True to allow SSLv3 and ciphersuites as used in old XenServer versions</param>
public static void set_ssl_legacy(Session session, string _host, bool _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_ssl_legacy(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_set_ssl_legacy(session.opaque_ref, _host ?? "", _value).parse();
}
/// <summary>
/// Enable/disable SSLv3 for interoperability with older server versions. When this is set to a different value, the host immediately restarts its SSL/TLS listening service; typically this takes less than a second but existing connections to it will be broken. API login sessions will remain valid.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">True to allow SSLv3 and ciphersuites as used in old XenServer versions</param>
public static XenRef<Task> async_set_ssl_legacy(Session session, string _host, bool _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_ssl_legacy(session.opaque_ref, _host, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_ssl_legacy(session.opaque_ref, _host ?? "", _value).parse());
}
/// <summary>
/// Sets the initiator IQN for the host
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The value to which the IQN should be set</param>
public static void set_iscsi_iqn(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_iscsi_iqn(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_set_iscsi_iqn(session.opaque_ref, _host ?? "", _value ?? "").parse();
}
/// <summary>
/// Sets the initiator IQN for the host
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The value to which the IQN should be set</param>
public static XenRef<Task> async_set_iscsi_iqn(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_iscsi_iqn(session.opaque_ref, _host, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_iscsi_iqn(session.opaque_ref, _host ?? "", _value ?? "").parse());
}
/// <summary>
/// Specifies whether multipathing is enabled
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">Whether multipathing should be enabled</param>
public static void set_multipathing(Session session, string _host, bool _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_multipathing(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_set_multipathing(session.opaque_ref, _host ?? "", _value).parse();
}
/// <summary>
/// Specifies whether multipathing is enabled
/// First published in XenServer 7.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">Whether multipathing should be enabled</param>
public static XenRef<Task> async_set_multipathing(Session session, string _host, bool _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_multipathing(session.opaque_ref, _host, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_multipathing(session.opaque_ref, _host ?? "", _value).parse());
}
/// <summary>
/// Sets the UEFI certificates on a host
/// First published in Citrix Hypervisor 8.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The certificates to apply to a host</param>
public static void set_uefi_certificates(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_uefi_certificates(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_set_uefi_certificates(session.opaque_ref, _host ?? "", _value ?? "").parse();
}
/// <summary>
/// Sets the UEFI certificates on a host
/// First published in Citrix Hypervisor 8.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The certificates to apply to a host</param>
public static XenRef<Task> async_set_uefi_certificates(Session session, string _host, string _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_uefi_certificates(session.opaque_ref, _host, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_uefi_certificates(session.opaque_ref, _host ?? "", _value ?? "").parse());
}
/// <summary>
/// Sets xen's sched-gran on a host. See: https://xenbits.xen.org/docs/unstable/misc/xen-command-line.html#sched-gran-x86
/// Experimental. First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The sched-gran to apply to a host</param>
public static void set_sched_gran(Session session, string _host, host_sched_gran _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_set_sched_gran(session.opaque_ref, _host, _value);
else
session.XmlRpcProxy.host_set_sched_gran(session.opaque_ref, _host ?? "", host_sched_gran_helper.ToString(_value)).parse();
}
/// <summary>
/// Sets xen's sched-gran on a host. See: https://xenbits.xen.org/docs/unstable/misc/xen-command-line.html#sched-gran-x86
/// Experimental. First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_value">The sched-gran to apply to a host</param>
public static XenRef<Task> async_set_sched_gran(Session session, string _host, host_sched_gran _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_set_sched_gran(session.opaque_ref, _host, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_set_sched_gran(session.opaque_ref, _host ?? "", host_sched_gran_helper.ToString(_value)).parse());
}
/// <summary>
/// Gets xen's sched-gran on a host
/// Experimental. First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static host_sched_gran get_sched_gran(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_sched_gran(session.opaque_ref, _host);
else
return (host_sched_gran)Helper.EnumParseDefault(typeof(host_sched_gran), (string)session.XmlRpcProxy.host_get_sched_gran(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Gets xen's sched-gran on a host
/// Experimental. First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
public static XenRef<Task> async_get_sched_gran(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_get_sched_gran(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_get_sched_gran(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
/// Disable TLS verification for this host only
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
public static void emergency_disable_tls_verification(Session session)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_emergency_disable_tls_verification(session.opaque_ref);
else
session.XmlRpcProxy.host_emergency_disable_tls_verification(session.opaque_ref).parse();
}
/// <summary>
/// Reenable TLS verification for this host only
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
public static void emergency_reenable_tls_verification(Session session)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_emergency_reenable_tls_verification(session.opaque_ref);
else
session.XmlRpcProxy.host_emergency_reenable_tls_verification(session.opaque_ref).parse();
}
/// <summary>
/// apply updates from current enabled repository on a host
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_hash">The hash of updateinfo to be applied which is returned by previous pool.sync_udpates</param>
public static void apply_updates(Session session, string _host, string _hash)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_apply_updates(session.opaque_ref, _host, _hash);
else
session.XmlRpcProxy.host_apply_updates(session.opaque_ref, _host ?? "", _hash ?? "").parse();
}
/// <summary>
/// apply updates from current enabled repository on a host
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The opaque_ref of the given host</param>
/// <param name="_hash">The hash of updateinfo to be applied which is returned by previous pool.sync_udpates</param>
public static XenRef<Task> async_apply_updates(Session session, string _host, string _hash)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_host_apply_updates(session.opaque_ref, _host, _hash);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_host_apply_updates(session.opaque_ref, _host ?? "", _hash ?? "").parse());
}
/// <summary>
/// Return a list of all the hosts known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Host>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_all(session.opaque_ref);
else
return XenRef<Host>.Create(session.XmlRpcProxy.host_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the host Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host>, Host> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_get_all_records(session.opaque_ref);
else
return XenRef<Host>.Create<Proxy_Host>(session.XmlRpcProxy.host_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Virtualization memory overhead (bytes).
/// </summary>
public virtual long memory_overhead
{
get { return _memory_overhead; }
set
{
if (!Helper.AreEqual(value, _memory_overhead))
{
_memory_overhead = value;
NotifyPropertyChanged("memory_overhead");
}
}
}
private long _memory_overhead = 0;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<host_allowed_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<host_allowed_operations> _allowed_operations = new List<host_allowed_operations>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, host_allowed_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, host_allowed_operations> _current_operations = new Dictionary<string, host_allowed_operations>() {};
/// <summary>
/// major version number
/// </summary>
public virtual long API_version_major
{
get { return _API_version_major; }
set
{
if (!Helper.AreEqual(value, _API_version_major))
{
_API_version_major = value;
NotifyPropertyChanged("API_version_major");
}
}
}
private long _API_version_major;
/// <summary>
/// minor version number
/// </summary>
public virtual long API_version_minor
{
get { return _API_version_minor; }
set
{
if (!Helper.AreEqual(value, _API_version_minor))
{
_API_version_minor = value;
NotifyPropertyChanged("API_version_minor");
}
}
}
private long _API_version_minor;
/// <summary>
/// identification of vendor
/// </summary>
public virtual string API_version_vendor
{
get { return _API_version_vendor; }
set
{
if (!Helper.AreEqual(value, _API_version_vendor))
{
_API_version_vendor = value;
NotifyPropertyChanged("API_version_vendor");
}
}
}
private string _API_version_vendor = "";
/// <summary>
/// details of vendor implementation
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> API_version_vendor_implementation
{
get { return _API_version_vendor_implementation; }
set
{
if (!Helper.AreEqual(value, _API_version_vendor_implementation))
{
_API_version_vendor_implementation = value;
NotifyPropertyChanged("API_version_vendor_implementation");
}
}
}
private Dictionary<string, string> _API_version_vendor_implementation = new Dictionary<string, string>() {};
/// <summary>
/// True if the host is currently enabled
/// </summary>
public virtual bool enabled
{
get { return _enabled; }
set
{
if (!Helper.AreEqual(value, _enabled))
{
_enabled = value;
NotifyPropertyChanged("enabled");
}
}
}
private bool _enabled;
/// <summary>
/// version strings
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> software_version
{
get { return _software_version; }
set
{
if (!Helper.AreEqual(value, _software_version))
{
_software_version = value;
NotifyPropertyChanged("software_version");
}
}
}
private Dictionary<string, string> _software_version = new Dictionary<string, string>() {};
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Xen capabilities
/// </summary>
public virtual string[] capabilities
{
get { return _capabilities; }
set
{
if (!Helper.AreEqual(value, _capabilities))
{
_capabilities = value;
NotifyPropertyChanged("capabilities");
}
}
}
private string[] _capabilities = {};
/// <summary>
/// The CPU configuration on this host. May contain keys such as "nr_nodes", "sockets_per_node", "cores_per_socket", or "threads_per_core"
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> cpu_configuration
{
get { return _cpu_configuration; }
set
{
if (!Helper.AreEqual(value, _cpu_configuration))
{
_cpu_configuration = value;
NotifyPropertyChanged("cpu_configuration");
}
}
}
private Dictionary<string, string> _cpu_configuration = new Dictionary<string, string>() {};
/// <summary>
/// Scheduler policy currently in force on this host
/// </summary>
public virtual string sched_policy
{
get { return _sched_policy; }
set
{
if (!Helper.AreEqual(value, _sched_policy))
{
_sched_policy = value;
NotifyPropertyChanged("sched_policy");
}
}
}
private string _sched_policy = "";
/// <summary>
/// a list of the bootloaders installed on the machine
/// </summary>
public virtual string[] supported_bootloaders
{
get { return _supported_bootloaders; }
set
{
if (!Helper.AreEqual(value, _supported_bootloaders))
{
_supported_bootloaders = value;
NotifyPropertyChanged("supported_bootloaders");
}
}
}
private string[] _supported_bootloaders = {};
/// <summary>
/// list of VMs currently resident on host
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VM>))]
public virtual List<XenRef<VM>> resident_VMs
{
get { return _resident_VMs; }
set
{
if (!Helper.AreEqual(value, _resident_VMs))
{
_resident_VMs = value;
NotifyPropertyChanged("resident_VMs");
}
}
}
private List<XenRef<VM>> _resident_VMs = new List<XenRef<VM>>() {};
/// <summary>
/// logging configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> logging
{
get { return _logging; }
set
{
if (!Helper.AreEqual(value, _logging))
{
_logging = value;
NotifyPropertyChanged("logging");
}
}
}
private Dictionary<string, string> _logging = new Dictionary<string, string>() {};
/// <summary>
/// physical network interfaces
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PIF>))]
public virtual List<XenRef<PIF>> PIFs
{
get { return _PIFs; }
set
{
if (!Helper.AreEqual(value, _PIFs))
{
_PIFs = value;
NotifyPropertyChanged("PIFs");
}
}
}
private List<XenRef<PIF>> _PIFs = new List<XenRef<PIF>>() {};
/// <summary>
/// The SR in which VDIs for suspend images are created
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> suspend_image_sr
{
get { return _suspend_image_sr; }
set
{
if (!Helper.AreEqual(value, _suspend_image_sr))
{
_suspend_image_sr = value;
NotifyPropertyChanged("suspend_image_sr");
}
}
}
private XenRef<SR> _suspend_image_sr = new XenRef<SR>(Helper.NullOpaqueRef);
/// <summary>
/// The SR in which VDIs for crash dumps are created
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> crash_dump_sr
{
get { return _crash_dump_sr; }
set
{
if (!Helper.AreEqual(value, _crash_dump_sr))
{
_crash_dump_sr = value;
NotifyPropertyChanged("crash_dump_sr");
}
}
}
private XenRef<SR> _crash_dump_sr = new XenRef<SR>(Helper.NullOpaqueRef);
/// <summary>
/// Set of host crash dumps
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host_crashdump>))]
public virtual List<XenRef<Host_crashdump>> crashdumps
{
get { return _crashdumps; }
set
{
if (!Helper.AreEqual(value, _crashdumps))
{
_crashdumps = value;
NotifyPropertyChanged("crashdumps");
}
}
}
private List<XenRef<Host_crashdump>> _crashdumps = new List<XenRef<Host_crashdump>>() {};
/// <summary>
/// Set of host patches
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host_patch>))]
public virtual List<XenRef<Host_patch>> patches
{
get { return _patches; }
set
{
if (!Helper.AreEqual(value, _patches))
{
_patches = value;
NotifyPropertyChanged("patches");
}
}
}
private List<XenRef<Host_patch>> _patches = new List<XenRef<Host_patch>>() {};
/// <summary>
/// Set of updates
/// First published in XenServer 7.1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Pool_update>))]
public virtual List<XenRef<Pool_update>> updates
{
get { return _updates; }
set
{
if (!Helper.AreEqual(value, _updates))
{
_updates = value;
NotifyPropertyChanged("updates");
}
}
}
private List<XenRef<Pool_update>> _updates = new List<XenRef<Pool_update>>() {};
/// <summary>
/// physical blockdevices
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PBD>))]
public virtual List<XenRef<PBD>> PBDs
{
get { return _PBDs; }
set
{
if (!Helper.AreEqual(value, _PBDs))
{
_PBDs = value;
NotifyPropertyChanged("PBDs");
}
}
}
private List<XenRef<PBD>> _PBDs = new List<XenRef<PBD>>() {};
/// <summary>
/// The physical CPUs on this host
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host_cpu>))]
public virtual List<XenRef<Host_cpu>> host_CPUs
{
get { return _host_CPUs; }
set
{
if (!Helper.AreEqual(value, _host_CPUs))
{
_host_CPUs = value;
NotifyPropertyChanged("host_CPUs");
}
}
}
private List<XenRef<Host_cpu>> _host_CPUs = new List<XenRef<Host_cpu>>() {};
/// <summary>
/// Details about the physical CPUs on this host
/// First published in XenServer 5.6.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> cpu_info
{
get { return _cpu_info; }
set
{
if (!Helper.AreEqual(value, _cpu_info))
{
_cpu_info = value;
NotifyPropertyChanged("cpu_info");
}
}
}
private Dictionary<string, string> _cpu_info = new Dictionary<string, string>() {};
/// <summary>
/// The hostname of this host
/// </summary>
public virtual string hostname
{
get { return _hostname; }
set
{
if (!Helper.AreEqual(value, _hostname))
{
_hostname = value;
NotifyPropertyChanged("hostname");
}
}
}
private string _hostname = "";
/// <summary>
/// The address by which this host can be contacted from any other host in the pool
/// </summary>
public virtual string address
{
get { return _address; }
set
{
if (!Helper.AreEqual(value, _address))
{
_address = value;
NotifyPropertyChanged("address");
}
}
}
private string _address = "";
/// <summary>
/// metrics associated with this host
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host_metrics>))]
public virtual XenRef<Host_metrics> metrics
{
get { return _metrics; }
set
{
if (!Helper.AreEqual(value, _metrics))
{
_metrics = value;
NotifyPropertyChanged("metrics");
}
}
}
private XenRef<Host_metrics> _metrics = new XenRef<Host_metrics>(Helper.NullOpaqueRef);
/// <summary>
/// State of the current license
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> license_params
{
get { return _license_params; }
set
{
if (!Helper.AreEqual(value, _license_params))
{
_license_params = value;
NotifyPropertyChanged("license_params");
}
}
}
private Dictionary<string, string> _license_params = new Dictionary<string, string>() {};
/// <summary>
/// The set of statefiles accessible from this host
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] ha_statefiles
{
get { return _ha_statefiles; }
set
{
if (!Helper.AreEqual(value, _ha_statefiles))
{
_ha_statefiles = value;
NotifyPropertyChanged("ha_statefiles");
}
}
}
private string[] _ha_statefiles = {};
/// <summary>
/// The set of hosts visible via the network from this host
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] ha_network_peers
{
get { return _ha_network_peers; }
set
{
if (!Helper.AreEqual(value, _ha_network_peers))
{
_ha_network_peers = value;
NotifyPropertyChanged("ha_network_peers");
}
}
}
private string[] _ha_network_peers = {};
/// <summary>
/// Binary blobs associated with this host
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringXenRefMapConverter<Blob>))]
public virtual Dictionary<string, XenRef<Blob>> blobs
{
get { return _blobs; }
set
{
if (!Helper.AreEqual(value, _blobs))
{
_blobs = value;
NotifyPropertyChanged("blobs");
}
}
}
private Dictionary<string, XenRef<Blob>> _blobs = new Dictionary<string, XenRef<Blob>>() {};
/// <summary>
/// user-specified tags for categorization purposes
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] tags
{
get { return _tags; }
set
{
if (!Helper.AreEqual(value, _tags))
{
_tags = value;
NotifyPropertyChanged("tags");
}
}
}
private string[] _tags = {};
/// <summary>
/// type of external authentication service configured; empty if none configured.
/// First published in XenServer 5.5.
/// </summary>
public virtual string external_auth_type
{
get { return _external_auth_type; }
set
{
if (!Helper.AreEqual(value, _external_auth_type))
{
_external_auth_type = value;
NotifyPropertyChanged("external_auth_type");
}
}
}
private string _external_auth_type = "";
/// <summary>
/// name of external authentication service configured; empty if none configured.
/// First published in XenServer 5.5.
/// </summary>
public virtual string external_auth_service_name
{
get { return _external_auth_service_name; }
set
{
if (!Helper.AreEqual(value, _external_auth_service_name))
{
_external_auth_service_name = value;
NotifyPropertyChanged("external_auth_service_name");
}
}
}
private string _external_auth_service_name = "";
/// <summary>
/// configuration specific to external authentication service
/// First published in XenServer 5.5.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> external_auth_configuration
{
get { return _external_auth_configuration; }
set
{
if (!Helper.AreEqual(value, _external_auth_configuration))
{
_external_auth_configuration = value;
NotifyPropertyChanged("external_auth_configuration");
}
}
}
private Dictionary<string, string> _external_auth_configuration = new Dictionary<string, string>() {};
/// <summary>
/// Product edition
/// First published in XenServer 5.6.
/// </summary>
public virtual string edition
{
get { return _edition; }
set
{
if (!Helper.AreEqual(value, _edition))
{
_edition = value;
NotifyPropertyChanged("edition");
}
}
}
private string _edition = "";
/// <summary>
/// Contact information of the license server
/// First published in XenServer 5.6.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> license_server
{
get { return _license_server; }
set
{
if (!Helper.AreEqual(value, _license_server))
{
_license_server = value;
NotifyPropertyChanged("license_server");
}
}
}
private Dictionary<string, string> _license_server = new Dictionary<string, string>() {{"address", "localhost"}, {"port", "27000"}};
/// <summary>
/// BIOS strings
/// First published in XenServer 5.6.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> bios_strings
{
get { return _bios_strings; }
set
{
if (!Helper.AreEqual(value, _bios_strings))
{
_bios_strings = value;
NotifyPropertyChanged("bios_strings");
}
}
}
private Dictionary<string, string> _bios_strings = new Dictionary<string, string>() {};
/// <summary>
/// The power on mode
/// First published in XenServer 5.6.
/// </summary>
public virtual string power_on_mode
{
get { return _power_on_mode; }
set
{
if (!Helper.AreEqual(value, _power_on_mode))
{
_power_on_mode = value;
NotifyPropertyChanged("power_on_mode");
}
}
}
private string _power_on_mode = "";
/// <summary>
/// The power on config
/// First published in XenServer 5.6.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> power_on_config
{
get { return _power_on_config; }
set
{
if (!Helper.AreEqual(value, _power_on_config))
{
_power_on_config = value;
NotifyPropertyChanged("power_on_config");
}
}
}
private Dictionary<string, string> _power_on_config = new Dictionary<string, string>() {};
/// <summary>
/// The SR that is used as a local cache
/// First published in XenServer 5.6 FP1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> local_cache_sr
{
get { return _local_cache_sr; }
set
{
if (!Helper.AreEqual(value, _local_cache_sr))
{
_local_cache_sr = value;
NotifyPropertyChanged("local_cache_sr");
}
}
}
private XenRef<SR> _local_cache_sr = new XenRef<SR>("OpaqueRef:NULL");
/// <summary>
/// Information about chipset features
/// First published in XenServer 6.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> chipset_info
{
get { return _chipset_info; }
set
{
if (!Helper.AreEqual(value, _chipset_info))
{
_chipset_info = value;
NotifyPropertyChanged("chipset_info");
}
}
}
private Dictionary<string, string> _chipset_info = new Dictionary<string, string>() {};
/// <summary>
/// List of PCI devices in the host
/// First published in XenServer 6.0.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PCI>))]
public virtual List<XenRef<PCI>> PCIs
{
get { return _PCIs; }
set
{
if (!Helper.AreEqual(value, _PCIs))
{
_PCIs = value;
NotifyPropertyChanged("PCIs");
}
}
}
private List<XenRef<PCI>> _PCIs = new List<XenRef<PCI>>() {};
/// <summary>
/// List of physical GPUs in the host
/// First published in XenServer 6.0.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> PGPUs
{
get { return _PGPUs; }
set
{
if (!Helper.AreEqual(value, _PGPUs))
{
_PGPUs = value;
NotifyPropertyChanged("PGPUs");
}
}
}
private List<XenRef<PGPU>> _PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of physical USBs in the host
/// First published in XenServer 7.3.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PUSB>))]
public virtual List<XenRef<PUSB>> PUSBs
{
get { return _PUSBs; }
set
{
if (!Helper.AreEqual(value, _PUSBs))
{
_PUSBs = value;
NotifyPropertyChanged("PUSBs");
}
}
}
private List<XenRef<PUSB>> _PUSBs = new List<XenRef<PUSB>>() {};
/// <summary>
/// Allow SSLv3 protocol and ciphersuites as used by older server versions. This controls both incoming and outgoing connections. When this is set to a different value, the host immediately restarts its SSL/TLS listening service; typically this takes less than a second but existing connections to it will be broken. API login sessions will remain valid.
/// First published in XenServer 7.0.
/// </summary>
public virtual bool ssl_legacy
{
get { return _ssl_legacy; }
set
{
if (!Helper.AreEqual(value, _ssl_legacy))
{
_ssl_legacy = value;
NotifyPropertyChanged("ssl_legacy");
}
}
}
private bool _ssl_legacy = true;
/// <summary>
/// VCPUs params to apply to all resident guests
/// First published in XenServer 6.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> guest_VCPUs_params
{
get { return _guest_VCPUs_params; }
set
{
if (!Helper.AreEqual(value, _guest_VCPUs_params))
{
_guest_VCPUs_params = value;
NotifyPropertyChanged("guest_VCPUs_params");
}
}
}
private Dictionary<string, string> _guest_VCPUs_params = new Dictionary<string, string>() {};
/// <summary>
/// indicates whether the host is configured to output its console to a physical display device
/// First published in XenServer 6.5 SP1.
/// </summary>
[JsonConverter(typeof(host_displayConverter))]
public virtual host_display display
{
get { return _display; }
set
{
if (!Helper.AreEqual(value, _display))
{
_display = value;
NotifyPropertyChanged("display");
}
}
}
private host_display _display = host_display.enabled;
/// <summary>
/// The set of versions of the virtual hardware platform that the host can offer to its guests
/// First published in XenServer 6.5 SP1.
/// </summary>
public virtual long[] virtual_hardware_platform_versions
{
get { return _virtual_hardware_platform_versions; }
set
{
if (!Helper.AreEqual(value, _virtual_hardware_platform_versions))
{
_virtual_hardware_platform_versions = value;
NotifyPropertyChanged("virtual_hardware_platform_versions");
}
}
}
private long[] _virtual_hardware_platform_versions = {0};
/// <summary>
/// The control domain (domain 0)
/// First published in XenServer 7.1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<VM>))]
public virtual XenRef<VM> control_domain
{
get { return _control_domain; }
set
{
if (!Helper.AreEqual(value, _control_domain))
{
_control_domain = value;
NotifyPropertyChanged("control_domain");
}
}
}
private XenRef<VM> _control_domain = new XenRef<VM>("OpaqueRef:NULL");
/// <summary>
/// List of updates which require reboot
/// First published in XenServer 7.1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Pool_update>))]
public virtual List<XenRef<Pool_update>> updates_requiring_reboot
{
get { return _updates_requiring_reboot; }
set
{
if (!Helper.AreEqual(value, _updates_requiring_reboot))
{
_updates_requiring_reboot = value;
NotifyPropertyChanged("updates_requiring_reboot");
}
}
}
private List<XenRef<Pool_update>> _updates_requiring_reboot = new List<XenRef<Pool_update>>() {};
/// <summary>
/// List of features available on this host
/// First published in XenServer 7.2.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Feature>))]
public virtual List<XenRef<Feature>> features
{
get { return _features; }
set
{
if (!Helper.AreEqual(value, _features))
{
_features = value;
NotifyPropertyChanged("features");
}
}
}
private List<XenRef<Feature>> _features = new List<XenRef<Feature>>() {};
/// <summary>
/// The initiator IQN for the host
/// First published in XenServer 7.5.
/// </summary>
public virtual string iscsi_iqn
{
get { return _iscsi_iqn; }
set
{
if (!Helper.AreEqual(value, _iscsi_iqn))
{
_iscsi_iqn = value;
NotifyPropertyChanged("iscsi_iqn");
}
}
}
private string _iscsi_iqn = "";
/// <summary>
/// Specifies whether multipathing is enabled
/// First published in XenServer 7.5.
/// </summary>
public virtual bool multipathing
{
get { return _multipathing; }
set
{
if (!Helper.AreEqual(value, _multipathing))
{
_multipathing = value;
NotifyPropertyChanged("multipathing");
}
}
}
private bool _multipathing = false;
/// <summary>
/// The UEFI certificates allowing Secure Boot
/// First published in Citrix Hypervisor 8.1.
/// </summary>
public virtual string uefi_certificates
{
get { return _uefi_certificates; }
set
{
if (!Helper.AreEqual(value, _uefi_certificates))
{
_uefi_certificates = value;
NotifyPropertyChanged("uefi_certificates");
}
}
}
private string _uefi_certificates = "";
/// <summary>
/// List of certificates installed in the host
/// First published in Citrix Hypervisor 8.2.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Certificate>))]
public virtual List<XenRef<Certificate>> certificates
{
get { return _certificates; }
set
{
if (!Helper.AreEqual(value, _certificates))
{
_certificates = value;
NotifyPropertyChanged("certificates");
}
}
}
private List<XenRef<Certificate>> _certificates = new List<XenRef<Certificate>>() {};
/// <summary>
/// List of all available product editions
/// First published in Citrix Hypervisor 8.2.
/// </summary>
public virtual string[] editions
{
get { return _editions; }
set
{
if (!Helper.AreEqual(value, _editions))
{
_editions = value;
NotifyPropertyChanged("editions");
}
}
}
private string[] _editions = {};
/// <summary>
/// The set of pending guidances after applying updates
/// First published in Unreleased.
/// </summary>
public virtual List<update_guidances> pending_guidances
{
get { return _pending_guidances; }
set
{
if (!Helper.AreEqual(value, _pending_guidances))
{
_pending_guidances = value;
NotifyPropertyChanged("pending_guidances");
}
}
}
private List<update_guidances> _pending_guidances = new List<update_guidances>() {};
/// <summary>
/// True if this host has TLS verifcation enabled
/// First published in Unreleased.
/// </summary>
public virtual bool tls_verification_enabled
{
get { return _tls_verification_enabled; }
set
{
if (!Helper.AreEqual(value, _tls_verification_enabled))
{
_tls_verification_enabled = value;
NotifyPropertyChanged("tls_verification_enabled");
}
}
}
private bool _tls_verification_enabled = false;
}
}
| 49.111134 | 363 | 0.593713 | [
"BSD-2-Clause"
] | CitrixChris/xenadmin | XenModel/XenAPI/Host.cs | 240,399 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Synapse.Handlers.Legacy.Database.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("LweTpvRmOp8mBcW5grgIuqNrbz7ces0Q2F6pf0aThSI=")]
public string ConnectionString {
get {
return ((string)(this["ConnectionString"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("123456789012345")]
public string PassPhrase {
get {
return ((string)(this["PassPhrase"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("12345678")]
public string SaltValue {
get {
return ((string)(this["SaltValue"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1234567890123456")]
public string InitVector {
get {
return ((string)(this["InitVector"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("((?=.*\\bMsg\\b)|(?=.*\\bHResult\\b))(?=.*\\bLevel\\b)(?=.*\\bState\\b)")]
public string RegexErrorFilterSqlServer {
get {
return ((string)(this["RegexErrorFilterSqlServer"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string WorkRoot {
get {
return ((string)(this["WorkRoot"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string SqlPlusPath {
get {
return ((string)(this["SqlPlusPath"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SourceFiles")]
public string SourceRoot {
get {
return ((string)(this["SourceRoot"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SystemFiles\\StagedFiles")]
public string StagedRoot {
get {
return ((string)(this["StagedRoot"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SystemFiles\\CachedFiles")]
public string CachedRoot {
get {
return ((string)(this["CachedRoot"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("ProcessedFiles")]
public string ProcessedRoot {
get {
return ((string)(this["ProcessedRoot"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("(Warning:.*with compilation errors.)")]
public string RegexErrorFilterOracleCompilation {
get {
return ((string)(this["RegexErrorFilterOracleCompilation"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("MyFolderPath")]
public string FolderPath {
get {
return ((string)(this["FolderPath"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\MyApp\\ImpersonatorScript.txt")]
public string ImpersonationFilePath {
get {
return ((string)(this["ImpersonationFilePath"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("^(ORA-)|(SP2-)|(Warning:.*with compilation errors.)|(\\r\\nORA-)")]
public string RegexErrorFilterOracle {
get {
return ((string)(this["RegexErrorFilterOracle"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("http://localhost/nostromo.svc")]
public string NostromoApi {
get {
return ((string)(this["NostromoApi"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("MyRoot")]
public string FolderRoot {
get {
return ((string)(this["FolderRoot"]));
}
}
}
}
| 42.688889 | 151 | 0.613222 | [
"MIT"
] | SynapseProject/handlers.Legacy.Database.net | Synapse.Handlers.Legacy.Database/Properties/Settings.Designer.cs | 7,686 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.SecurityCenter.Settings.V1Beta1.Snippets
{
// [START securitycenter_v1beta1_generated_SecurityCenterSettingsService_CalculateEffectiveSettings_sync_flattened_resourceNames]
using Google.Cloud.SecurityCenter.Settings.V1Beta1;
public sealed partial class GeneratedSecurityCenterSettingsServiceClientSnippets
{
/// <summary>Snippet for CalculateEffectiveSettings</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CalculateEffectiveSettingsResourceNames()
{
// Create client
SecurityCenterSettingsServiceClient securityCenterSettingsServiceClient = SecurityCenterSettingsServiceClient.Create();
// Initialize request argument(s)
SettingsName name = SettingsName.FromOrganization("[ORGANIZATION]");
// Make the request
Settings response = securityCenterSettingsServiceClient.CalculateEffectiveSettings(name);
}
}
// [END securitycenter_v1beta1_generated_SecurityCenterSettingsService_CalculateEffectiveSettings_sync_flattened_resourceNames]
}
| 46.073171 | 133 | 0.746956 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.SecurityCenter.Settings.V1Beta1/Google.Cloud.SecurityCenter.Settings.V1Beta1.GeneratedSnippets/SecurityCenterSettingsServiceClient.CalculateEffectiveSettingsResourceNamesSnippet.g.cs | 1,889 | C# |
/* Copyright (c) 2009 Robert Adams
* 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.
* * The name of the copyright holder may not 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.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using LookingGlass.Comm;
using LookingGlass.Framework;
using LookingGlass.Framework.Logging;
using LookingGlass.Framework.WorkQueue;
using LookingGlass.World;
using LookingGlass.World.LL;
using OMV = OpenMetaverse;
namespace LookingGlass.World.OS {
public class OSAssetContextV1 : AssetContextBase {
private ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
string m_basePath;
string m_proxyPath = null;
// Some of the asset servers will return just the data if you put 'data' on the
// end of the URL. That is happening if this is 'true'.
bool m_dataFetch = false;
public OSAssetContextV1() : base("Unknown") {
}
public OSAssetContextV1(string name) : base(name) {
}
public override void InitializeContextFinish() {
m_basePath = World.Instance.Grids.GridParameter(Grids.Current, "OS.AssetServer.V1");
string requestFormat = World.Instance.Grids.GridParameter(Grids.Current, "OS.AssetServer.V1.Request");
if (requestFormat != null) {
// does the parameters specify the 'data' binary data request?
if (requestFormat.ToLower().Equals("data")) {
m_dataFetch = true;
}
}
if (m_basePath == null) {
m_log.Log(LogLevel.DBADERROR, "OSAssetContextV1::InitializeContextFinish: NOT BASE PATH SPECIFIED: NOT INITIALIZING");
return;
}
while (m_basePath.EndsWith("/")) {
m_basePath = m_basePath.Substring(0, m_basePath.Length-1);
}
m_proxyPath = World.Instance.Grids.GridParameter(Grids.Current, "OS.AssetServer.Proxy");
try {
string maxRequests = World.Instance.Grids.GridParameter(Grids.Current, "OS.AssetServer.MaxRequests");
if (maxRequests == null) {
m_maxOutstandingTextureRequests = 4;
}
else {
m_maxOutstandingTextureRequests = Int32.Parse(maxRequests);
}
}
catch {
m_maxOutstandingTextureRequests = 4;
}
if (m_proxyPath != null && m_proxyPath.Length == 0) m_proxyPath = null;
m_log.Log(LogLevel.DINIT, "InitializeContextFinish: base={0}, proxy={1}", m_basePath,
m_proxyPath == null ? "NULL" : m_proxyPath);
return;
}
// if it starts with our region name, it must be ours
public override bool isTextureOwner(EntityName textureEntityName) {
return textureEntityName.Name.StartsWith(m_Name + EntityName.PartSeparator);
}
public override void DoTextureLoad(EntityName textureEntityName, AssetType typ, DownloadFinishedCallback finishCall) {
EntityNameLL textureEnt = new EntityNameLL(textureEntityName);
string worldID = textureEnt.EntityPart;
OMV.UUID binID = new OMV.UUID(worldID);
if (m_basePath == null) return;
// do we already have the file?
string textureFilename = Path.Combine(CacheDirBase, textureEnt.CacheFilename);
lock (FileSystemAccessLock) {
if (File.Exists(textureFilename)) {
m_log.Log(LogLevel.DTEXTUREDETAIL, "DoTextureLoad: Texture file already exists for " + worldID);
bool hasTransparancy = CheckTextureFileForTransparancy(textureFilename);
// make the callback happen on a new thread so things don't get tangled (caller getting the callback)
Object[] finishCallParams = { finishCall, textureEntityName.Name, hasTransparancy };
m_completionWork.DoLater(FinishCallDoLater, finishCallParams);
// m_completionWork.DoLater(new FinishCallDoLater(finishCall, textureEntityName.Name, hasTransparancy));
}
else {
bool sendRequest = false;
lock (m_waiting) {
// if this is already being requested, don't waste our time
if (m_waiting.ContainsKey(binID)) {
m_log.Log(LogLevel.DTEXTUREDETAIL, "DoTextureLoad: Already waiting for " + worldID);
}
else {
WaitingInfo wi = new WaitingInfo(binID, finishCall);
wi.filename = textureFilename;
wi.type = typ;
m_waiting.Add(binID, wi);
sendRequest = true;
}
}
if (sendRequest) {
// this is here because RequestTexture might immediately call the callback
// and we should be outside the lock
m_log.Log(LogLevel.DTEXTUREDETAIL, "DoTextureLoad: Requesting: " + textureEntityName);
// m_texturePipe.RequestTexture(binID, OMV.ImageType.Normal, 50f, 0, 0, OnACDownloadFinished, false);
// m_comm.GridClient.Assets.RequestImage(binID, OMV.ImageType.Normal, 101300f, 0, 0, OnACDownloadFinished, false);
// m_comm.GridClient.Assets.RequestImage(binID, OMV.ImageType.Normal, 50f, 0, 0, OnACDownloadFinished, false);
ThrottleTextureRequests(binID);
}
}
}
return;
}
#region THROTTLE TEXTURES
// some routines to throttle the number of outstand textures requetst to see if
// libomv is getting overwhelmed by thousands of requests
Queue<OMV.UUID> m_textureQueue = new Queue<OpenMetaverse.UUID>();
int m_maxOutstandingTextureRequests = 4;
int m_currentOutstandingTextureRequests = 0;
BasicWorkQueue m_doThrottledTextureRequest = null;
private void ThrottleTextureRequests(OMV.UUID binID) {
lock (m_textureQueue) {
m_textureQueue.Enqueue(binID);
}
ThrottleTextureRequestsCheck();
}
private void ThrottleTextureRequestsCheck() {
OMV.UUID binID = OMV.UUID.Zero;
lock (m_textureQueue) {
if (m_textureQueue.Count > 0 && m_currentOutstandingTextureRequests < m_maxOutstandingTextureRequests) {
m_currentOutstandingTextureRequests++;
binID = m_textureQueue.Dequeue();
}
}
if (binID != OMV.UUID.Zero) {
if (m_doThrottledTextureRequest == null) {
m_doThrottledTextureRequest = new BasicWorkQueue("OSThrottledTexture" + m_numAssetContextBase.ToString());
}
m_doThrottledTextureRequest.DoLater(ThrottleTextureMakeRequest, binID);
}
}
/// <summary>
/// On our own thread, make the synchronous texture request from the asset server
/// </summary>
/// <param name="qInstance"></param>
/// <param name="obinID"></param>
/// <returns></returns>
private bool ThrottleTextureMakeRequest(DoLaterBase qInstance, Object obinID) {
OMV.UUID binID = (OMV.UUID)obinID;
Uri assetPath = new Uri(m_basePath + "/assets/" + binID.ToString() + (m_dataFetch ? "/data" : ""));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(assetPath);
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Timeout = 30000; // 30 second timeout
if (m_proxyPath != null) {
// configure proxy if necessary
WebProxy myProxy = new WebProxy();
myProxy.Address = new Uri(m_proxyPath);
request.Proxy = myProxy;
}
try {
m_log.Log(LogLevel.DCOMMDETAIL, "ThrottleTextureMakeRequest: requesting '{0}'", assetPath);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
m_log.Log(LogLevel.DCOMMDETAIL, "ThrottleTextureMakeRequest: request returned. resp={0}, l={1}",
response.StatusCode, response.ContentLength);
if (response.StatusCode == HttpStatusCode.OK) {
using (Stream receiveStream = response.GetResponseStream()) {
OMV.Assets.AssetTexture at;
if (m_dataFetch) {
// we're getting raw binary data
byte[] textureBuff = new byte[response.ContentLength];
receiveStream.Read(textureBuff, 0, (int)response.ContentLength);
at = new OMV.Assets.AssetTexture(binID, textureBuff);
}
else {
// receiving a serialized package
XmlSerializer xserial = new XmlSerializer(typeof(OpenSim.Framework.AssetBase));
OpenSim.Framework.AssetBase abase = (OpenSim.Framework.AssetBase)xserial.Deserialize(receiveStream);
at = new OMV.Assets.AssetTexture(binID, abase.Data);
}
ProcessDownloadFinished(OMV.TextureRequestState.Finished, at);
}
}
else {
OMV.Assets.AssetTexture at = new OMV.Assets.AssetTexture(binID, new byte[0]);
ProcessDownloadFinished(OMV.TextureRequestState.NotFound, at);
}
}
}
catch (Exception e) {
m_log.Log(LogLevel.DBADERROR, "Error fetching asset: {0}", e);
OMV.Assets.AssetTexture at = new OMV.Assets.AssetTexture(binID, new byte[0]);
ProcessDownloadFinished(OMV.TextureRequestState.NotFound, at);
}
return true;
}
protected override void CompletionWorkComplete() {
ThrottleTextureRequestsComplete();
base.CompletionWorkComplete();
}
private void ThrottleTextureRequestsComplete() {
m_currentOutstandingTextureRequests--;
ThrottleTextureRequestsCheck();
}
#endregion THROTTLE TEXTURES
}
}
| 47.854772 | 134 | 0.631406 | [
"BSD-3-Clause"
] | Misterblue/LookingGlass-Viewer | src/LookingGlass.World.OS/OSAssetContextV1.cs | 11,535 | C# |
using System;
using System.Security.Cryptography;
namespace Binsync.Core
{
public static partial class Constants
{
public static readonly RandomNumberGenerator RNG = RNGCryptoServiceProvider.Create();
public static readonly string MetaVersion = "1.0";
public const int SegmentSize = 524288; //segment size: raw chunk size, so maybe -1 because of compression for better last encrypted block if CBC?
public const int DataBeforeParity = 100;
public const int ParityCount = 20;
//public const int ArticlesBeforeMeta = 20;
//public static int MaxConnections = 16;
//public const int ReplicationSearchBounds = 10;
public const int AssuranceReplicationDefaultCount = 20;
public const int AssuranceReplicationSearchCount = 25;
public const int ReplicationAttemptCount = 20;
public static readonly Logger Logger = new Logger(Console.WriteLine);
public const int CacheSize = 100000;
public const int DiskCacheSize = 100000;
}
}
| 34.071429 | 147 | 0.774633 | [
"Unlicense"
] | retroplasma/binsync | src/Binsync.Core/Constants.cs | 954 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.